repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/installer/tests/TestUtils/NetCoreAppBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Extensions.DependencyModel; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.DotNet.CoreSetup.Test { public class NetCoreAppBuilder { public string Name { get; set; } public string Framework { get; set; } public string Runtime { get; set; } private TestApp _sourceApp; public Action<RuntimeConfig> RuntimeConfigCustomizer { get; set; } public List<RuntimeLibraryBuilder> RuntimeLibraries { get; } = new List<RuntimeLibraryBuilder>(); public List<RuntimeFallbacksBuilder> RuntimeFallbacks { get; } = new List<RuntimeFallbacksBuilder>(); internal class BuildContext { public TestApp App { get; set; } } public abstract class FileBuilder { public string Path { get; set; } public string SourcePath { get; set; } public string FileOnDiskPath { get; set; } public FileBuilder(string path) { Path = path; } internal void Build(BuildContext context) { string path = ToDiskPath(FileOnDiskPath ?? Path); string absolutePath = System.IO.Path.Combine(context.App.Location, path); if (SourcePath != null) { FileUtils.EnsureFileDirectoryExists(absolutePath); File.Copy(SourcePath, absolutePath); } else if (FileOnDiskPath == null || FileOnDiskPath.Length >= 0) { FileUtils.CreateEmptyFile(absolutePath); } } protected static string ToDiskPath(string assetPath) { return assetPath.Replace('/', System.IO.Path.DirectorySeparatorChar); } } public abstract class FileBuilder<T> : FileBuilder where T : FileBuilder { public FileBuilder(string path) : base(path) { } public T CopyFromFile(string sourcePath) { SourcePath = sourcePath; return this as T; } public T WithFileOnDiskPath(string relativePath) { FileOnDiskPath = relativePath; return this as T; } public T NotOnDisk() { FileOnDiskPath = string.Empty; return this as T; } } public class RuntimeFileBuilder : FileBuilder<RuntimeFileBuilder> { public string AssemblyVersion { get; set; } public string FileVersion { get; set; } public RuntimeFileBuilder(string path) : base(path) { } public RuntimeFileBuilder WithVersion(string assemblyVersion, string fileVersion) { AssemblyVersion = assemblyVersion; FileVersion = fileVersion; return this; } internal new RuntimeFile Build(BuildContext context) { base.Build(context); return new RuntimeFile(Path, AssemblyVersion, FileVersion); } } public class ResourceAssemblyBuilder : FileBuilder<ResourceAssemblyBuilder> { public string Locale { get; set; } public ResourceAssemblyBuilder(string path) : base(path) { int i = path.IndexOf('/'); if (i > 0) { Locale = path.Substring(0, i); } } public ResourceAssemblyBuilder WithLocale(string locale) { Locale = locale; return this; } internal new ResourceAssembly Build(BuildContext context) { base.Build(context); return new ResourceAssembly(Path, Locale); } } public class RuntimeAssetGroupBuilder { public string Runtime { get; set; } public bool IncludeMainAssembly { get; set; } public List<RuntimeFileBuilder> Assets { get; } = new List<RuntimeFileBuilder>(); public RuntimeAssetGroupBuilder(string runtime) { Runtime = runtime ?? string.Empty; } public RuntimeAssetGroupBuilder WithMainAssembly() { IncludeMainAssembly = true; return this; } public RuntimeAssetGroupBuilder WithAsset(RuntimeFileBuilder asset) { Assets.Add(asset); return this; } public RuntimeAssetGroupBuilder WithAsset(string path, Action<RuntimeFileBuilder> customizer = null) { RuntimeFileBuilder runtimeFile = new RuntimeFileBuilder(path); customizer?.Invoke(runtimeFile); return WithAsset(runtimeFile); } internal RuntimeAssetGroup Build(BuildContext context) { IEnumerable<RuntimeFileBuilder> assets = Assets; if (IncludeMainAssembly) { assets = assets.Append(new RuntimeFileBuilder(Path.GetFileName(context.App.AppDll))); } return new RuntimeAssetGroup( Runtime, assets.Select(a => a.Build(context))); } } public enum RuntimeLibraryType { project, package } public class RuntimeLibraryBuilder { public string Type { get; set; } public string Name { get; set; } public string Version { get; set; } public List<RuntimeAssetGroupBuilder> AssemblyGroups { get; } = new List<RuntimeAssetGroupBuilder>(); public List<RuntimeAssetGroupBuilder> NativeLibraryGroups { get; } = new List<RuntimeAssetGroupBuilder>(); public List<ResourceAssemblyBuilder> ResourceAssemblies { get; } = new List<ResourceAssemblyBuilder>(); public RuntimeLibraryBuilder(RuntimeLibraryType type, string name, string version) { Type = type.ToString(); Name = name; Version = version; } public RuntimeLibraryBuilder WithAssemblyGroup(string runtime, Action<RuntimeAssetGroupBuilder> customizer = null) { return WithRuntimeAssetGroup(runtime, AssemblyGroups, customizer); } public RuntimeLibraryBuilder WithNativeLibraryGroup(string runtime, Action<RuntimeAssetGroupBuilder> customizer = null) { return WithRuntimeAssetGroup(runtime, NativeLibraryGroups, customizer); } private RuntimeLibraryBuilder WithRuntimeAssetGroup( string runtime, IList<RuntimeAssetGroupBuilder> list, Action<RuntimeAssetGroupBuilder> customizer) { RuntimeAssetGroupBuilder runtimeAssetGroup = new RuntimeAssetGroupBuilder(runtime); customizer?.Invoke(runtimeAssetGroup); list.Add(runtimeAssetGroup); return this; } public RuntimeLibraryBuilder WithResourceAssembly(string path, Action<ResourceAssemblyBuilder> customizer = null) { ResourceAssemblyBuilder resourceAssembly = new ResourceAssemblyBuilder(path); customizer?.Invoke(resourceAssembly); ResourceAssemblies.Add(resourceAssembly); return this; } internal RuntimeLibrary Build(BuildContext context) { return new RuntimeLibrary( Type, Name, Version, string.Empty, AssemblyGroups.Select(g => g.Build(context)).ToList(), NativeLibraryGroups.Select(g => g.Build(context)).ToList(), ResourceAssemblies.Select(ra => ra.Build(context)).ToList(), Enumerable.Empty<Dependency>(), false); } } public class RuntimeFallbacksBuilder { public string Runtime { get; set; } public List<string> Fallbacks { get; } = new List<string>(); public RuntimeFallbacksBuilder(string runtime, params string[] fallbacks) { Runtime = runtime; Fallbacks.AddRange(fallbacks); } public RuntimeFallbacksBuilder WithFallback(params string[] fallback) { Fallbacks.AddRange(fallback); return this; } internal RuntimeFallbacks Build() { return new RuntimeFallbacks(Runtime, Fallbacks); } } public static NetCoreAppBuilder PortableForNETCoreApp(TestApp sourceApp) { return new NetCoreAppBuilder() { _sourceApp = sourceApp, Name = sourceApp.Name, Framework = ".NETCoreApp,Version=v3.0", Runtime = null }; } public static NetCoreAppBuilder ForNETCoreApp(string name, string runtime) { return new NetCoreAppBuilder() { _sourceApp = null, Name = name, Framework = ".NETCoreApp,Version=v3.0", Runtime = runtime }; } public NetCoreAppBuilder WithRuntimeConfig(Action<RuntimeConfig> runtimeConfigCustomizer) { RuntimeConfigCustomizer = runtimeConfigCustomizer; return this; } public NetCoreAppBuilder WithRuntimeLibrary( RuntimeLibraryType type, string name, string version, Action<RuntimeLibraryBuilder> customizer = null) { RuntimeLibraryBuilder runtimeLibrary = new RuntimeLibraryBuilder(type, name, version); customizer?.Invoke(runtimeLibrary); RuntimeLibraries.Add(runtimeLibrary); return this; } public NetCoreAppBuilder WithProject(string name, string version, Action<RuntimeLibraryBuilder> customizer = null) { return WithRuntimeLibrary(RuntimeLibraryType.project, name, version, customizer); } public NetCoreAppBuilder WithProject(Action<RuntimeLibraryBuilder> customizer = null) { return WithRuntimeLibrary(RuntimeLibraryType.project, Name, "1.0.0", customizer); } public NetCoreAppBuilder WithPackage(string name, string version, Action<RuntimeLibraryBuilder> customizer = null) { return WithRuntimeLibrary(RuntimeLibraryType.package, name, version, customizer); } public NetCoreAppBuilder WithRuntimeFallbacks(string runtime, params string[] fallbacks) { RuntimeFallbacks.Add(new RuntimeFallbacksBuilder(runtime, fallbacks)); return this; } public NetCoreAppBuilder WithStandardRuntimeFallbacks() { return WithRuntimeFallbacks("win10-x64", "win10", "win-x64", "win", "any") .WithRuntimeFallbacks("win10-x86", "win10", "win-x86", "win", "any") .WithRuntimeFallbacks("win10", "win", "any") .WithRuntimeFallbacks("win-x64", "win", "any") .WithRuntimeFallbacks("win-x86", "win", "any") .WithRuntimeFallbacks("win", "any") .WithRuntimeFallbacks("linux-x64", "linux", "any") .WithRuntimeFallbacks("linux", "any"); } public NetCoreAppBuilder WithCustomizer(Action<NetCoreAppBuilder> customizer) { customizer?.Invoke(this); return this; } private DependencyContext BuildDependencyContext(BuildContext context) { return new DependencyContext( new TargetInfo(Framework, Runtime, null, Runtime == null), CompilationOptions.Default, Enumerable.Empty<CompilationLibrary>(), RuntimeLibraries.Select(rl => rl.Build(context)), RuntimeFallbacks.Select(rf => rf.Build())); } public TestApp Build() { return Build(_sourceApp.Copy()); } public TestApp Build(TestApp testApp) { RuntimeConfig runtimeConfig = null; if (File.Exists(testApp.RuntimeConfigJson)) { runtimeConfig = RuntimeConfig.FromFile(testApp.RuntimeConfigJson); } else if (RuntimeConfigCustomizer != null) { runtimeConfig = new RuntimeConfig(testApp.RuntimeConfigJson); } if (runtimeConfig != null) { RuntimeConfigCustomizer?.Invoke(runtimeConfig); runtimeConfig.Save(); } BuildContext buildContext = new BuildContext() { App = testApp }; DependencyContext dependencyContext = BuildDependencyContext(buildContext); DependencyContextWriter writer = new DependencyContextWriter(); using (FileStream stream = new FileStream(testApp.DepsJson, FileMode.Create)) { writer.Write(dependencyContext, stream); } return testApp; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Extensions.DependencyModel; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.DotNet.CoreSetup.Test { public class NetCoreAppBuilder { public string Name { get; set; } public string Framework { get; set; } public string Runtime { get; set; } private TestApp _sourceApp; public Action<RuntimeConfig> RuntimeConfigCustomizer { get; set; } public List<RuntimeLibraryBuilder> RuntimeLibraries { get; } = new List<RuntimeLibraryBuilder>(); public List<RuntimeFallbacksBuilder> RuntimeFallbacks { get; } = new List<RuntimeFallbacksBuilder>(); internal class BuildContext { public TestApp App { get; set; } } public abstract class FileBuilder { public string Path { get; set; } public string SourcePath { get; set; } public string FileOnDiskPath { get; set; } public FileBuilder(string path) { Path = path; } internal void Build(BuildContext context) { string path = ToDiskPath(FileOnDiskPath ?? Path); string absolutePath = System.IO.Path.Combine(context.App.Location, path); if (SourcePath != null) { FileUtils.EnsureFileDirectoryExists(absolutePath); File.Copy(SourcePath, absolutePath); } else if (FileOnDiskPath == null || FileOnDiskPath.Length >= 0) { FileUtils.CreateEmptyFile(absolutePath); } } protected static string ToDiskPath(string assetPath) { return assetPath.Replace('/', System.IO.Path.DirectorySeparatorChar); } } public abstract class FileBuilder<T> : FileBuilder where T : FileBuilder { public FileBuilder(string path) : base(path) { } public T CopyFromFile(string sourcePath) { SourcePath = sourcePath; return this as T; } public T WithFileOnDiskPath(string relativePath) { FileOnDiskPath = relativePath; return this as T; } public T NotOnDisk() { FileOnDiskPath = string.Empty; return this as T; } } public class RuntimeFileBuilder : FileBuilder<RuntimeFileBuilder> { public string AssemblyVersion { get; set; } public string FileVersion { get; set; } public RuntimeFileBuilder(string path) : base(path) { } public RuntimeFileBuilder WithVersion(string assemblyVersion, string fileVersion) { AssemblyVersion = assemblyVersion; FileVersion = fileVersion; return this; } internal new RuntimeFile Build(BuildContext context) { base.Build(context); return new RuntimeFile(Path, AssemblyVersion, FileVersion); } } public class ResourceAssemblyBuilder : FileBuilder<ResourceAssemblyBuilder> { public string Locale { get; set; } public ResourceAssemblyBuilder(string path) : base(path) { int i = path.IndexOf('/'); if (i > 0) { Locale = path.Substring(0, i); } } public ResourceAssemblyBuilder WithLocale(string locale) { Locale = locale; return this; } internal new ResourceAssembly Build(BuildContext context) { base.Build(context); return new ResourceAssembly(Path, Locale); } } public class RuntimeAssetGroupBuilder { public string Runtime { get; set; } public bool IncludeMainAssembly { get; set; } public List<RuntimeFileBuilder> Assets { get; } = new List<RuntimeFileBuilder>(); public RuntimeAssetGroupBuilder(string runtime) { Runtime = runtime ?? string.Empty; } public RuntimeAssetGroupBuilder WithMainAssembly() { IncludeMainAssembly = true; return this; } public RuntimeAssetGroupBuilder WithAsset(RuntimeFileBuilder asset) { Assets.Add(asset); return this; } public RuntimeAssetGroupBuilder WithAsset(string path, Action<RuntimeFileBuilder> customizer = null) { RuntimeFileBuilder runtimeFile = new RuntimeFileBuilder(path); customizer?.Invoke(runtimeFile); return WithAsset(runtimeFile); } internal RuntimeAssetGroup Build(BuildContext context) { IEnumerable<RuntimeFileBuilder> assets = Assets; if (IncludeMainAssembly) { assets = assets.Append(new RuntimeFileBuilder(Path.GetFileName(context.App.AppDll))); } return new RuntimeAssetGroup( Runtime, assets.Select(a => a.Build(context))); } } public enum RuntimeLibraryType { project, package } public class RuntimeLibraryBuilder { public string Type { get; set; } public string Name { get; set; } public string Version { get; set; } public List<RuntimeAssetGroupBuilder> AssemblyGroups { get; } = new List<RuntimeAssetGroupBuilder>(); public List<RuntimeAssetGroupBuilder> NativeLibraryGroups { get; } = new List<RuntimeAssetGroupBuilder>(); public List<ResourceAssemblyBuilder> ResourceAssemblies { get; } = new List<ResourceAssemblyBuilder>(); public RuntimeLibraryBuilder(RuntimeLibraryType type, string name, string version) { Type = type.ToString(); Name = name; Version = version; } public RuntimeLibraryBuilder WithAssemblyGroup(string runtime, Action<RuntimeAssetGroupBuilder> customizer = null) { return WithRuntimeAssetGroup(runtime, AssemblyGroups, customizer); } public RuntimeLibraryBuilder WithNativeLibraryGroup(string runtime, Action<RuntimeAssetGroupBuilder> customizer = null) { return WithRuntimeAssetGroup(runtime, NativeLibraryGroups, customizer); } private RuntimeLibraryBuilder WithRuntimeAssetGroup( string runtime, IList<RuntimeAssetGroupBuilder> list, Action<RuntimeAssetGroupBuilder> customizer) { RuntimeAssetGroupBuilder runtimeAssetGroup = new RuntimeAssetGroupBuilder(runtime); customizer?.Invoke(runtimeAssetGroup); list.Add(runtimeAssetGroup); return this; } public RuntimeLibraryBuilder WithResourceAssembly(string path, Action<ResourceAssemblyBuilder> customizer = null) { ResourceAssemblyBuilder resourceAssembly = new ResourceAssemblyBuilder(path); customizer?.Invoke(resourceAssembly); ResourceAssemblies.Add(resourceAssembly); return this; } internal RuntimeLibrary Build(BuildContext context) { return new RuntimeLibrary( Type, Name, Version, string.Empty, AssemblyGroups.Select(g => g.Build(context)).ToList(), NativeLibraryGroups.Select(g => g.Build(context)).ToList(), ResourceAssemblies.Select(ra => ra.Build(context)).ToList(), Enumerable.Empty<Dependency>(), false); } } public class RuntimeFallbacksBuilder { public string Runtime { get; set; } public List<string> Fallbacks { get; } = new List<string>(); public RuntimeFallbacksBuilder(string runtime, params string[] fallbacks) { Runtime = runtime; Fallbacks.AddRange(fallbacks); } public RuntimeFallbacksBuilder WithFallback(params string[] fallback) { Fallbacks.AddRange(fallback); return this; } internal RuntimeFallbacks Build() { return new RuntimeFallbacks(Runtime, Fallbacks); } } public static NetCoreAppBuilder PortableForNETCoreApp(TestApp sourceApp) { return new NetCoreAppBuilder() { _sourceApp = sourceApp, Name = sourceApp.Name, Framework = ".NETCoreApp,Version=v3.0", Runtime = null }; } public static NetCoreAppBuilder ForNETCoreApp(string name, string runtime) { return new NetCoreAppBuilder() { _sourceApp = null, Name = name, Framework = ".NETCoreApp,Version=v3.0", Runtime = runtime }; } public NetCoreAppBuilder WithRuntimeConfig(Action<RuntimeConfig> runtimeConfigCustomizer) { RuntimeConfigCustomizer = runtimeConfigCustomizer; return this; } public NetCoreAppBuilder WithRuntimeLibrary( RuntimeLibraryType type, string name, string version, Action<RuntimeLibraryBuilder> customizer = null) { RuntimeLibraryBuilder runtimeLibrary = new RuntimeLibraryBuilder(type, name, version); customizer?.Invoke(runtimeLibrary); RuntimeLibraries.Add(runtimeLibrary); return this; } public NetCoreAppBuilder WithProject(string name, string version, Action<RuntimeLibraryBuilder> customizer = null) { return WithRuntimeLibrary(RuntimeLibraryType.project, name, version, customizer); } public NetCoreAppBuilder WithProject(Action<RuntimeLibraryBuilder> customizer = null) { return WithRuntimeLibrary(RuntimeLibraryType.project, Name, "1.0.0", customizer); } public NetCoreAppBuilder WithPackage(string name, string version, Action<RuntimeLibraryBuilder> customizer = null) { return WithRuntimeLibrary(RuntimeLibraryType.package, name, version, customizer); } public NetCoreAppBuilder WithRuntimeFallbacks(string runtime, params string[] fallbacks) { RuntimeFallbacks.Add(new RuntimeFallbacksBuilder(runtime, fallbacks)); return this; } public NetCoreAppBuilder WithStandardRuntimeFallbacks() { return WithRuntimeFallbacks("win10-x64", "win10", "win-x64", "win", "any") .WithRuntimeFallbacks("win10-x86", "win10", "win-x86", "win", "any") .WithRuntimeFallbacks("win10", "win", "any") .WithRuntimeFallbacks("win-x64", "win", "any") .WithRuntimeFallbacks("win-x86", "win", "any") .WithRuntimeFallbacks("win", "any") .WithRuntimeFallbacks("linux-x64", "linux", "any") .WithRuntimeFallbacks("linux", "any"); } public NetCoreAppBuilder WithCustomizer(Action<NetCoreAppBuilder> customizer) { customizer?.Invoke(this); return this; } private DependencyContext BuildDependencyContext(BuildContext context) { return new DependencyContext( new TargetInfo(Framework, Runtime, null, Runtime == null), CompilationOptions.Default, Enumerable.Empty<CompilationLibrary>(), RuntimeLibraries.Select(rl => rl.Build(context)), RuntimeFallbacks.Select(rf => rf.Build())); } public TestApp Build() { return Build(_sourceApp.Copy()); } public TestApp Build(TestApp testApp) { RuntimeConfig runtimeConfig = null; if (File.Exists(testApp.RuntimeConfigJson)) { runtimeConfig = RuntimeConfig.FromFile(testApp.RuntimeConfigJson); } else if (RuntimeConfigCustomizer != null) { runtimeConfig = new RuntimeConfig(testApp.RuntimeConfigJson); } if (runtimeConfig != null) { RuntimeConfigCustomizer?.Invoke(runtimeConfig); runtimeConfig.Save(); } BuildContext buildContext = new BuildContext() { App = testApp }; DependencyContext dependencyContext = BuildDependencyContext(buildContext); DependencyContextWriter writer = new DependencyContextWriter(); using (FileStream stream = new FileStream(testApp.DepsJson, FileMode.Create)) { writer.Write(dependencyContext, stream); } return testApp; } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Methodical/divrem/div/decimaldiv_cs_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="decimaldiv.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="decimaldiv.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/coreclr/dlls/mscordbi/mscordbi.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // MSCorDBI.cpp // // COM+ Debugging Services -- Debugger Interface DLL // // Dll* routines for entry points, and support for COM framework. // //***************************************************************************** #include "stdafx.h" extern BOOL WINAPI DbgDllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved); //***************************************************************************** // The main dll entry point for this module. This routine is called by the // OS when the dll gets loaded. Control is simply deferred to the main code. //***************************************************************************** extern "C" #ifdef TARGET_UNIX DLLEXPORT // For Win32 PAL LoadLibrary emulation #endif BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { // Defer to the main debugging code. return DbgDllMain(hInstance, dwReason, lpReserved); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // MSCorDBI.cpp // // COM+ Debugging Services -- Debugger Interface DLL // // Dll* routines for entry points, and support for COM framework. // //***************************************************************************** #include "stdafx.h" extern BOOL WINAPI DbgDllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved); //***************************************************************************** // The main dll entry point for this module. This routine is called by the // OS when the dll gets loaded. Control is simply deferred to the main code. //***************************************************************************** extern "C" #ifdef TARGET_UNIX DLLEXPORT // For Win32 PAL LoadLibrary emulation #endif BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { // Defer to the main debugging code. return DbgDllMain(hInstance, dwReason, lpReserved); }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Reflection.MetadataLoadContext/tests/src/Tests/Type/TypeTests.TypeFactories.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using SampleMetadata; using Xunit; namespace System.Reflection.Tests { public static partial class TypeTests { [Fact] public static void TestMakeArray() { Type et = typeof(int).Project(); Type t = et.MakeArrayType(); Assert.True(t.IsSZArray()); Assert.Equal(et, t.GetElementType()); t.TestSzArrayInvariants(); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(3)] public static void TestMakeMdArray(int rank) { Type et = typeof(int).Project(); Type t = et.MakeArrayType(rank); Assert.True(t.IsVariableBoundArray()); Assert.Equal(rank, t.GetArrayRank()); Assert.Equal(et, t.GetElementType()); t.TestMdArrayInvariants(); } [Fact] public static void TestMakeByRef() { Type et = typeof(int).Project(); Type t = et.MakeByRefType(); Assert.True(t.IsByRef); Assert.Equal(et, t.GetElementType()); t.TestByRefInvariants(); } [Fact] public static void TestMakePointer() { Type et = typeof(int).Project(); Type t = et.MakePointerType(); Assert.True(t.IsPointer); Assert.Equal(et, t.GetElementType()); t.TestPointerInvariants(); } [Fact] public static void TestMakeGenericType() { Type gt = typeof(GenericClass3<,,>).Project(); Type[] gas = { typeof(int).Project(), typeof(string).Project(), typeof(double).Project() }; Type t = gt.MakeGenericType(gas); Assert.True(t.IsConstructedGenericType); Assert.Equal(gt, t.GetGenericTypeDefinition()); Assert.Equal<Type>(gas, t.GenericTypeArguments); t.TestConstructedGenericTypeInvariants(); } [Fact] public static void TestMakeGenericTypeParameter() { Type gt = typeof(GenericClass3<,,>).Project(); Type[] gps = gt.GetTypeInfo().GenericTypeParameters; Assert.Equal(3, gps.Length); Assert.Equal("T", gps[0].Name); Assert.Equal("U", gps[1].Name); Assert.Equal("V", gps[2].Name); foreach (Type gp in gps) { gp.TestGenericTypeParameterInvariants(); } } [Fact] public static void TestMakeArrayNegativeIndex() { Type t = typeof(object).Project(); Assert.Throws<IndexOutOfRangeException>(() => t.MakeArrayType(rank: -1)); } [Fact] public static void TestMakeGenericTypeNegativeInput() { Type t = typeof(GenericClass3<,,>).Project(); Type[] typeArguments = null; Assert.Throws<ArgumentNullException>(() => t.MakeGenericType(typeArguments)); typeArguments = new Type[2]; // Wrong number of arguments Assert.Throws<ArgumentException>(() => t.MakeGenericType(typeArguments)); typeArguments = new Type[4]; // Wrong number of arguments Assert.Throws<ArgumentException>(() => t.MakeGenericType(typeArguments)); typeArguments = new Type[] { typeof(int).Project(), null, typeof(int).Project() }; // Null embedded in array. Assert.Throws<ArgumentNullException>(() => t.MakeGenericType(typeArguments)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using SampleMetadata; using Xunit; namespace System.Reflection.Tests { public static partial class TypeTests { [Fact] public static void TestMakeArray() { Type et = typeof(int).Project(); Type t = et.MakeArrayType(); Assert.True(t.IsSZArray()); Assert.Equal(et, t.GetElementType()); t.TestSzArrayInvariants(); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(3)] public static void TestMakeMdArray(int rank) { Type et = typeof(int).Project(); Type t = et.MakeArrayType(rank); Assert.True(t.IsVariableBoundArray()); Assert.Equal(rank, t.GetArrayRank()); Assert.Equal(et, t.GetElementType()); t.TestMdArrayInvariants(); } [Fact] public static void TestMakeByRef() { Type et = typeof(int).Project(); Type t = et.MakeByRefType(); Assert.True(t.IsByRef); Assert.Equal(et, t.GetElementType()); t.TestByRefInvariants(); } [Fact] public static void TestMakePointer() { Type et = typeof(int).Project(); Type t = et.MakePointerType(); Assert.True(t.IsPointer); Assert.Equal(et, t.GetElementType()); t.TestPointerInvariants(); } [Fact] public static void TestMakeGenericType() { Type gt = typeof(GenericClass3<,,>).Project(); Type[] gas = { typeof(int).Project(), typeof(string).Project(), typeof(double).Project() }; Type t = gt.MakeGenericType(gas); Assert.True(t.IsConstructedGenericType); Assert.Equal(gt, t.GetGenericTypeDefinition()); Assert.Equal<Type>(gas, t.GenericTypeArguments); t.TestConstructedGenericTypeInvariants(); } [Fact] public static void TestMakeGenericTypeParameter() { Type gt = typeof(GenericClass3<,,>).Project(); Type[] gps = gt.GetTypeInfo().GenericTypeParameters; Assert.Equal(3, gps.Length); Assert.Equal("T", gps[0].Name); Assert.Equal("U", gps[1].Name); Assert.Equal("V", gps[2].Name); foreach (Type gp in gps) { gp.TestGenericTypeParameterInvariants(); } } [Fact] public static void TestMakeArrayNegativeIndex() { Type t = typeof(object).Project(); Assert.Throws<IndexOutOfRangeException>(() => t.MakeArrayType(rank: -1)); } [Fact] public static void TestMakeGenericTypeNegativeInput() { Type t = typeof(GenericClass3<,,>).Project(); Type[] typeArguments = null; Assert.Throws<ArgumentNullException>(() => t.MakeGenericType(typeArguments)); typeArguments = new Type[2]; // Wrong number of arguments Assert.Throws<ArgumentException>(() => t.MakeGenericType(typeArguments)); typeArguments = new Type[4]; // Wrong number of arguments Assert.Throws<ArgumentException>(() => t.MakeGenericType(typeArguments)); typeArguments = new Type[] { typeof(int).Project(), null, typeof(int).Project() }; // Null embedded in array. Assert.Throws<ArgumentNullException>(() => t.MakeGenericType(typeArguments)); } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/Common/src/Interop/Unix/System.Native/Interop.Stat.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Sys { // Even though csc will by default use a sequential layout, a CS0649 warning as error // is produced for un-assigned fields when no StructLayout is specified. // // Explicitly saying Sequential disables that warning/error for consumers which only // use Stat in debug builds. [StructLayout(LayoutKind.Sequential)] internal struct FileStatus { internal FileStatusFlags Flags; internal int Mode; internal uint Uid; internal uint Gid; internal long Size; internal long ATime; internal long ATimeNsec; internal long MTime; internal long MTimeNsec; internal long CTime; internal long CTimeNsec; internal long BirthTime; internal long BirthTimeNsec; internal long Dev; internal long Ino; internal uint UserFlags; } internal static class FileTypes { internal const int S_IFMT = 0xF000; internal const int S_IFIFO = 0x1000; internal const int S_IFCHR = 0x2000; internal const int S_IFDIR = 0x4000; internal const int S_IFREG = 0x8000; internal const int S_IFLNK = 0xA000; internal const int S_IFSOCK = 0xC000; } [Flags] internal enum FileStatusFlags { None = 0, HasBirthTime = 1, } [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FStat", SetLastError = true)] internal static partial int FStat(SafeHandle fd, out FileStatus output); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] internal static partial int Stat(string path, out FileStatus output); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LStat", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] internal static partial int LStat(string path, out FileStatus output); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Sys { // Even though csc will by default use a sequential layout, a CS0649 warning as error // is produced for un-assigned fields when no StructLayout is specified. // // Explicitly saying Sequential disables that warning/error for consumers which only // use Stat in debug builds. [StructLayout(LayoutKind.Sequential)] internal struct FileStatus { internal FileStatusFlags Flags; internal int Mode; internal uint Uid; internal uint Gid; internal long Size; internal long ATime; internal long ATimeNsec; internal long MTime; internal long MTimeNsec; internal long CTime; internal long CTimeNsec; internal long BirthTime; internal long BirthTimeNsec; internal long Dev; internal long Ino; internal uint UserFlags; } internal static class FileTypes { internal const int S_IFMT = 0xF000; internal const int S_IFIFO = 0x1000; internal const int S_IFCHR = 0x2000; internal const int S_IFDIR = 0x4000; internal const int S_IFREG = 0x8000; internal const int S_IFLNK = 0xA000; internal const int S_IFSOCK = 0xC000; } [Flags] internal enum FileStatusFlags { None = 0, HasBirthTime = 1, } [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FStat", SetLastError = true)] internal static partial int FStat(SafeHandle fd, out FileStatus output); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] internal static partial int Stat(string path, out FileStatus output); [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LStat", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] internal static partial int LStat(string path, out FileStatus output); } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Regression/CLR-x86-JIT/V1.2-M01/b02345/b02345.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/coreclr/jit/decomposelongs.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX DecomposeLongs XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #ifndef _DECOMPOSELONGS_H_ #define _DECOMPOSELONGS_H_ #include "compiler.h" class DecomposeLongs { public: DecomposeLongs(Compiler* compiler) : m_compiler(compiler) { } void PrepareForDecomposition(); void DecomposeBlock(BasicBlock* block); static void DecomposeRange(Compiler* compiler, LIR::Range& range); private: inline LIR::Range& Range() const { return *m_range; } void PromoteLongVars(); // Driver functions void DecomposeRangeHelper(); GenTree* DecomposeNode(GenTree* tree); // Per-node type decompose cases GenTree* DecomposeLclVar(LIR::Use& use); GenTree* DecomposeLclFld(LIR::Use& use); GenTree* DecomposeStoreLclVar(LIR::Use& use); GenTree* DecomposeStoreLclFld(LIR::Use& use); GenTree* DecomposeCast(LIR::Use& use); GenTree* DecomposeCnsLng(LIR::Use& use); GenTree* DecomposeFieldList(GenTreeFieldList* fieldList, GenTreeOp* longNode); GenTree* DecomposeCall(LIR::Use& use); GenTree* DecomposeInd(LIR::Use& use); GenTree* DecomposeStoreInd(LIR::Use& use); GenTree* DecomposeNot(LIR::Use& use); GenTree* DecomposeNeg(LIR::Use& use); GenTree* DecomposeArith(LIR::Use& use); GenTree* DecomposeShift(LIR::Use& use); GenTree* DecomposeRotate(LIR::Use& use); GenTree* DecomposeMul(LIR::Use& use); GenTree* DecomposeUMod(LIR::Use& use); #ifdef FEATURE_HW_INTRINSICS GenTree* DecomposeHWIntrinsic(LIR::Use& use); GenTree* DecomposeHWIntrinsicGetElement(LIR::Use& use, GenTreeHWIntrinsic* node); #endif // FEATURE_HW_INTRINSICS GenTree* OptimizeCastFromDecomposedLong(GenTreeCast* cast, GenTree* nextNode); // Helper functions GenTree* FinalizeDecomposition(LIR::Use& use, GenTree* loResult, GenTree* hiResult, GenTree* insertResultAfter); GenTree* RepresentOpAsLocalVar(GenTree* op, GenTree* user, GenTree** edge); GenTree* EnsureIntSized(GenTree* node, bool signExtend); GenTree* StoreNodeToVar(LIR::Use& use); static genTreeOps GetHiOper(genTreeOps oper); static genTreeOps GetLoOper(genTreeOps oper); // Data Compiler* m_compiler; LIR::Range* m_range; }; #endif // _DECOMPOSELONGS_H_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX DecomposeLongs XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #ifndef _DECOMPOSELONGS_H_ #define _DECOMPOSELONGS_H_ #include "compiler.h" class DecomposeLongs { public: DecomposeLongs(Compiler* compiler) : m_compiler(compiler) { } void PrepareForDecomposition(); void DecomposeBlock(BasicBlock* block); static void DecomposeRange(Compiler* compiler, LIR::Range& range); private: inline LIR::Range& Range() const { return *m_range; } void PromoteLongVars(); // Driver functions void DecomposeRangeHelper(); GenTree* DecomposeNode(GenTree* tree); // Per-node type decompose cases GenTree* DecomposeLclVar(LIR::Use& use); GenTree* DecomposeLclFld(LIR::Use& use); GenTree* DecomposeStoreLclVar(LIR::Use& use); GenTree* DecomposeStoreLclFld(LIR::Use& use); GenTree* DecomposeCast(LIR::Use& use); GenTree* DecomposeCnsLng(LIR::Use& use); GenTree* DecomposeFieldList(GenTreeFieldList* fieldList, GenTreeOp* longNode); GenTree* DecomposeCall(LIR::Use& use); GenTree* DecomposeInd(LIR::Use& use); GenTree* DecomposeStoreInd(LIR::Use& use); GenTree* DecomposeNot(LIR::Use& use); GenTree* DecomposeNeg(LIR::Use& use); GenTree* DecomposeArith(LIR::Use& use); GenTree* DecomposeShift(LIR::Use& use); GenTree* DecomposeRotate(LIR::Use& use); GenTree* DecomposeMul(LIR::Use& use); GenTree* DecomposeUMod(LIR::Use& use); #ifdef FEATURE_HW_INTRINSICS GenTree* DecomposeHWIntrinsic(LIR::Use& use); GenTree* DecomposeHWIntrinsicGetElement(LIR::Use& use, GenTreeHWIntrinsic* node); #endif // FEATURE_HW_INTRINSICS GenTree* OptimizeCastFromDecomposedLong(GenTreeCast* cast, GenTree* nextNode); // Helper functions GenTree* FinalizeDecomposition(LIR::Use& use, GenTree* loResult, GenTree* hiResult, GenTree* insertResultAfter); GenTree* RepresentOpAsLocalVar(GenTree* op, GenTree* user, GenTree** edge); GenTree* EnsureIntSized(GenTree* node, bool signExtend); GenTree* StoreNodeToVar(LIR::Use& use); static genTreeOps GetHiOper(genTreeOps oper); static genTreeOps GetLoOper(genTreeOps oper); // Data Compiler* m_compiler; LIR::Range* m_range; }; #endif // _DECOMPOSELONGS_H_
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="nonlocalgotoinatryblockinahandler.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="nonlocalgotoinatryblockinahandler.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObject.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Linq.Expressions; namespace System.Dynamic { /// <summary> /// Represents the dynamic binding and a binding logic of an object participating in the dynamic binding. /// </summary> public class DynamicMetaObject { /// <summary> /// Represents an empty array of type <see cref="DynamicMetaObject"/>. This field is read-only. /// </summary> public static readonly DynamicMetaObject[] EmptyMetaObjects = Array.Empty<DynamicMetaObject>(); /// <summary> /// Initializes a new instance of the <see cref="DynamicMetaObject"/> class. /// </summary> /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param> /// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param> public DynamicMetaObject(Expression expression, BindingRestrictions restrictions) { ContractUtils.RequiresNotNull(expression, nameof(expression)); ContractUtils.RequiresNotNull(restrictions, nameof(restrictions)); Expression = expression; Restrictions = restrictions; } /// <summary> /// Initializes a new instance of the <see cref="DynamicMetaObject"/> class. /// </summary> /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param> /// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param> /// <param name="value">The runtime value represented by the <see cref="DynamicMetaObject"/>.</param> public DynamicMetaObject(Expression expression, BindingRestrictions restrictions, object value) : this(expression, restrictions) { _value = value; } // having sentinel value means having no value. (this way we do not need a separate hasValue field) private static readonly object s_noValueSentinel = new object(); private readonly object _value = s_noValueSentinel; /// <summary> /// The expression representing the <see cref="DynamicMetaObject"/> during the dynamic binding process. /// </summary> public Expression Expression { get; } /// <summary> /// The set of binding restrictions under which the binding is valid. /// </summary> public BindingRestrictions Restrictions { get; } /// <summary> /// The runtime value represented by this <see cref="DynamicMetaObject"/>. /// </summary> public object? Value => HasValue ? _value : null; /// <summary> /// Gets a value indicating whether the <see cref="DynamicMetaObject"/> has the runtime value. /// </summary> public bool HasValue => _value != s_noValueSentinel; /// <summary> /// Gets the <see cref="Type"/> of the runtime value or null if the <see cref="DynamicMetaObject"/> has no value associated with it. /// </summary> public Type? RuntimeType { get { if (HasValue) { Type ct = Expression.Type; // valuetype at compile time, type cannot change. if (ct.IsValueType) { return ct; } return Value?.GetType(); } else { return null; } } } /// <summary> /// Gets the limit type of the <see cref="DynamicMetaObject"/>. /// </summary> /// <remarks>Represents the most specific type known about the object represented by the <see cref="DynamicMetaObject"/>. <see cref="RuntimeType"/> if runtime value is available, a type of the <see cref="Expression"/> otherwise.</remarks> public Type LimitType => RuntimeType ?? Expression.Type; /// <summary> /// Performs the binding of the dynamic conversion operation. /// </summary> /// <param name="binder">An instance of the <see cref="ConvertBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindConvert(ConvertBinder binder) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackConvert(this); } /// <summary> /// Performs the binding of the dynamic get member operation. /// </summary> /// <param name="binder">An instance of the <see cref="GetMemberBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindGetMember(GetMemberBinder binder) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackGetMember(this); } /// <summary> /// Performs the binding of the dynamic set member operation. /// </summary> /// <param name="binder">An instance of the <see cref="SetMemberBinder"/> that represents the details of the dynamic operation.</param> /// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set member operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackSetMember(this, value); } /// <summary> /// Performs the binding of the dynamic delete member operation. /// </summary> /// <param name="binder">An instance of the <see cref="DeleteMemberBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackDeleteMember(this); } /// <summary> /// Performs the binding of the dynamic get index operation. /// </summary> /// <param name="binder">An instance of the <see cref="GetIndexBinder"/> that represents the details of the dynamic operation.</param> /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the get index operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackGetIndex(this, indexes); } /// <summary> /// Performs the binding of the dynamic set index operation. /// </summary> /// <param name="binder">An instance of the <see cref="SetIndexBinder"/> that represents the details of the dynamic operation.</param> /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the set index operation.</param> /// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set index operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackSetIndex(this, indexes, value); } /// <summary> /// Performs the binding of the dynamic delete index operation. /// </summary> /// <param name="binder">An instance of the <see cref="DeleteIndexBinder"/> that represents the details of the dynamic operation.</param> /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the delete index operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackDeleteIndex(this, indexes); } /// <summary> /// Performs the binding of the dynamic invoke member operation. /// </summary> /// <param name="binder">An instance of the <see cref="InvokeMemberBinder"/> that represents the details of the dynamic operation.</param> /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackInvokeMember(this, args); } /// <summary> /// Performs the binding of the dynamic invoke operation. /// </summary> /// <param name="binder">An instance of the <see cref="InvokeBinder"/> that represents the details of the dynamic operation.</param> /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackInvoke(this, args); } /// <summary> /// Performs the binding of the dynamic create instance operation. /// </summary> /// <param name="binder">An instance of the <see cref="CreateInstanceBinder"/> that represents the details of the dynamic operation.</param> /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the create instance operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackCreateInstance(this, args); } /// <summary> /// Performs the binding of the dynamic unary operation. /// </summary> /// <param name="binder">An instance of the <see cref="UnaryOperationBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackUnaryOperation(this); } /// <summary> /// Performs the binding of the dynamic binary operation. /// </summary> /// <param name="binder">An instance of the <see cref="BinaryOperationBinder"/> that represents the details of the dynamic operation.</param> /// <param name="arg">An instance of the <see cref="DynamicMetaObject"/> representing the right hand side of the binary operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackBinaryOperation(this, arg); } /// <summary> /// Returns the enumeration of all dynamic member names. /// </summary> /// <returns>The list of dynamic member names.</returns> public virtual IEnumerable<string> GetDynamicMemberNames() => Array.Empty<string>(); /// <summary> /// Returns the list of expressions represented by the <see cref="DynamicMetaObject"/> instances. /// </summary> /// <param name="objects">An array of <see cref="DynamicMetaObject"/> instances to extract expressions from.</param> /// <returns>The array of expressions.</returns> internal static Expression[] GetExpressions(DynamicMetaObject[] objects) { ContractUtils.RequiresNotNull(objects, nameof(objects)); Expression[] res = new Expression[objects.Length]; for (int i = 0; i < objects.Length; i++) { DynamicMetaObject mo = objects[i]; ContractUtils.RequiresNotNull(mo, nameof(objects)); Expression expr = mo.Expression; Debug.Assert(expr != null, "Unexpected null expression; ctor should have caught this."); res[i] = expr; } return res; } /// <summary> /// Creates a meta-object for the specified object. /// </summary> /// <param name="value">The object to get a meta-object for.</param> /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param> /// <returns> /// If the given object implements <see cref="IDynamicMetaObjectProvider"/> and is not a remote object from outside the current AppDomain, /// returns the object's specific meta-object returned by <see cref="IDynamicMetaObjectProvider.GetMetaObject"/>. Otherwise a plain new meta-object /// with no restrictions is created and returned. /// </returns> public static DynamicMetaObject Create(object value, Expression expression) { ContractUtils.RequiresNotNull(expression, nameof(expression)); if (value is IDynamicMetaObjectProvider ido) { var idoMetaObject = ido.GetMetaObject(expression); if (idoMetaObject == null || !idoMetaObject.HasValue || idoMetaObject.Value == null || (object)idoMetaObject.Expression != (object)expression) { throw System.Linq.Expressions.Error.InvalidMetaObjectCreated(ido.GetType()); } return idoMetaObject; } else { return new DynamicMetaObject(expression, BindingRestrictions.Empty, value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Linq.Expressions; namespace System.Dynamic { /// <summary> /// Represents the dynamic binding and a binding logic of an object participating in the dynamic binding. /// </summary> public class DynamicMetaObject { /// <summary> /// Represents an empty array of type <see cref="DynamicMetaObject"/>. This field is read-only. /// </summary> public static readonly DynamicMetaObject[] EmptyMetaObjects = Array.Empty<DynamicMetaObject>(); /// <summary> /// Initializes a new instance of the <see cref="DynamicMetaObject"/> class. /// </summary> /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param> /// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param> public DynamicMetaObject(Expression expression, BindingRestrictions restrictions) { ContractUtils.RequiresNotNull(expression, nameof(expression)); ContractUtils.RequiresNotNull(restrictions, nameof(restrictions)); Expression = expression; Restrictions = restrictions; } /// <summary> /// Initializes a new instance of the <see cref="DynamicMetaObject"/> class. /// </summary> /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param> /// <param name="restrictions">The set of binding restrictions under which the binding is valid.</param> /// <param name="value">The runtime value represented by the <see cref="DynamicMetaObject"/>.</param> public DynamicMetaObject(Expression expression, BindingRestrictions restrictions, object value) : this(expression, restrictions) { _value = value; } // having sentinel value means having no value. (this way we do not need a separate hasValue field) private static readonly object s_noValueSentinel = new object(); private readonly object _value = s_noValueSentinel; /// <summary> /// The expression representing the <see cref="DynamicMetaObject"/> during the dynamic binding process. /// </summary> public Expression Expression { get; } /// <summary> /// The set of binding restrictions under which the binding is valid. /// </summary> public BindingRestrictions Restrictions { get; } /// <summary> /// The runtime value represented by this <see cref="DynamicMetaObject"/>. /// </summary> public object? Value => HasValue ? _value : null; /// <summary> /// Gets a value indicating whether the <see cref="DynamicMetaObject"/> has the runtime value. /// </summary> public bool HasValue => _value != s_noValueSentinel; /// <summary> /// Gets the <see cref="Type"/> of the runtime value or null if the <see cref="DynamicMetaObject"/> has no value associated with it. /// </summary> public Type? RuntimeType { get { if (HasValue) { Type ct = Expression.Type; // valuetype at compile time, type cannot change. if (ct.IsValueType) { return ct; } return Value?.GetType(); } else { return null; } } } /// <summary> /// Gets the limit type of the <see cref="DynamicMetaObject"/>. /// </summary> /// <remarks>Represents the most specific type known about the object represented by the <see cref="DynamicMetaObject"/>. <see cref="RuntimeType"/> if runtime value is available, a type of the <see cref="Expression"/> otherwise.</remarks> public Type LimitType => RuntimeType ?? Expression.Type; /// <summary> /// Performs the binding of the dynamic conversion operation. /// </summary> /// <param name="binder">An instance of the <see cref="ConvertBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindConvert(ConvertBinder binder) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackConvert(this); } /// <summary> /// Performs the binding of the dynamic get member operation. /// </summary> /// <param name="binder">An instance of the <see cref="GetMemberBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindGetMember(GetMemberBinder binder) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackGetMember(this); } /// <summary> /// Performs the binding of the dynamic set member operation. /// </summary> /// <param name="binder">An instance of the <see cref="SetMemberBinder"/> that represents the details of the dynamic operation.</param> /// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set member operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackSetMember(this, value); } /// <summary> /// Performs the binding of the dynamic delete member operation. /// </summary> /// <param name="binder">An instance of the <see cref="DeleteMemberBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackDeleteMember(this); } /// <summary> /// Performs the binding of the dynamic get index operation. /// </summary> /// <param name="binder">An instance of the <see cref="GetIndexBinder"/> that represents the details of the dynamic operation.</param> /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the get index operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackGetIndex(this, indexes); } /// <summary> /// Performs the binding of the dynamic set index operation. /// </summary> /// <param name="binder">An instance of the <see cref="SetIndexBinder"/> that represents the details of the dynamic operation.</param> /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the set index operation.</param> /// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set index operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackSetIndex(this, indexes, value); } /// <summary> /// Performs the binding of the dynamic delete index operation. /// </summary> /// <param name="binder">An instance of the <see cref="DeleteIndexBinder"/> that represents the details of the dynamic operation.</param> /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the delete index operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackDeleteIndex(this, indexes); } /// <summary> /// Performs the binding of the dynamic invoke member operation. /// </summary> /// <param name="binder">An instance of the <see cref="InvokeMemberBinder"/> that represents the details of the dynamic operation.</param> /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke member operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackInvokeMember(this, args); } /// <summary> /// Performs the binding of the dynamic invoke operation. /// </summary> /// <param name="binder">An instance of the <see cref="InvokeBinder"/> that represents the details of the dynamic operation.</param> /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the invoke operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackInvoke(this, args); } /// <summary> /// Performs the binding of the dynamic create instance operation. /// </summary> /// <param name="binder">An instance of the <see cref="CreateInstanceBinder"/> that represents the details of the dynamic operation.</param> /// <param name="args">An array of <see cref="DynamicMetaObject"/> instances - arguments to the create instance operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackCreateInstance(this, args); } /// <summary> /// Performs the binding of the dynamic unary operation. /// </summary> /// <param name="binder">An instance of the <see cref="UnaryOperationBinder"/> that represents the details of the dynamic operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackUnaryOperation(this); } /// <summary> /// Performs the binding of the dynamic binary operation. /// </summary> /// <param name="binder">An instance of the <see cref="BinaryOperationBinder"/> that represents the details of the dynamic operation.</param> /// <param name="arg">An instance of the <see cref="DynamicMetaObject"/> representing the right hand side of the binary operation.</param> /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> public virtual DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) { ContractUtils.RequiresNotNull(binder, nameof(binder)); return binder.FallbackBinaryOperation(this, arg); } /// <summary> /// Returns the enumeration of all dynamic member names. /// </summary> /// <returns>The list of dynamic member names.</returns> public virtual IEnumerable<string> GetDynamicMemberNames() => Array.Empty<string>(); /// <summary> /// Returns the list of expressions represented by the <see cref="DynamicMetaObject"/> instances. /// </summary> /// <param name="objects">An array of <see cref="DynamicMetaObject"/> instances to extract expressions from.</param> /// <returns>The array of expressions.</returns> internal static Expression[] GetExpressions(DynamicMetaObject[] objects) { ContractUtils.RequiresNotNull(objects, nameof(objects)); Expression[] res = new Expression[objects.Length]; for (int i = 0; i < objects.Length; i++) { DynamicMetaObject mo = objects[i]; ContractUtils.RequiresNotNull(mo, nameof(objects)); Expression expr = mo.Expression; Debug.Assert(expr != null, "Unexpected null expression; ctor should have caught this."); res[i] = expr; } return res; } /// <summary> /// Creates a meta-object for the specified object. /// </summary> /// <param name="value">The object to get a meta-object for.</param> /// <param name="expression">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param> /// <returns> /// If the given object implements <see cref="IDynamicMetaObjectProvider"/> and is not a remote object from outside the current AppDomain, /// returns the object's specific meta-object returned by <see cref="IDynamicMetaObjectProvider.GetMetaObject"/>. Otherwise a plain new meta-object /// with no restrictions is created and returned. /// </returns> public static DynamicMetaObject Create(object value, Expression expression) { ContractUtils.RequiresNotNull(expression, nameof(expression)); if (value is IDynamicMetaObjectProvider ido) { var idoMetaObject = ido.GetMetaObject(expression); if (idoMetaObject == null || !idoMetaObject.HasValue || idoMetaObject.Value == null || (object)idoMetaObject.Expression != (object)expression) { throw System.Linq.Expressions.Error.InvalidMetaObjectCreated(ido.GetType()); } return idoMetaObject; } else { return new DynamicMetaObject(expression, BindingRestrictions.Empty, value); } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/ScalarEscaperBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Text.Encodings.Web { /// <summary> /// A class that can escape a scalar value and write either UTF-16 or UTF-8 format. /// </summary> internal abstract class ScalarEscaperBase { internal abstract int EncodeUtf16(Rune value, Span<char> destination); internal abstract int EncodeUtf8(Rune value, Span<byte> destination); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Text.Encodings.Web { /// <summary> /// A class that can escape a scalar value and write either UTF-16 or UTF-8 format. /// </summary> internal abstract class ScalarEscaperBase { internal abstract int EncodeUtf16(Rune value, Span<char> destination); internal abstract int EncodeUtf8(Rune value, Span<byte> destination); } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; namespace System.Xml.Schema { using System; using System.Diagnostics; using System.Text; /// <summary> /// This structure holds components of an Xsd Duration. It is used internally to support Xsd durations without loss /// of fidelity. XsdDuration structures are immutable once they've been created. /// </summary> internal struct XsdDuration { private int _years; private int _months; private int _days; private int _hours; private int _minutes; private int _seconds; private uint _nanoseconds; // High bit is used to indicate whether duration is negative private const uint NegativeBit = 0x80000000; private enum Parts { HasNone = 0, HasYears = 1, HasMonths = 2, HasDays = 4, HasHours = 8, HasMinutes = 16, HasSeconds = 32, } public enum DurationType { Duration, YearMonthDuration, DayTimeDuration, } /// <summary> /// Construct an XsdDuration from component parts. /// </summary> public XsdDuration(bool isNegative, int years, int months, int days, int hours, int minutes, int seconds, int nanoseconds) { if (years < 0) throw new ArgumentOutOfRangeException(nameof(years)); if (months < 0) throw new ArgumentOutOfRangeException(nameof(months)); if (days < 0) throw new ArgumentOutOfRangeException(nameof(days)); if (hours < 0) throw new ArgumentOutOfRangeException(nameof(hours)); if (minutes < 0) throw new ArgumentOutOfRangeException(nameof(minutes)); if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds)); if (nanoseconds < 0 || nanoseconds > 999999999) throw new ArgumentOutOfRangeException(nameof(nanoseconds)); _years = years; _months = months; _days = days; _hours = hours; _minutes = minutes; _seconds = seconds; _nanoseconds = (uint)nanoseconds; if (isNegative) _nanoseconds |= NegativeBit; } /// <summary> /// Construct an XsdDuration from a TimeSpan value. /// </summary> public XsdDuration(TimeSpan timeSpan) : this(timeSpan, DurationType.Duration) { } /// <summary> /// Construct an XsdDuration from a TimeSpan value that represents an xsd:duration, an xdt:dayTimeDuration, or /// an xdt:yearMonthDuration. /// </summary> public XsdDuration(TimeSpan timeSpan, DurationType durationType) { long ticks = timeSpan.Ticks; ulong ticksPos; bool isNegative; if (ticks < 0) { // Note that (ulong) -Int64.MinValue = Int64.MaxValue + 1, which is what we want for that special case isNegative = true; ticksPos = unchecked((ulong)-ticks); } else { isNegative = false; ticksPos = (ulong)ticks; } if (durationType == DurationType.YearMonthDuration) { int years = (int)(ticksPos / ((ulong)TimeSpan.TicksPerDay * 365)); int months = (int)((ticksPos % ((ulong)TimeSpan.TicksPerDay * 365)) / ((ulong)TimeSpan.TicksPerDay * 30)); if (months == 12) { // If remaining days >= 360 and < 365, then round off to year years++; months = 0; } this = new XsdDuration(isNegative, years, months, 0, 0, 0, 0, 0); } else { Debug.Assert(durationType == DurationType.Duration || durationType == DurationType.DayTimeDuration); // Tick count is expressed in 100 nanosecond intervals _nanoseconds = (uint)(ticksPos % 10000000) * 100; if (isNegative) _nanoseconds |= NegativeBit; _years = 0; _months = 0; _days = (int)(ticksPos / (ulong)TimeSpan.TicksPerDay); _hours = (int)((ticksPos / (ulong)TimeSpan.TicksPerHour) % 24); _minutes = (int)((ticksPos / (ulong)TimeSpan.TicksPerMinute) % 60); _seconds = (int)((ticksPos / (ulong)TimeSpan.TicksPerSecond) % 60); } } /// <summary> /// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored with loss /// of fidelity (except in the case of overflow). /// </summary> public XsdDuration(string s) : this(s, DurationType.Duration) { } /// <summary> /// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored without loss /// of fidelity (except in the case of overflow). /// </summary> public XsdDuration(string s, DurationType durationType) { XsdDuration result; Exception? exception = TryParse(s, durationType, out result); if (exception != null) { throw exception; } _years = result.Years; _months = result.Months; _days = result.Days; _hours = result.Hours; _minutes = result.Minutes; _seconds = result.Seconds; _nanoseconds = (uint)result.Nanoseconds; if (result.IsNegative) { _nanoseconds |= NegativeBit; } return; } /// <summary> /// Return true if this duration is negative. /// </summary> public bool IsNegative { get { return (_nanoseconds & NegativeBit) != 0; } } /// <summary> /// Return number of years in this duration (stored in 31 bits). /// </summary> public int Years { get { return _years; } } /// <summary> /// Return number of months in this duration (stored in 31 bits). /// </summary> public int Months { get { return _months; } } /// <summary> /// Return number of days in this duration (stored in 31 bits). /// </summary> public int Days { get { return _days; } } /// <summary> /// Return number of hours in this duration (stored in 31 bits). /// </summary> public int Hours { get { return _hours; } } /// <summary> /// Return number of minutes in this duration (stored in 31 bits). /// </summary> public int Minutes { get { return _minutes; } } /// <summary> /// Return number of seconds in this duration (stored in 31 bits). /// </summary> public int Seconds { get { return _seconds; } } /// <summary> /// Return number of nanoseconds in this duration. /// </summary> public int Nanoseconds { get { return (int)(_nanoseconds & ~NegativeBit); } } /// <summary> /// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate /// that there are 365 days in the year and 30 days in a month. /// </summary> public TimeSpan ToTimeSpan() { return ToTimeSpan(DurationType.Duration); } /// <summary> /// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate /// that there are 365 days in the year and 30 days in a month. /// </summary> public TimeSpan ToTimeSpan(DurationType durationType) { TimeSpan result; Exception? exception = TryToTimeSpan(durationType, out result); if (exception != null) { throw exception; } return result; } internal Exception? TryToTimeSpan(out TimeSpan result) { return TryToTimeSpan(DurationType.Duration, out result); } internal Exception? TryToTimeSpan(DurationType durationType, out TimeSpan result) { Exception? exception; ulong ticks = 0; // Throw error if result cannot fit into a long try { checked { // Discard year and month parts if constructing TimeSpan for DayTimeDuration if (durationType != DurationType.DayTimeDuration) { ticks += ((ulong)_years + (ulong)_months / 12) * 365; ticks += ((ulong)_months % 12) * 30; } // Discard day and time parts if constructing TimeSpan for YearMonthDuration if (durationType != DurationType.YearMonthDuration) { ticks += (ulong)_days; ticks *= 24; ticks += (ulong)_hours; ticks *= 60; ticks += (ulong)_minutes; ticks *= 60; ticks += (ulong)_seconds; // Tick count interval is in 100 nanosecond intervals (7 digits) ticks *= (ulong)TimeSpan.TicksPerSecond; ticks += (ulong)Nanoseconds / 100; } else { // Multiply YearMonth duration by number of ticks per day ticks *= (ulong)TimeSpan.TicksPerDay; } if (IsNegative) { // Handle special case of Int64.MaxValue + 1 before negation, since it would otherwise overflow if (ticks == (ulong)long.MaxValue + 1) { result = new TimeSpan(long.MinValue); } else { result = new TimeSpan(-((long)ticks)); } } else { result = new TimeSpan((long)ticks); } return null; } } catch (OverflowException) { result = TimeSpan.MinValue; exception = new OverflowException(SR.Format(SR.XmlConvert_Overflow, durationType, "TimeSpan")); } return exception; } /// <summary> /// Return the string representation of this Xsd duration. /// </summary> public override string ToString() { return ToString(DurationType.Duration); } /// <summary> /// Return the string representation according to xsd:duration rules, xdt:dayTimeDuration rules, or /// xdt:yearMonthDuration rules. /// </summary> internal string ToString(DurationType durationType) { var vsb = new ValueStringBuilder(stackalloc char[20]); int nanoseconds, digit, zeroIdx, len; if (IsNegative) vsb.Append('-'); vsb.Append('P'); if (durationType != DurationType.DayTimeDuration) { if (_years != 0) { vsb.AppendSpanFormattable(_years, null, CultureInfo.InvariantCulture); vsb.Append('Y'); } if (_months != 0) { vsb.AppendSpanFormattable(_months, null, CultureInfo.InvariantCulture); vsb.Append('M'); } } if (durationType != DurationType.YearMonthDuration) { if (_days != 0) { vsb.AppendSpanFormattable(_days, null, CultureInfo.InvariantCulture); vsb.Append('D'); } if (_hours != 0 || _minutes != 0 || _seconds != 0 || Nanoseconds != 0) { vsb.Append('T'); if (_hours != 0) { vsb.AppendSpanFormattable(_hours, null, CultureInfo.InvariantCulture); vsb.Append('H'); } if (_minutes != 0) { vsb.AppendSpanFormattable(_minutes, null, CultureInfo.InvariantCulture); vsb.Append('M'); } nanoseconds = Nanoseconds; if (_seconds != 0 || nanoseconds != 0) { vsb.AppendSpanFormattable(_seconds, null, CultureInfo.InvariantCulture); if (nanoseconds != 0) { vsb.Append('.'); len = vsb.Length; Span<char> tmpSpan = stackalloc char[9]; zeroIdx = len + 8; for (int idx = zeroIdx; idx >= len; idx--) { digit = nanoseconds % 10; tmpSpan[idx - len] = (char)(digit + '0'); if (zeroIdx == idx && digit == 0) zeroIdx--; nanoseconds /= 10; } vsb.EnsureCapacity(zeroIdx + 1); vsb.Append(tmpSpan.Slice(0, zeroIdx - len + 1)); } vsb.Append('S'); } } // Zero is represented as "PT0S" if (vsb[vsb.Length - 1] == 'P') vsb.Append("T0S"); } else { // Zero is represented as "T0M" if (vsb[vsb.Length - 1] == 'P') vsb.Append("0M"); } return vsb.ToString(); } internal static Exception? TryParse(string s, out XsdDuration result) { return TryParse(s, DurationType.Duration, out result); } internal static Exception? TryParse(string s, DurationType durationType, out XsdDuration result) { string? errorCode; int length; int value, pos, numDigits; Parts parts = Parts.HasNone; result = default; s = s.Trim(); length = s.Length; pos = 0; if (pos >= length) goto InvalidFormat; if (s[pos] == '-') { pos++; result._nanoseconds = NegativeBit; } else { result._nanoseconds = 0; } if (pos >= length) goto InvalidFormat; if (s[pos++] != 'P') goto InvalidFormat; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; if (s[pos] == 'Y') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasYears; result._years = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'M') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasMonths; result._months = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'D') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasDays; result._days = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out _, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'T') { if (numDigits != 0) goto InvalidFormat; pos++; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; if (s[pos] == 'H') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasHours; result._hours = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'M') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasMinutes; result._minutes = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == '.') { pos++; parts |= Parts.HasSeconds; result._seconds = value; errorCode = TryParseDigits(s, ref pos, true, out value, out numDigits); if (errorCode != null) goto Error; if (numDigits == 0) { //If there are no digits after the decimal point, assume 0 value = 0; } // Normalize to nanosecond intervals for (; numDigits > 9; numDigits--) value /= 10; for (; numDigits < 9; numDigits++) value *= 10; result._nanoseconds |= (uint)value; if (pos >= length) goto InvalidFormat; if (s[pos] != 'S') goto InvalidFormat; if (++pos == length) goto Done; } else if (s[pos] == 'S') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasSeconds; result._seconds = value; if (++pos == length) goto Done; } } // Duration cannot end with digits if (numDigits != 0) goto InvalidFormat; // No further characters are allowed if (pos != length) goto InvalidFormat; Done: // At least one part must be defined if (parts == Parts.HasNone) goto InvalidFormat; if (durationType == DurationType.DayTimeDuration) { if ((parts & (Parts.HasYears | Parts.HasMonths)) != 0) goto InvalidFormat; } else if (durationType == DurationType.YearMonthDuration) { if ((parts & ~(XsdDuration.Parts.HasYears | XsdDuration.Parts.HasMonths)) != 0) goto InvalidFormat; } return null; InvalidFormat: return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, durationType)); Error: return new OverflowException(SR.Format(SR.XmlConvert_Overflow, s, durationType)); } /// Helper method that constructs an integer from leading digits starting at s[offset]. "offset" is /// updated to contain an offset just beyond the last digit. The number of digits consumed is returned in /// cntDigits. The integer is returned (0 if no digits). If the digits cannot fit into an Int32: /// 1. If eatDigits is true, then additional digits will be silently discarded (don't count towards numDigits) /// 2. If eatDigits is false, an overflow exception is thrown private static string? TryParseDigits(string s, ref int offset, bool eatDigits, out int result, out int numDigits) { int offsetStart = offset; int offsetEnd = s.Length; int digit; result = 0; numDigits = 0; while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') { digit = s[offset] - '0'; if (result > (int.MaxValue - digit) / 10) { if (!eatDigits) { return SR.XmlConvert_Overflow; } // Skip past any remaining digits numDigits = offset - offsetStart; while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') { offset++; } return null; } result = result * 10 + digit; offset++; } numDigits = offset - offsetStart; return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; namespace System.Xml.Schema { using System; using System.Diagnostics; using System.Text; /// <summary> /// This structure holds components of an Xsd Duration. It is used internally to support Xsd durations without loss /// of fidelity. XsdDuration structures are immutable once they've been created. /// </summary> internal struct XsdDuration { private int _years; private int _months; private int _days; private int _hours; private int _minutes; private int _seconds; private uint _nanoseconds; // High bit is used to indicate whether duration is negative private const uint NegativeBit = 0x80000000; private enum Parts { HasNone = 0, HasYears = 1, HasMonths = 2, HasDays = 4, HasHours = 8, HasMinutes = 16, HasSeconds = 32, } public enum DurationType { Duration, YearMonthDuration, DayTimeDuration, } /// <summary> /// Construct an XsdDuration from component parts. /// </summary> public XsdDuration(bool isNegative, int years, int months, int days, int hours, int minutes, int seconds, int nanoseconds) { if (years < 0) throw new ArgumentOutOfRangeException(nameof(years)); if (months < 0) throw new ArgumentOutOfRangeException(nameof(months)); if (days < 0) throw new ArgumentOutOfRangeException(nameof(days)); if (hours < 0) throw new ArgumentOutOfRangeException(nameof(hours)); if (minutes < 0) throw new ArgumentOutOfRangeException(nameof(minutes)); if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds)); if (nanoseconds < 0 || nanoseconds > 999999999) throw new ArgumentOutOfRangeException(nameof(nanoseconds)); _years = years; _months = months; _days = days; _hours = hours; _minutes = minutes; _seconds = seconds; _nanoseconds = (uint)nanoseconds; if (isNegative) _nanoseconds |= NegativeBit; } /// <summary> /// Construct an XsdDuration from a TimeSpan value. /// </summary> public XsdDuration(TimeSpan timeSpan) : this(timeSpan, DurationType.Duration) { } /// <summary> /// Construct an XsdDuration from a TimeSpan value that represents an xsd:duration, an xdt:dayTimeDuration, or /// an xdt:yearMonthDuration. /// </summary> public XsdDuration(TimeSpan timeSpan, DurationType durationType) { long ticks = timeSpan.Ticks; ulong ticksPos; bool isNegative; if (ticks < 0) { // Note that (ulong) -Int64.MinValue = Int64.MaxValue + 1, which is what we want for that special case isNegative = true; ticksPos = unchecked((ulong)-ticks); } else { isNegative = false; ticksPos = (ulong)ticks; } if (durationType == DurationType.YearMonthDuration) { int years = (int)(ticksPos / ((ulong)TimeSpan.TicksPerDay * 365)); int months = (int)((ticksPos % ((ulong)TimeSpan.TicksPerDay * 365)) / ((ulong)TimeSpan.TicksPerDay * 30)); if (months == 12) { // If remaining days >= 360 and < 365, then round off to year years++; months = 0; } this = new XsdDuration(isNegative, years, months, 0, 0, 0, 0, 0); } else { Debug.Assert(durationType == DurationType.Duration || durationType == DurationType.DayTimeDuration); // Tick count is expressed in 100 nanosecond intervals _nanoseconds = (uint)(ticksPos % 10000000) * 100; if (isNegative) _nanoseconds |= NegativeBit; _years = 0; _months = 0; _days = (int)(ticksPos / (ulong)TimeSpan.TicksPerDay); _hours = (int)((ticksPos / (ulong)TimeSpan.TicksPerHour) % 24); _minutes = (int)((ticksPos / (ulong)TimeSpan.TicksPerMinute) % 60); _seconds = (int)((ticksPos / (ulong)TimeSpan.TicksPerSecond) % 60); } } /// <summary> /// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored with loss /// of fidelity (except in the case of overflow). /// </summary> public XsdDuration(string s) : this(s, DurationType.Duration) { } /// <summary> /// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored without loss /// of fidelity (except in the case of overflow). /// </summary> public XsdDuration(string s, DurationType durationType) { XsdDuration result; Exception? exception = TryParse(s, durationType, out result); if (exception != null) { throw exception; } _years = result.Years; _months = result.Months; _days = result.Days; _hours = result.Hours; _minutes = result.Minutes; _seconds = result.Seconds; _nanoseconds = (uint)result.Nanoseconds; if (result.IsNegative) { _nanoseconds |= NegativeBit; } return; } /// <summary> /// Return true if this duration is negative. /// </summary> public bool IsNegative { get { return (_nanoseconds & NegativeBit) != 0; } } /// <summary> /// Return number of years in this duration (stored in 31 bits). /// </summary> public int Years { get { return _years; } } /// <summary> /// Return number of months in this duration (stored in 31 bits). /// </summary> public int Months { get { return _months; } } /// <summary> /// Return number of days in this duration (stored in 31 bits). /// </summary> public int Days { get { return _days; } } /// <summary> /// Return number of hours in this duration (stored in 31 bits). /// </summary> public int Hours { get { return _hours; } } /// <summary> /// Return number of minutes in this duration (stored in 31 bits). /// </summary> public int Minutes { get { return _minutes; } } /// <summary> /// Return number of seconds in this duration (stored in 31 bits). /// </summary> public int Seconds { get { return _seconds; } } /// <summary> /// Return number of nanoseconds in this duration. /// </summary> public int Nanoseconds { get { return (int)(_nanoseconds & ~NegativeBit); } } /// <summary> /// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate /// that there are 365 days in the year and 30 days in a month. /// </summary> public TimeSpan ToTimeSpan() { return ToTimeSpan(DurationType.Duration); } /// <summary> /// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate /// that there are 365 days in the year and 30 days in a month. /// </summary> public TimeSpan ToTimeSpan(DurationType durationType) { TimeSpan result; Exception? exception = TryToTimeSpan(durationType, out result); if (exception != null) { throw exception; } return result; } internal Exception? TryToTimeSpan(out TimeSpan result) { return TryToTimeSpan(DurationType.Duration, out result); } internal Exception? TryToTimeSpan(DurationType durationType, out TimeSpan result) { Exception? exception; ulong ticks = 0; // Throw error if result cannot fit into a long try { checked { // Discard year and month parts if constructing TimeSpan for DayTimeDuration if (durationType != DurationType.DayTimeDuration) { ticks += ((ulong)_years + (ulong)_months / 12) * 365; ticks += ((ulong)_months % 12) * 30; } // Discard day and time parts if constructing TimeSpan for YearMonthDuration if (durationType != DurationType.YearMonthDuration) { ticks += (ulong)_days; ticks *= 24; ticks += (ulong)_hours; ticks *= 60; ticks += (ulong)_minutes; ticks *= 60; ticks += (ulong)_seconds; // Tick count interval is in 100 nanosecond intervals (7 digits) ticks *= (ulong)TimeSpan.TicksPerSecond; ticks += (ulong)Nanoseconds / 100; } else { // Multiply YearMonth duration by number of ticks per day ticks *= (ulong)TimeSpan.TicksPerDay; } if (IsNegative) { // Handle special case of Int64.MaxValue + 1 before negation, since it would otherwise overflow if (ticks == (ulong)long.MaxValue + 1) { result = new TimeSpan(long.MinValue); } else { result = new TimeSpan(-((long)ticks)); } } else { result = new TimeSpan((long)ticks); } return null; } } catch (OverflowException) { result = TimeSpan.MinValue; exception = new OverflowException(SR.Format(SR.XmlConvert_Overflow, durationType, "TimeSpan")); } return exception; } /// <summary> /// Return the string representation of this Xsd duration. /// </summary> public override string ToString() { return ToString(DurationType.Duration); } /// <summary> /// Return the string representation according to xsd:duration rules, xdt:dayTimeDuration rules, or /// xdt:yearMonthDuration rules. /// </summary> internal string ToString(DurationType durationType) { var vsb = new ValueStringBuilder(stackalloc char[20]); int nanoseconds, digit, zeroIdx, len; if (IsNegative) vsb.Append('-'); vsb.Append('P'); if (durationType != DurationType.DayTimeDuration) { if (_years != 0) { vsb.AppendSpanFormattable(_years, null, CultureInfo.InvariantCulture); vsb.Append('Y'); } if (_months != 0) { vsb.AppendSpanFormattable(_months, null, CultureInfo.InvariantCulture); vsb.Append('M'); } } if (durationType != DurationType.YearMonthDuration) { if (_days != 0) { vsb.AppendSpanFormattable(_days, null, CultureInfo.InvariantCulture); vsb.Append('D'); } if (_hours != 0 || _minutes != 0 || _seconds != 0 || Nanoseconds != 0) { vsb.Append('T'); if (_hours != 0) { vsb.AppendSpanFormattable(_hours, null, CultureInfo.InvariantCulture); vsb.Append('H'); } if (_minutes != 0) { vsb.AppendSpanFormattable(_minutes, null, CultureInfo.InvariantCulture); vsb.Append('M'); } nanoseconds = Nanoseconds; if (_seconds != 0 || nanoseconds != 0) { vsb.AppendSpanFormattable(_seconds, null, CultureInfo.InvariantCulture); if (nanoseconds != 0) { vsb.Append('.'); len = vsb.Length; Span<char> tmpSpan = stackalloc char[9]; zeroIdx = len + 8; for (int idx = zeroIdx; idx >= len; idx--) { digit = nanoseconds % 10; tmpSpan[idx - len] = (char)(digit + '0'); if (zeroIdx == idx && digit == 0) zeroIdx--; nanoseconds /= 10; } vsb.EnsureCapacity(zeroIdx + 1); vsb.Append(tmpSpan.Slice(0, zeroIdx - len + 1)); } vsb.Append('S'); } } // Zero is represented as "PT0S" if (vsb[vsb.Length - 1] == 'P') vsb.Append("T0S"); } else { // Zero is represented as "T0M" if (vsb[vsb.Length - 1] == 'P') vsb.Append("0M"); } return vsb.ToString(); } internal static Exception? TryParse(string s, out XsdDuration result) { return TryParse(s, DurationType.Duration, out result); } internal static Exception? TryParse(string s, DurationType durationType, out XsdDuration result) { string? errorCode; int length; int value, pos, numDigits; Parts parts = Parts.HasNone; result = default; s = s.Trim(); length = s.Length; pos = 0; if (pos >= length) goto InvalidFormat; if (s[pos] == '-') { pos++; result._nanoseconds = NegativeBit; } else { result._nanoseconds = 0; } if (pos >= length) goto InvalidFormat; if (s[pos++] != 'P') goto InvalidFormat; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; if (s[pos] == 'Y') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasYears; result._years = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'M') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasMonths; result._months = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'D') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasDays; result._days = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out _, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'T') { if (numDigits != 0) goto InvalidFormat; pos++; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; if (s[pos] == 'H') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasHours; result._hours = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'M') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasMinutes; result._minutes = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == '.') { pos++; parts |= Parts.HasSeconds; result._seconds = value; errorCode = TryParseDigits(s, ref pos, true, out value, out numDigits); if (errorCode != null) goto Error; if (numDigits == 0) { //If there are no digits after the decimal point, assume 0 value = 0; } // Normalize to nanosecond intervals for (; numDigits > 9; numDigits--) value /= 10; for (; numDigits < 9; numDigits++) value *= 10; result._nanoseconds |= (uint)value; if (pos >= length) goto InvalidFormat; if (s[pos] != 'S') goto InvalidFormat; if (++pos == length) goto Done; } else if (s[pos] == 'S') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasSeconds; result._seconds = value; if (++pos == length) goto Done; } } // Duration cannot end with digits if (numDigits != 0) goto InvalidFormat; // No further characters are allowed if (pos != length) goto InvalidFormat; Done: // At least one part must be defined if (parts == Parts.HasNone) goto InvalidFormat; if (durationType == DurationType.DayTimeDuration) { if ((parts & (Parts.HasYears | Parts.HasMonths)) != 0) goto InvalidFormat; } else if (durationType == DurationType.YearMonthDuration) { if ((parts & ~(XsdDuration.Parts.HasYears | XsdDuration.Parts.HasMonths)) != 0) goto InvalidFormat; } return null; InvalidFormat: return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, durationType)); Error: return new OverflowException(SR.Format(SR.XmlConvert_Overflow, s, durationType)); } /// Helper method that constructs an integer from leading digits starting at s[offset]. "offset" is /// updated to contain an offset just beyond the last digit. The number of digits consumed is returned in /// cntDigits. The integer is returned (0 if no digits). If the digits cannot fit into an Int32: /// 1. If eatDigits is true, then additional digits will be silently discarded (don't count towards numDigits) /// 2. If eatDigits is false, an overflow exception is thrown private static string? TryParseDigits(string s, ref int offset, bool eatDigits, out int result, out int numDigits) { int offsetStart = offset; int offsetEnd = s.Length; int digit; result = 0; numDigits = 0; while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') { digit = s[offset] - '0'; if (result > (int.MaxValue - digit) / 10) { if (!eatDigits) { return SR.XmlConvert_Overflow; } // Skip past any remaining digits numDigits = offset - offsetStart; while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') { offset++; } return null; } result = result * 10 + digit; offset++; } numDigits = offset - offsetStart; return null; } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Collections/tests/Generic/Stack/Stack.Tests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; namespace System.Collections.Tests { public class Stack_ICollection_NonGeneric_Tests : ICollection_NonGeneric_Tests { #region ICollection Helper Methods protected override Type ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType => typeof(ArgumentException); protected override void AddToCollection(ICollection collection, int numberOfItemsToAdd) { int seed = numberOfItemsToAdd * 34; for (int i = 0; i < numberOfItemsToAdd; i++) ((Stack<string>)collection).Push(CreateT(seed++)); } protected override ICollection NonGenericICollectionFactory() { return new Stack<string>(); } protected override bool Enumerator_Current_UndefinedOperation_Throws => true; protected override Type ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentOutOfRangeException); /// <summary> /// Returns a set of ModifyEnumerable delegates that modify the enumerable passed to them. /// </summary> protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) { if ((operations & ModifyOperation.Add) == ModifyOperation.Add) { yield return (IEnumerable enumerable) => { var casted = (Stack<string>)enumerable; casted.Push(CreateT(2344)); return true; }; } if ((operations & ModifyOperation.Remove) == ModifyOperation.Remove) { yield return (IEnumerable enumerable) => { var casted = (Stack<string>)enumerable; if (casted.Count > 0) { casted.Pop(); return true; } return false; }; } if ((operations & ModifyOperation.Clear) == ModifyOperation.Clear) { yield return (IEnumerable enumerable) => { var casted = (Stack<string>)enumerable; if (casted.Count > 0) { casted.Clear(); return true; } return false; }; } } protected string CreateT(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; namespace System.Collections.Tests { public class Stack_ICollection_NonGeneric_Tests : ICollection_NonGeneric_Tests { #region ICollection Helper Methods protected override Type ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType => typeof(ArgumentException); protected override void AddToCollection(ICollection collection, int numberOfItemsToAdd) { int seed = numberOfItemsToAdd * 34; for (int i = 0; i < numberOfItemsToAdd; i++) ((Stack<string>)collection).Push(CreateT(seed++)); } protected override ICollection NonGenericICollectionFactory() { return new Stack<string>(); } protected override bool Enumerator_Current_UndefinedOperation_Throws => true; protected override Type ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentOutOfRangeException); /// <summary> /// Returns a set of ModifyEnumerable delegates that modify the enumerable passed to them. /// </summary> protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) { if ((operations & ModifyOperation.Add) == ModifyOperation.Add) { yield return (IEnumerable enumerable) => { var casted = (Stack<string>)enumerable; casted.Push(CreateT(2344)); return true; }; } if ((operations & ModifyOperation.Remove) == ModifyOperation.Remove) { yield return (IEnumerable enumerable) => { var casted = (Stack<string>)enumerable; if (casted.Count > 0) { casted.Pop(); return true; } return false; }; } if ((operations & ModifyOperation.Clear) == ModifyOperation.Clear) { yield return (IEnumerable enumerable) => { var casted = (Stack<string>)enumerable; if (casted.Count > 0) { casted.Clear(); return true; } return false; }; } } protected string CreateT(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } #endregion } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/HardwareIntrinsics/Arm/Dp/DotProduct.Vector64.Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void DotProduct_Vector64_Int32() { var test = new SimpleTernaryOpTest__DotProduct_Vector64_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__DotProduct_Vector64_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, SByte[] inArray2, SByte[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<SByte, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector64<SByte> _fld2; public Vector64<SByte> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__DotProduct_Vector64_Int32 testClass) { var result = Dp.DotProduct(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__DotProduct_Vector64_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) fixed (Vector64<SByte>* pFld3 = &_fld3) { var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), AdvSimd.LoadVector64((SByte*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static SByte[] _data3 = new SByte[Op3ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<SByte> _clsVar2; private static Vector64<SByte> _clsVar3; private Vector64<Int32> _fld1; private Vector64<SByte> _fld2; private Vector64<SByte> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__DotProduct_Vector64_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); } public SimpleTernaryOpTest__DotProduct_Vector64_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Dp.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Dp.DotProduct( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Dp).GetMethod(nameof(Dp.DotProduct), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Dp).GetMethod(nameof(Dp.DotProduct), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Dp.DotProduct( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<SByte>* pClsVar2 = &_clsVar2) fixed (Vector64<SByte>* pClsVar3 = &_clsVar3) { var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((SByte*)(pClsVar2)), AdvSimd.LoadVector64((SByte*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr); var result = Dp.DotProduct(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr)); var result = Dp.DotProduct(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__DotProduct_Vector64_Int32(); var result = Dp.DotProduct(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__DotProduct_Vector64_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<SByte>* pFld2 = &test._fld2) fixed (Vector64<SByte>* pFld3 = &test._fld3) { var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), AdvSimd.LoadVector64((SByte*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Dp.DotProduct(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) fixed (Vector64<SByte>* pFld3 = &_fld3) { var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), AdvSimd.LoadVector64((SByte*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Dp.DotProduct(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((SByte*)(&test._fld2)), AdvSimd.LoadVector64((SByte*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, Vector64<SByte> op2, Vector64<SByte> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] inArray3 = new SByte[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] inArray3 = new SByte[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, SByte[] secondOp, SByte[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.DotProduct(firstOp[i], secondOp, 4 * i, thirdOp, 4 * i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Dp)}.{nameof(Dp.DotProduct)}<Int32>(Vector64<Int32>, Vector64<SByte>, Vector64<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void DotProduct_Vector64_Int32() { var test = new SimpleTernaryOpTest__DotProduct_Vector64_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__DotProduct_Vector64_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, SByte[] inArray2, SByte[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<SByte, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector64<SByte> _fld2; public Vector64<SByte> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__DotProduct_Vector64_Int32 testClass) { var result = Dp.DotProduct(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__DotProduct_Vector64_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) fixed (Vector64<SByte>* pFld3 = &_fld3) { var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), AdvSimd.LoadVector64((SByte*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static SByte[] _data3 = new SByte[Op3ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<SByte> _clsVar2; private static Vector64<SByte> _clsVar3; private Vector64<Int32> _fld1; private Vector64<SByte> _fld2; private Vector64<SByte> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__DotProduct_Vector64_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); } public SimpleTernaryOpTest__DotProduct_Vector64_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Dp.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Dp.DotProduct( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Dp).GetMethod(nameof(Dp.DotProduct), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Dp).GetMethod(nameof(Dp.DotProduct), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Dp.DotProduct( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<SByte>* pClsVar2 = &_clsVar2) fixed (Vector64<SByte>* pClsVar3 = &_clsVar3) { var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((SByte*)(pClsVar2)), AdvSimd.LoadVector64((SByte*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr); var result = Dp.DotProduct(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr)); var result = Dp.DotProduct(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__DotProduct_Vector64_Int32(); var result = Dp.DotProduct(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__DotProduct_Vector64_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<SByte>* pFld2 = &test._fld2) fixed (Vector64<SByte>* pFld3 = &test._fld3) { var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), AdvSimd.LoadVector64((SByte*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Dp.DotProduct(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) fixed (Vector64<SByte>* pFld3 = &_fld3) { var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), AdvSimd.LoadVector64((SByte*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Dp.DotProduct(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Dp.DotProduct( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((SByte*)(&test._fld2)), AdvSimd.LoadVector64((SByte*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, Vector64<SByte> op2, Vector64<SByte> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] inArray3 = new SByte[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] inArray3 = new SByte[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, SByte[] secondOp, SByte[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.DotProduct(firstOp[i], secondOp, 4 * i, thirdOp, 4 * i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Dp)}.{nameof(Dp.DotProduct)}<Int32>(Vector64<Int32>, Vector64<SByte>, Vector64<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Methodical/Invoke/SEH/catchfinally_jmp_il_r.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="catchfinally_jmp.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="catchfinally_jmp.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Linq/tests/SelectTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Xunit; namespace System.Linq.Tests { public class SelectTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsStringQuery() { var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" } select x1; var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 } select x2; var q = from x3 in q1 from x4 in q2 select new { a1 = x3, a2 = x4 }; Assert.Equal(q.Select(e => e.a1), q.Select(e => e.a1)); } [Fact] public void SingleElement() { var source = new[] { new { name = "Prakash", custID = 98088 } }; string[] expected = { "Prakash" }; Assert.Equal(expected, source.Select(e => e.name)); } [Fact] public void SelectProperty() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name=(string)null, custID=30349 }, new { name="Prakash", custID=39030 } }; string[] expected = { "Prakash", "Bob", "Chris", null, "Prakash" }; Assert.Equal(expected, source.Select(e => e.name)); } [Fact] public void RunOnce() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name=(string)null, custID=30349 }, new { name="Prakash", custID=39030 } }; string[] expected = { "Prakash", "Bob", "Chris", null, "Prakash" }; Assert.Equal(expected, source.RunOnce().Select(e => e.name)); Assert.Equal(expected, source.ToArray().RunOnce().Select(e => e.name)); Assert.Equal(expected, source.ToList().RunOnce().Select(e => e.name)); } [Fact] public void EmptyWithIndexedSelector() { Assert.Equal(Enumerable.Empty<int>(), Enumerable.Empty<string>().Select((s, i) => s.Length + i)); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void EnumerateFromDifferentThread() { var selected = Enumerable.Range(0, 100).Where(i => i > 3).Select(i => i.ToString()); Task[] tasks = new Task[4]; for (int i = 0; i != 4; ++i) tasks[i] = Task.Run(() => selected.ToList()); Task.WaitAll(tasks); } [Fact] public void SingleElementIndexedSelector() { var source = new[] { new { name = "Prakash", custID = 98088 } }; string[] expected = { "Prakash" }; Assert.Equal(expected, source.Select((e, index) => e.name)); } [Fact] public void SelectPropertyPassingIndex() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name=(string)null, custID=30349 }, new { name="Prakash", custID=39030 } }; string[] expected = { "Prakash", "Bob", "Chris", null, "Prakash" }; Assert.Equal(expected, source.Select((e, i) => e.name)); } [Fact] public void SelectPropertyUsingIndex() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 } }; string[] expected = { "Prakash", null, null }; Assert.Equal(expected, source.Select((e, i) => i == 0 ? e.name : null)); } [Fact] public void SelectPropertyPassingIndexOnLast() { var source = new[]{ new { name="Prakash", custID=98088}, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name="Robert", custID=39033 }, new { name="Allen", custID=39033 }, new { name="Chuck", custID=39033 } }; string[] expected = { null, null, null, null, null, "Chuck" }; Assert.Equal(expected, source.Select((e, i) => i == 5 ? e.name : null)); } [ConditionalFact(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] public void Overflow() { var selected = new FastInfiniteEnumerator<int>().Select((e, i) => e); using (var en = selected.GetEnumerator()) Assert.Throws<OverflowException>(() => { while (en.MoveNext()) { } }); } [Fact] public void Select_SourceIsNull_ArgumentNullExceptionThrown() { IEnumerable<int> source = null; Func<int, int> selector = i => i + 1; AssertExtensions.Throws<ArgumentNullException>("source", () => source.Select(selector)); } [Fact] public void Select_SelectorIsNull_ArgumentNullExceptionThrown_Indexed() { IEnumerable<int> source = Enumerable.Range(1, 10); Func<int, int, int> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => source.Select(selector)); } [Fact] public void Select_SourceIsNull_ArgumentNullExceptionThrown_Indexed() { IEnumerable<int> source = null; Func<int, int, int> selector = (e, i) => i + 1; AssertExtensions.Throws<ArgumentNullException>("source", () => source.Select(selector)); } [Fact] public void Select_SelectorIsNull_ArgumentNullExceptionThrown() { IEnumerable<int> source = Enumerable.Range(1, 10); Func<int, int> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => source.Select(selector)); } [Fact] public void Select_SourceIsAnArray_ExecutionIsDeferred() { bool funcCalled = false; Func<int>[] source = new Func<int>[] { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsAList_ExecutionIsDeferred() { bool funcCalled = false; List<Func<int>> source = new List<Func<int>>() { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsIReadOnlyCollection_ExecutionIsDeferred() { bool funcCalled = false; IReadOnlyCollection<Func<int>> source = new ReadOnlyCollection<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsICollection_ExecutionIsDeferred() { bool funcCalled = false; ICollection<Func<int>> source = new LinkedList<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsIEnumerable_ExecutionIsDeferred() { bool funcCalled = false; IEnumerable<Func<int>> source = Enumerable.Repeat((Func<int>)(() => { funcCalled = true; return 1; }), 1); IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsAnArray_ExecutionIsDeferred() { bool funcCalled = false; Func<int>[] source = new Func<int>[] { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsAList_ExecutionIsDeferred() { bool funcCalled = false; List<Func<int>> source = new List<Func<int>>() { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsIReadOnlyCollection_ExecutionIsDeferred() { bool funcCalled = false; IReadOnlyCollection<Func<int>> source = new ReadOnlyCollection<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsICollection_ExecutionIsDeferred() { bool funcCalled = false; ICollection<Func<int>> source = new LinkedList<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsIEnumerable_ExecutionIsDeferred() { bool funcCalled = false; IEnumerable<Func<int>> source = Enumerable.Repeat((Func<int>)(() => { funcCalled = true; return 1; }), 1); IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsAnArray_ReturnsExpectedValues() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { var expected = selector(source[index]); Assert.Equal(expected, item); index++; } Assert.Equal(source.Length, index); } [Fact] public void Select_SourceIsAList_ReturnsExpectedValues() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { var expected = selector(source[index]); Assert.Equal(expected, item); index++; } Assert.Equal(source.Count, index); } [Fact] public void Select_SourceIsIReadOnlyCollection_ReturnsExpectedValues() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(index); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void Select_SourceIsICollection_ReturnsExpectedValues() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(index); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void Select_SourceIsIEnumerable_ReturnsExpectedValues() { int nbOfItems = 5; IEnumerable<int> source = Enumerable.Range(1, nbOfItems); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(index); Assert.Equal(expected, item); } Assert.Equal(nbOfItems, index); } [Fact] public void Select_SourceIsAnArray_CurrentIsDefaultOfTAfterEnumeration() { int[] source = new[] { 1 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsAList_CurrentIsDefaultOfTAfterEnumeration() { List<int> source = new List<int>() { 1 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsIReadOnlyCollection_CurrentIsDefaultOfTAfterEnumeration() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int>() { 1 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsICollection_CurrentIsDefaultOfTAfterEnumeration() { ICollection<int> source = new LinkedList<int>(new List<int>() { 1 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsIEnumerable_CurrentIsDefaultOfTAfterEnumeration() { IEnumerable<int> source = Enumerable.Repeat(1, 1); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void SelectSelect_SourceIsAnArray_ReturnsExpectedValues() { Func<int, int> selector = i => i + 1; int[] source = new[] { 1, 2, 3, 4, 5 }; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { var expected = selector(selector(source[index])); Assert.Equal(expected, item); index++; } Assert.Equal(source.Length, index); } [Fact] public void SelectSelect_SourceIsAList_ReturnsExpectedValues() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { var expected = selector(selector(source[index])); Assert.Equal(expected, item); index++; } Assert.Equal(source.Count, index); } [Fact] public void SelectSelect_SourceIsIReadOnlyCollection_ReturnsExpectedValues() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(selector(index)); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void SelectSelect_SourceIsICollection_ReturnsExpectedValues() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(selector(index)); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void SelectSelect_SourceIsIEnumerable_ReturnsExpectedValues() { int nbOfItems = 5; IEnumerable<int> source = Enumerable.Range(1, 5); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(selector(index)); Assert.Equal(expected, item); } Assert.Equal(nbOfItems, index); } [Fact] public void Select_SourceIsEmptyEnumerable_ReturnedCollectionHasNoElements() { IEnumerable<int> source = Enumerable.Empty<int>(); bool wasSelectorCalled = false; IEnumerable<int> result = source.Select(i => { wasSelectorCalled = true; return i + 1; }); bool hadItems = false; foreach (var item in result) { hadItems = true; } Assert.False(hadItems); Assert.False(wasSelectorCalled); } [Fact] public void Select_ExceptionThrownFromSelector_ExceptionPropagatedToTheCaller() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => { throw new InvalidOperationException(); }; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromSelector_IteratorCanBeUsedAfterExceptionIsCaught() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => { if (i == 1) throw new InvalidOperationException(); return i + 1; }; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.MoveNext(); Assert.Equal(3 /* 2 + 1 */, enumerator.Current); } [Fact] public void Select_ExceptionThrownFromCurrentOfSourceIterator_ExceptionPropagatedToTheCaller() { IEnumerable<int> source = new ThrowsOnCurrent(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromCurrentOfSourceIterator_IteratorCanBeUsedAfterExceptionIsCaught() { IEnumerable<int> source = new ThrowsOnCurrent(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.MoveNext(); Assert.Equal(3 /* 2 + 1 */, enumerator.Current); } /// <summary> /// Test enumerator - throws InvalidOperationException from Current after MoveNext called once. /// </summary> private class ThrowsOnCurrent : TestEnumerator { public override int Current { get { var current = base.Current; if (current == 1) throw new InvalidOperationException(); return current; } } } [Fact] public void Select_ExceptionThrownFromMoveNextOfSourceIterator_ExceptionPropagatedToTheCaller() { IEnumerable<int> source = new ThrowsOnMoveNext(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromMoveNextOfSourceIterator_IteratorCanBeUsedAfterExceptionIsCaught() { IEnumerable<int> source = new ThrowsOnMoveNext(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.MoveNext(); Assert.Equal(3 /* 2 + 1 */, enumerator.Current); } [Fact] public void Select_ExceptionThrownFromGetEnumeratorOnSource_ExceptionPropagatedToTheCaller() { IEnumerable<int> source = new ThrowsOnGetEnumerator(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromGetEnumeratorOnSource_CurrentIsSetToDefaultOfItemTypeAndIteratorCanBeUsedAfterExceptionIsCaught() { IEnumerable<int> source = new ThrowsOnGetEnumerator(); Func<int, string> selector = i => i.ToString(); var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); string currentValue = enumerator.Current; Assert.Equal(default(string), currentValue); Assert.True(enumerator.MoveNext()); Assert.Equal("1", enumerator.Current); } [Fact] public void Select_SourceListGetsModifiedDuringIteration_ExceptionIsPropagated() { List<int> source = new List<int>() { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(2 /* 1 + 1 */, enumerator.Current); source.Add(6); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_GetEnumeratorCalledTwice_DifferentInstancesReturned() { int[] source = new[] { 1, 2, 3, 4, 5 }; var query = source.Select(i => i + 1); var enumerator1 = query.GetEnumerator(); var enumerator2 = query.GetEnumerator(); Assert.Same(query, enumerator1); Assert.NotSame(enumerator1, enumerator2); enumerator1.Dispose(); enumerator2.Dispose(); } [Fact] public void Select_ResetCalledOnEnumerator_ThrowsException() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> result = source.Select(selector); IEnumerator<int> enumerator = result.GetEnumerator(); Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Select(i => i); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIndexed() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Select((e, i) => i); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateArray() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToArray().Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateList() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIList() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().AsReadOnly().Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIPartition() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().AsReadOnly().Select(i => i).Skip(1); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void Select_SourceIsArray_Count() { var source = new[] { 1, 2, 3, 4 }; Assert.Equal(source.Length, source.Select(i => i * 2).Count()); } [Fact] public void Select_SourceIsAList_Count() { var source = new List<int> { 1, 2, 3, 4 }; Assert.Equal(source.Count, source.Select(i => i * 2).Count()); } [Fact] public void Select_SourceIsAnIList_Count() { var souce = new List<int> { 1, 2, 3, 4 }.AsReadOnly(); Assert.Equal(souce.Count, souce.Select(i => i * 2).Count()); } [Fact] public void Select_SourceIsArray_Skip() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 6, 8 }, source.Skip(2)); Assert.Equal(new[] { 6, 8 }, source.Skip(2).Skip(-1)); Assert.Equal(new[] { 6, 8 }, source.Skip(1).Skip(1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Skip(-1)); Assert.Empty(source.Skip(4)); Assert.Empty(source.Skip(20)); } [Fact] public void Select_SourceIsList_Skip() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 6, 8 }, source.Skip(2)); Assert.Equal(new[] { 6, 8 }, source.Skip(2).Skip(-1)); Assert.Equal(new[] { 6, 8 }, source.Skip(1).Skip(1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Skip(-1)); Assert.Empty(source.Skip(4)); Assert.Empty(source.Skip(20)); } [Fact] public void Select_SourceIsIList_Skip() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(new[] { 6, 8 }, source.Skip(2)); Assert.Equal(new[] { 6, 8 }, source.Skip(2).Skip(-1)); Assert.Equal(new[] { 6, 8 }, source.Skip(1).Skip(1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Skip(-1)); Assert.Empty(source.Skip(4)); Assert.Empty(source.Skip(20)); } [Fact] public void Select_SourceIsArray_Take() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 2, 4 }, source.Take(2)); Assert.Equal(new[] { 2, 4 }, source.Take(3).Take(2)); Assert.Empty(source.Take(-1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(4)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(40)); Assert.Equal(new[] { 2 }, source.Take(1)); Assert.Equal(new[] { 4 }, source.Skip(1).Take(1)); Assert.Equal(new[] { 6 }, source.Take(3).Skip(2)); Assert.Equal(new[] { 2 }, source.Take(3).Take(1)); } [Fact] public void Select_SourceIsList_Take() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 2, 4 }, source.Take(2)); Assert.Equal(new[] { 2, 4 }, source.Take(3).Take(2)); Assert.Empty(source.Take(-1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(4)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(40)); Assert.Equal(new[] { 2 }, source.Take(1)); Assert.Equal(new[] { 4 }, source.Skip(1).Take(1)); Assert.Equal(new[] { 6 }, source.Take(3).Skip(2)); Assert.Equal(new[] { 2 }, source.Take(3).Take(1)); } [Fact] public void Select_SourceIsIList_Take() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(new[] { 2, 4 }, source.Take(2)); Assert.Equal(new[] { 2, 4 }, source.Take(3).Take(2)); Assert.Empty(source.Take(-1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(4)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(40)); Assert.Equal(new[] { 2 }, source.Take(1)); Assert.Equal(new[] { 4 }, source.Skip(1).Take(1)); Assert.Equal(new[] { 6 }, source.Take(3).Skip(2)); Assert.Equal(new[] { 2 }, source.Take(3).Take(1)); } [Fact] public void Select_SourceIsArray_ElementAt() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAt(i)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(40)); Assert.Equal(6, source.Skip(1).ElementAt(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.Skip(2).ElementAt(9)); } [Fact] public void Select_SourceIsList_ElementAt() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAt(i)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(40)); Assert.Equal(6, source.Skip(1).ElementAt(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.Skip(2).ElementAt(9)); } [Fact] public void Select_SourceIsIList_ElementAt() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAt(i)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(40)); Assert.Equal(6, source.Skip(1).ElementAt(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.Skip(2).ElementAt(9)); } [Fact] public void Select_SourceIsArray_ElementAtOrDefault() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAtOrDefault(i)); Assert.Equal(0, source.ElementAtOrDefault(-1)); Assert.Equal(0, source.ElementAtOrDefault(4)); Assert.Equal(0, source.ElementAtOrDefault(40)); Assert.Equal(6, source.Skip(1).ElementAtOrDefault(1)); Assert.Equal(0, source.Skip(2).ElementAtOrDefault(9)); } [Fact] public void Select_SourceIsList_ElementAtOrDefault() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAtOrDefault(i)); Assert.Equal(0, source.ElementAtOrDefault(-1)); Assert.Equal(0, source.ElementAtOrDefault(4)); Assert.Equal(0, source.ElementAtOrDefault(40)); Assert.Equal(6, source.Skip(1).ElementAtOrDefault(1)); Assert.Equal(0, source.Skip(2).ElementAtOrDefault(9)); } [Fact] public void Select_SourceIsIList_ElementAtOrDefault() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAtOrDefault(i)); Assert.Equal(0, source.ElementAtOrDefault(-1)); Assert.Equal(0, source.ElementAtOrDefault(4)); Assert.Equal(0, source.ElementAtOrDefault(40)); Assert.Equal(6, source.Skip(1).ElementAtOrDefault(1)); Assert.Equal(0, source.Skip(2).ElementAtOrDefault(9)); } [Fact] public void Select_SourceIsArray_First() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); Assert.Equal(6, source.Skip(2).First()); Assert.Equal(6, source.Skip(2).FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Skip(4).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(14).First()); Assert.Equal(0, source.Skip(4).FirstOrDefault()); Assert.Equal(0, source.Skip(14).FirstOrDefault()); var empty = new int[0].Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.First()); Assert.Equal(0, empty.FirstOrDefault()); } [Fact] public void Select_SourceIsList_First() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); Assert.Equal(6, source.Skip(2).First()); Assert.Equal(6, source.Skip(2).FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Skip(4).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(14).First()); Assert.Equal(0, source.Skip(4).FirstOrDefault()); Assert.Equal(0, source.Skip(14).FirstOrDefault()); var empty = new List<int>().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.First()); Assert.Equal(0, empty.FirstOrDefault()); } [Fact] public void Select_SourceIsIList_First() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); Assert.Equal(6, source.Skip(2).First()); Assert.Equal(6, source.Skip(2).FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Skip(4).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(14).First()); Assert.Equal(0, source.Skip(4).FirstOrDefault()); Assert.Equal(0, source.Skip(14).FirstOrDefault()); var empty = new List<int>().AsReadOnly().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.First()); Assert.Equal(0, empty.FirstOrDefault()); } [Fact] public void Select_SourceIsArray_Last() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(8, source.Last()); Assert.Equal(8, source.LastOrDefault()); Assert.Equal(6, source.Take(3).Last()); Assert.Equal(6, source.Take(3).LastOrDefault()); var empty = new int[0].Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.Last()); Assert.Equal(0, empty.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => empty.Skip(1).Last()); Assert.Equal(0, empty.Skip(1).LastOrDefault()); } [Fact] public void Select_SourceIsList_Last() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(8, source.Last()); Assert.Equal(8, source.LastOrDefault()); Assert.Equal(6, source.Take(3).Last()); Assert.Equal(6, source.Take(3).LastOrDefault()); var empty = new List<int>().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.Last()); Assert.Equal(0, empty.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => empty.Skip(1).Last()); Assert.Equal(0, empty.Skip(1).LastOrDefault()); } [Fact] public void Select_SourceIsIList_Last() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(8, source.Last()); Assert.Equal(8, source.LastOrDefault()); Assert.Equal(6, source.Take(3).Last()); Assert.Equal(6, source.Take(3).LastOrDefault()); var empty = new List<int>().AsReadOnly().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.Last()); Assert.Equal(0, empty.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => empty.Skip(1).Last()); Assert.Equal(0, empty.Skip(1).LastOrDefault()); } [Fact] public void Select_SourceIsArray_SkipRepeatCalls() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2).Skip(1); Assert.Equal(source, source); } [Fact] public void Select_SourceIsArraySkipSelect() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2).Skip(1).Select(i => i + 1); Assert.Equal(new[] { 5, 7, 9 }, source); } [Fact] public void Select_SourceIsArrayTakeTake() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2).Take(2).Take(1); Assert.Equal(new[] { 2 }, source); Assert.Equal(new[] { 2 }, source.Take(10)); } [Fact] public void Select_SourceIsListSkipTakeCount() { Assert.Equal(3, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(3).Count()); Assert.Equal(4, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(9).Count()); Assert.Equal(2, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(2).Count()); Assert.Equal(0, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(8).Count()); } [Fact] public void Select_SourceIsListSkipTakeToArray() { Assert.Equal(new[] { 2, 4, 6 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(3).ToArray()); Assert.Equal(new[] { 2, 4, 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(9).ToArray()); Assert.Equal(new[] { 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(2).ToArray()); Assert.Empty(new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(8).ToArray()); } [Fact] public void Select_SourceIsListSkipTakeToList() { Assert.Equal(new[] { 2, 4, 6 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(3).ToList()); Assert.Equal(new[] { 2, 4, 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(9).ToList()); Assert.Equal(new[] { 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(2).ToList()); Assert.Empty(new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(8).ToList()); } [Theory] [MemberData(nameof(MoveNextAfterDisposeData))] public void MoveNextAfterDispose(IEnumerable<int> source) { // Select is specialized for a bunch of different types, so we want // to make sure this holds true for all of them. var identityTransforms = new List<Func<IEnumerable<int>, IEnumerable<int>>> { e => e, e => ForceNotCollection(e), e => e.ToArray(), e => e.ToList(), e => new LinkedList<int>(e), // IList<T> that's not a List e => e.Select(i => i) // Multiple Select() chains are optimized }; foreach (IEnumerable<int> equivalentSource in identityTransforms.Select(t => t(source))) { IEnumerable<int> result = equivalentSource.Select(i => i); using (IEnumerator<int> e = result.GetEnumerator()) { while (e.MoveNext()) ; // Loop until we reach the end of the iterator, @ which pt it gets disposed. Assert.False(e.MoveNext()); // MoveNext should not throw an exception after Dispose. } } } public static IEnumerable<object[]> MoveNextAfterDisposeData() { yield return new object[] { Array.Empty<int>() }; yield return new object[] { new int[1] }; yield return new object[] { Enumerable.Range(1, 30) }; } [Theory] [MemberData(nameof(RunSelectorDuringCountData))] public void RunSelectorDuringCount(IEnumerable<int> source) { int timesRun = 0; var selected = source.Select(i => timesRun++); selected.Count(); Assert.Equal(source.Count(), timesRun); } public static IEnumerable<object[]> RunSelectorDuringCountData() { var transforms = new Func<IEnumerable<int>, IEnumerable<int>>[] { e => e, e => ForceNotCollection(e), e => ForceNotCollection(e).Skip(1), e => ForceNotCollection(e).Where(i => true), e => e.ToArray().Where(i => true), e => e.ToList().Where(i => true), e => new LinkedList<int>(e).Where(i => true), e => e.Select(i => i), e => e.Take(e.Count()), e => e.ToArray(), e => e.ToList(), e => new LinkedList<int>(e) // Implements IList<T>. }; var r = new Random(unchecked((int)0x984bf1a3)); for (int i = 0; i <= 5; i++) { var enumerable = Enumerable.Range(1, i).Select(_ => r.Next()); foreach (var transform in transforms) { yield return new object[] { transform(enumerable) }; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Xunit; namespace System.Linq.Tests { public class SelectTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsStringQuery() { var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" } select x1; var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 } select x2; var q = from x3 in q1 from x4 in q2 select new { a1 = x3, a2 = x4 }; Assert.Equal(q.Select(e => e.a1), q.Select(e => e.a1)); } [Fact] public void SingleElement() { var source = new[] { new { name = "Prakash", custID = 98088 } }; string[] expected = { "Prakash" }; Assert.Equal(expected, source.Select(e => e.name)); } [Fact] public void SelectProperty() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name=(string)null, custID=30349 }, new { name="Prakash", custID=39030 } }; string[] expected = { "Prakash", "Bob", "Chris", null, "Prakash" }; Assert.Equal(expected, source.Select(e => e.name)); } [Fact] public void RunOnce() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name=(string)null, custID=30349 }, new { name="Prakash", custID=39030 } }; string[] expected = { "Prakash", "Bob", "Chris", null, "Prakash" }; Assert.Equal(expected, source.RunOnce().Select(e => e.name)); Assert.Equal(expected, source.ToArray().RunOnce().Select(e => e.name)); Assert.Equal(expected, source.ToList().RunOnce().Select(e => e.name)); } [Fact] public void EmptyWithIndexedSelector() { Assert.Equal(Enumerable.Empty<int>(), Enumerable.Empty<string>().Select((s, i) => s.Length + i)); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void EnumerateFromDifferentThread() { var selected = Enumerable.Range(0, 100).Where(i => i > 3).Select(i => i.ToString()); Task[] tasks = new Task[4]; for (int i = 0; i != 4; ++i) tasks[i] = Task.Run(() => selected.ToList()); Task.WaitAll(tasks); } [Fact] public void SingleElementIndexedSelector() { var source = new[] { new { name = "Prakash", custID = 98088 } }; string[] expected = { "Prakash" }; Assert.Equal(expected, source.Select((e, index) => e.name)); } [Fact] public void SelectPropertyPassingIndex() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name=(string)null, custID=30349 }, new { name="Prakash", custID=39030 } }; string[] expected = { "Prakash", "Bob", "Chris", null, "Prakash" }; Assert.Equal(expected, source.Select((e, i) => e.name)); } [Fact] public void SelectPropertyUsingIndex() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 } }; string[] expected = { "Prakash", null, null }; Assert.Equal(expected, source.Select((e, i) => i == 0 ? e.name : null)); } [Fact] public void SelectPropertyPassingIndexOnLast() { var source = new[]{ new { name="Prakash", custID=98088}, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name="Robert", custID=39033 }, new { name="Allen", custID=39033 }, new { name="Chuck", custID=39033 } }; string[] expected = { null, null, null, null, null, "Chuck" }; Assert.Equal(expected, source.Select((e, i) => i == 5 ? e.name : null)); } [ConditionalFact(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] public void Overflow() { var selected = new FastInfiniteEnumerator<int>().Select((e, i) => e); using (var en = selected.GetEnumerator()) Assert.Throws<OverflowException>(() => { while (en.MoveNext()) { } }); } [Fact] public void Select_SourceIsNull_ArgumentNullExceptionThrown() { IEnumerable<int> source = null; Func<int, int> selector = i => i + 1; AssertExtensions.Throws<ArgumentNullException>("source", () => source.Select(selector)); } [Fact] public void Select_SelectorIsNull_ArgumentNullExceptionThrown_Indexed() { IEnumerable<int> source = Enumerable.Range(1, 10); Func<int, int, int> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => source.Select(selector)); } [Fact] public void Select_SourceIsNull_ArgumentNullExceptionThrown_Indexed() { IEnumerable<int> source = null; Func<int, int, int> selector = (e, i) => i + 1; AssertExtensions.Throws<ArgumentNullException>("source", () => source.Select(selector)); } [Fact] public void Select_SelectorIsNull_ArgumentNullExceptionThrown() { IEnumerable<int> source = Enumerable.Range(1, 10); Func<int, int> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => source.Select(selector)); } [Fact] public void Select_SourceIsAnArray_ExecutionIsDeferred() { bool funcCalled = false; Func<int>[] source = new Func<int>[] { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsAList_ExecutionIsDeferred() { bool funcCalled = false; List<Func<int>> source = new List<Func<int>>() { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsIReadOnlyCollection_ExecutionIsDeferred() { bool funcCalled = false; IReadOnlyCollection<Func<int>> source = new ReadOnlyCollection<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsICollection_ExecutionIsDeferred() { bool funcCalled = false; ICollection<Func<int>> source = new LinkedList<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsIEnumerable_ExecutionIsDeferred() { bool funcCalled = false; IEnumerable<Func<int>> source = Enumerable.Repeat((Func<int>)(() => { funcCalled = true; return 1; }), 1); IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsAnArray_ExecutionIsDeferred() { bool funcCalled = false; Func<int>[] source = new Func<int>[] { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsAList_ExecutionIsDeferred() { bool funcCalled = false; List<Func<int>> source = new List<Func<int>>() { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsIReadOnlyCollection_ExecutionIsDeferred() { bool funcCalled = false; IReadOnlyCollection<Func<int>> source = new ReadOnlyCollection<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsICollection_ExecutionIsDeferred() { bool funcCalled = false; ICollection<Func<int>> source = new LinkedList<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsIEnumerable_ExecutionIsDeferred() { bool funcCalled = false; IEnumerable<Func<int>> source = Enumerable.Repeat((Func<int>)(() => { funcCalled = true; return 1; }), 1); IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsAnArray_ReturnsExpectedValues() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { var expected = selector(source[index]); Assert.Equal(expected, item); index++; } Assert.Equal(source.Length, index); } [Fact] public void Select_SourceIsAList_ReturnsExpectedValues() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { var expected = selector(source[index]); Assert.Equal(expected, item); index++; } Assert.Equal(source.Count, index); } [Fact] public void Select_SourceIsIReadOnlyCollection_ReturnsExpectedValues() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(index); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void Select_SourceIsICollection_ReturnsExpectedValues() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(index); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void Select_SourceIsIEnumerable_ReturnsExpectedValues() { int nbOfItems = 5; IEnumerable<int> source = Enumerable.Range(1, nbOfItems); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(index); Assert.Equal(expected, item); } Assert.Equal(nbOfItems, index); } [Fact] public void Select_SourceIsAnArray_CurrentIsDefaultOfTAfterEnumeration() { int[] source = new[] { 1 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsAList_CurrentIsDefaultOfTAfterEnumeration() { List<int> source = new List<int>() { 1 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsIReadOnlyCollection_CurrentIsDefaultOfTAfterEnumeration() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int>() { 1 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsICollection_CurrentIsDefaultOfTAfterEnumeration() { ICollection<int> source = new LinkedList<int>(new List<int>() { 1 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsIEnumerable_CurrentIsDefaultOfTAfterEnumeration() { IEnumerable<int> source = Enumerable.Repeat(1, 1); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void SelectSelect_SourceIsAnArray_ReturnsExpectedValues() { Func<int, int> selector = i => i + 1; int[] source = new[] { 1, 2, 3, 4, 5 }; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { var expected = selector(selector(source[index])); Assert.Equal(expected, item); index++; } Assert.Equal(source.Length, index); } [Fact] public void SelectSelect_SourceIsAList_ReturnsExpectedValues() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { var expected = selector(selector(source[index])); Assert.Equal(expected, item); index++; } Assert.Equal(source.Count, index); } [Fact] public void SelectSelect_SourceIsIReadOnlyCollection_ReturnsExpectedValues() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(selector(index)); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void SelectSelect_SourceIsICollection_ReturnsExpectedValues() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(selector(index)); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void SelectSelect_SourceIsIEnumerable_ReturnsExpectedValues() { int nbOfItems = 5; IEnumerable<int> source = Enumerable.Range(1, 5); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(selector(index)); Assert.Equal(expected, item); } Assert.Equal(nbOfItems, index); } [Fact] public void Select_SourceIsEmptyEnumerable_ReturnedCollectionHasNoElements() { IEnumerable<int> source = Enumerable.Empty<int>(); bool wasSelectorCalled = false; IEnumerable<int> result = source.Select(i => { wasSelectorCalled = true; return i + 1; }); bool hadItems = false; foreach (var item in result) { hadItems = true; } Assert.False(hadItems); Assert.False(wasSelectorCalled); } [Fact] public void Select_ExceptionThrownFromSelector_ExceptionPropagatedToTheCaller() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => { throw new InvalidOperationException(); }; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromSelector_IteratorCanBeUsedAfterExceptionIsCaught() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => { if (i == 1) throw new InvalidOperationException(); return i + 1; }; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.MoveNext(); Assert.Equal(3 /* 2 + 1 */, enumerator.Current); } [Fact] public void Select_ExceptionThrownFromCurrentOfSourceIterator_ExceptionPropagatedToTheCaller() { IEnumerable<int> source = new ThrowsOnCurrent(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromCurrentOfSourceIterator_IteratorCanBeUsedAfterExceptionIsCaught() { IEnumerable<int> source = new ThrowsOnCurrent(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.MoveNext(); Assert.Equal(3 /* 2 + 1 */, enumerator.Current); } /// <summary> /// Test enumerator - throws InvalidOperationException from Current after MoveNext called once. /// </summary> private class ThrowsOnCurrent : TestEnumerator { public override int Current { get { var current = base.Current; if (current == 1) throw new InvalidOperationException(); return current; } } } [Fact] public void Select_ExceptionThrownFromMoveNextOfSourceIterator_ExceptionPropagatedToTheCaller() { IEnumerable<int> source = new ThrowsOnMoveNext(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromMoveNextOfSourceIterator_IteratorCanBeUsedAfterExceptionIsCaught() { IEnumerable<int> source = new ThrowsOnMoveNext(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.MoveNext(); Assert.Equal(3 /* 2 + 1 */, enumerator.Current); } [Fact] public void Select_ExceptionThrownFromGetEnumeratorOnSource_ExceptionPropagatedToTheCaller() { IEnumerable<int> source = new ThrowsOnGetEnumerator(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromGetEnumeratorOnSource_CurrentIsSetToDefaultOfItemTypeAndIteratorCanBeUsedAfterExceptionIsCaught() { IEnumerable<int> source = new ThrowsOnGetEnumerator(); Func<int, string> selector = i => i.ToString(); var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); string currentValue = enumerator.Current; Assert.Equal(default(string), currentValue); Assert.True(enumerator.MoveNext()); Assert.Equal("1", enumerator.Current); } [Fact] public void Select_SourceListGetsModifiedDuringIteration_ExceptionIsPropagated() { List<int> source = new List<int>() { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(2 /* 1 + 1 */, enumerator.Current); source.Add(6); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_GetEnumeratorCalledTwice_DifferentInstancesReturned() { int[] source = new[] { 1, 2, 3, 4, 5 }; var query = source.Select(i => i + 1); var enumerator1 = query.GetEnumerator(); var enumerator2 = query.GetEnumerator(); Assert.Same(query, enumerator1); Assert.NotSame(enumerator1, enumerator2); enumerator1.Dispose(); enumerator2.Dispose(); } [Fact] public void Select_ResetCalledOnEnumerator_ThrowsException() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> result = source.Select(selector); IEnumerator<int> enumerator = result.GetEnumerator(); Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Select(i => i); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIndexed() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Select((e, i) => i); // Don't insist on this behaviour, but check it's correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateArray() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToArray().Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateList() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIList() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().AsReadOnly().Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIPartition() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().AsReadOnly().Select(i => i).Skip(1); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void Select_SourceIsArray_Count() { var source = new[] { 1, 2, 3, 4 }; Assert.Equal(source.Length, source.Select(i => i * 2).Count()); } [Fact] public void Select_SourceIsAList_Count() { var source = new List<int> { 1, 2, 3, 4 }; Assert.Equal(source.Count, source.Select(i => i * 2).Count()); } [Fact] public void Select_SourceIsAnIList_Count() { var souce = new List<int> { 1, 2, 3, 4 }.AsReadOnly(); Assert.Equal(souce.Count, souce.Select(i => i * 2).Count()); } [Fact] public void Select_SourceIsArray_Skip() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 6, 8 }, source.Skip(2)); Assert.Equal(new[] { 6, 8 }, source.Skip(2).Skip(-1)); Assert.Equal(new[] { 6, 8 }, source.Skip(1).Skip(1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Skip(-1)); Assert.Empty(source.Skip(4)); Assert.Empty(source.Skip(20)); } [Fact] public void Select_SourceIsList_Skip() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 6, 8 }, source.Skip(2)); Assert.Equal(new[] { 6, 8 }, source.Skip(2).Skip(-1)); Assert.Equal(new[] { 6, 8 }, source.Skip(1).Skip(1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Skip(-1)); Assert.Empty(source.Skip(4)); Assert.Empty(source.Skip(20)); } [Fact] public void Select_SourceIsIList_Skip() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(new[] { 6, 8 }, source.Skip(2)); Assert.Equal(new[] { 6, 8 }, source.Skip(2).Skip(-1)); Assert.Equal(new[] { 6, 8 }, source.Skip(1).Skip(1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Skip(-1)); Assert.Empty(source.Skip(4)); Assert.Empty(source.Skip(20)); } [Fact] public void Select_SourceIsArray_Take() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 2, 4 }, source.Take(2)); Assert.Equal(new[] { 2, 4 }, source.Take(3).Take(2)); Assert.Empty(source.Take(-1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(4)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(40)); Assert.Equal(new[] { 2 }, source.Take(1)); Assert.Equal(new[] { 4 }, source.Skip(1).Take(1)); Assert.Equal(new[] { 6 }, source.Take(3).Skip(2)); Assert.Equal(new[] { 2 }, source.Take(3).Take(1)); } [Fact] public void Select_SourceIsList_Take() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 2, 4 }, source.Take(2)); Assert.Equal(new[] { 2, 4 }, source.Take(3).Take(2)); Assert.Empty(source.Take(-1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(4)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(40)); Assert.Equal(new[] { 2 }, source.Take(1)); Assert.Equal(new[] { 4 }, source.Skip(1).Take(1)); Assert.Equal(new[] { 6 }, source.Take(3).Skip(2)); Assert.Equal(new[] { 2 }, source.Take(3).Take(1)); } [Fact] public void Select_SourceIsIList_Take() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(new[] { 2, 4 }, source.Take(2)); Assert.Equal(new[] { 2, 4 }, source.Take(3).Take(2)); Assert.Empty(source.Take(-1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(4)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(40)); Assert.Equal(new[] { 2 }, source.Take(1)); Assert.Equal(new[] { 4 }, source.Skip(1).Take(1)); Assert.Equal(new[] { 6 }, source.Take(3).Skip(2)); Assert.Equal(new[] { 2 }, source.Take(3).Take(1)); } [Fact] public void Select_SourceIsArray_ElementAt() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAt(i)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(40)); Assert.Equal(6, source.Skip(1).ElementAt(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.Skip(2).ElementAt(9)); } [Fact] public void Select_SourceIsList_ElementAt() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAt(i)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(40)); Assert.Equal(6, source.Skip(1).ElementAt(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.Skip(2).ElementAt(9)); } [Fact] public void Select_SourceIsIList_ElementAt() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAt(i)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(4)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(40)); Assert.Equal(6, source.Skip(1).ElementAt(1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => source.Skip(2).ElementAt(9)); } [Fact] public void Select_SourceIsArray_ElementAtOrDefault() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAtOrDefault(i)); Assert.Equal(0, source.ElementAtOrDefault(-1)); Assert.Equal(0, source.ElementAtOrDefault(4)); Assert.Equal(0, source.ElementAtOrDefault(40)); Assert.Equal(6, source.Skip(1).ElementAtOrDefault(1)); Assert.Equal(0, source.Skip(2).ElementAtOrDefault(9)); } [Fact] public void Select_SourceIsList_ElementAtOrDefault() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAtOrDefault(i)); Assert.Equal(0, source.ElementAtOrDefault(-1)); Assert.Equal(0, source.ElementAtOrDefault(4)); Assert.Equal(0, source.ElementAtOrDefault(40)); Assert.Equal(6, source.Skip(1).ElementAtOrDefault(1)); Assert.Equal(0, source.Skip(2).ElementAtOrDefault(9)); } [Fact] public void Select_SourceIsIList_ElementAtOrDefault() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAtOrDefault(i)); Assert.Equal(0, source.ElementAtOrDefault(-1)); Assert.Equal(0, source.ElementAtOrDefault(4)); Assert.Equal(0, source.ElementAtOrDefault(40)); Assert.Equal(6, source.Skip(1).ElementAtOrDefault(1)); Assert.Equal(0, source.Skip(2).ElementAtOrDefault(9)); } [Fact] public void Select_SourceIsArray_First() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); Assert.Equal(6, source.Skip(2).First()); Assert.Equal(6, source.Skip(2).FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Skip(4).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(14).First()); Assert.Equal(0, source.Skip(4).FirstOrDefault()); Assert.Equal(0, source.Skip(14).FirstOrDefault()); var empty = new int[0].Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.First()); Assert.Equal(0, empty.FirstOrDefault()); } [Fact] public void Select_SourceIsList_First() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); Assert.Equal(6, source.Skip(2).First()); Assert.Equal(6, source.Skip(2).FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Skip(4).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(14).First()); Assert.Equal(0, source.Skip(4).FirstOrDefault()); Assert.Equal(0, source.Skip(14).FirstOrDefault()); var empty = new List<int>().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.First()); Assert.Equal(0, empty.FirstOrDefault()); } [Fact] public void Select_SourceIsIList_First() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); Assert.Equal(6, source.Skip(2).First()); Assert.Equal(6, source.Skip(2).FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Skip(4).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(14).First()); Assert.Equal(0, source.Skip(4).FirstOrDefault()); Assert.Equal(0, source.Skip(14).FirstOrDefault()); var empty = new List<int>().AsReadOnly().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.First()); Assert.Equal(0, empty.FirstOrDefault()); } [Fact] public void Select_SourceIsArray_Last() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(8, source.Last()); Assert.Equal(8, source.LastOrDefault()); Assert.Equal(6, source.Take(3).Last()); Assert.Equal(6, source.Take(3).LastOrDefault()); var empty = new int[0].Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.Last()); Assert.Equal(0, empty.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => empty.Skip(1).Last()); Assert.Equal(0, empty.Skip(1).LastOrDefault()); } [Fact] public void Select_SourceIsList_Last() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(8, source.Last()); Assert.Equal(8, source.LastOrDefault()); Assert.Equal(6, source.Take(3).Last()); Assert.Equal(6, source.Take(3).LastOrDefault()); var empty = new List<int>().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.Last()); Assert.Equal(0, empty.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => empty.Skip(1).Last()); Assert.Equal(0, empty.Skip(1).LastOrDefault()); } [Fact] public void Select_SourceIsIList_Last() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(8, source.Last()); Assert.Equal(8, source.LastOrDefault()); Assert.Equal(6, source.Take(3).Last()); Assert.Equal(6, source.Take(3).LastOrDefault()); var empty = new List<int>().AsReadOnly().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.Last()); Assert.Equal(0, empty.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => empty.Skip(1).Last()); Assert.Equal(0, empty.Skip(1).LastOrDefault()); } [Fact] public void Select_SourceIsArray_SkipRepeatCalls() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2).Skip(1); Assert.Equal(source, source); } [Fact] public void Select_SourceIsArraySkipSelect() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2).Skip(1).Select(i => i + 1); Assert.Equal(new[] { 5, 7, 9 }, source); } [Fact] public void Select_SourceIsArrayTakeTake() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2).Take(2).Take(1); Assert.Equal(new[] { 2 }, source); Assert.Equal(new[] { 2 }, source.Take(10)); } [Fact] public void Select_SourceIsListSkipTakeCount() { Assert.Equal(3, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(3).Count()); Assert.Equal(4, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(9).Count()); Assert.Equal(2, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(2).Count()); Assert.Equal(0, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(8).Count()); } [Fact] public void Select_SourceIsListSkipTakeToArray() { Assert.Equal(new[] { 2, 4, 6 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(3).ToArray()); Assert.Equal(new[] { 2, 4, 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(9).ToArray()); Assert.Equal(new[] { 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(2).ToArray()); Assert.Empty(new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(8).ToArray()); } [Fact] public void Select_SourceIsListSkipTakeToList() { Assert.Equal(new[] { 2, 4, 6 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(3).ToList()); Assert.Equal(new[] { 2, 4, 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(9).ToList()); Assert.Equal(new[] { 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(2).ToList()); Assert.Empty(new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(8).ToList()); } [Theory] [MemberData(nameof(MoveNextAfterDisposeData))] public void MoveNextAfterDispose(IEnumerable<int> source) { // Select is specialized for a bunch of different types, so we want // to make sure this holds true for all of them. var identityTransforms = new List<Func<IEnumerable<int>, IEnumerable<int>>> { e => e, e => ForceNotCollection(e), e => e.ToArray(), e => e.ToList(), e => new LinkedList<int>(e), // IList<T> that's not a List e => e.Select(i => i) // Multiple Select() chains are optimized }; foreach (IEnumerable<int> equivalentSource in identityTransforms.Select(t => t(source))) { IEnumerable<int> result = equivalentSource.Select(i => i); using (IEnumerator<int> e = result.GetEnumerator()) { while (e.MoveNext()) ; // Loop until we reach the end of the iterator, @ which pt it gets disposed. Assert.False(e.MoveNext()); // MoveNext should not throw an exception after Dispose. } } } public static IEnumerable<object[]> MoveNextAfterDisposeData() { yield return new object[] { Array.Empty<int>() }; yield return new object[] { new int[1] }; yield return new object[] { Enumerable.Range(1, 30) }; } [Theory] [MemberData(nameof(RunSelectorDuringCountData))] public void RunSelectorDuringCount(IEnumerable<int> source) { int timesRun = 0; var selected = source.Select(i => timesRun++); selected.Count(); Assert.Equal(source.Count(), timesRun); } public static IEnumerable<object[]> RunSelectorDuringCountData() { var transforms = new Func<IEnumerable<int>, IEnumerable<int>>[] { e => e, e => ForceNotCollection(e), e => ForceNotCollection(e).Skip(1), e => ForceNotCollection(e).Where(i => true), e => e.ToArray().Where(i => true), e => e.ToList().Where(i => true), e => new LinkedList<int>(e).Where(i => true), e => e.Select(i => i), e => e.Take(e.Count()), e => e.ToArray(), e => e.ToList(), e => new LinkedList<int>(e) // Implements IList<T>. }; var r = new Random(unchecked((int)0x984bf1a3)); for (int i = 0; i <= 5; i++) { var enumerable = Enumerable.Range(1, i).Select(_ => r.Next()); foreach (var transform in transforms) { yield return new object[] { transform(enumerable) }; } } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/opt/perf/doublenegate/GitHub_57470.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <DebugType>None</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="GitHub_57470.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <DebugType>None</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="GitHub_57470.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/mono/mono/utils/networking-posix.c
/** * \file * Modern posix networking code * * Author: * Rodrigo Kumpera ([email protected]) * * (C) 2015 Xamarin */ #include <config.h> #include <glib.h> #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_GETIFADDRS #include <ifaddrs.h> #endif #ifdef HAVE_QP2GETIFADDRS /* Bizarrely, IBM i implements this, but AIX doesn't, so on i, it has a different name... */ #include <as400_types.h> #include <as400_protos.h> /* Defines to just reuse ifaddrs code */ #define ifaddrs ifaddrs_pase #define freeifaddrs Qp2freeifaddrs #define getifaddrs Qp2getifaddrs #endif #include <mono/utils/networking.h> #include <mono/utils/mono-threads-coop.h> #if HAVE_SIOCGIFCONF || HAVE_GETIFADDRS static void* get_address_from_sockaddr (struct sockaddr *sa) { switch (sa->sa_family) { case AF_INET: return &((struct sockaddr_in*)sa)->sin_addr; #ifdef HAVE_STRUCT_SOCKADDR_IN6 case AF_INET6: return &((struct sockaddr_in6*)sa)->sin6_addr; #endif } return NULL; } #endif #ifdef HAVE_GETADDRINFO int mono_get_address_info (const char *hostname, int port, int flags, MonoAddressInfo **result) { char service_name [16]; struct addrinfo hints, *res = NULL, *info; MonoAddressEntry *cur = NULL, *prev = NULL; MonoAddressInfo *addr_info; int ret; memset (&hints, 0, sizeof (struct addrinfo)); *result = NULL; hints.ai_family = PF_UNSPEC; if (flags & MONO_HINT_IPV4) hints.ai_family = PF_INET; else if (flags & MONO_HINT_IPV6) hints.ai_family = PF_INET6; hints.ai_socktype = SOCK_STREAM; if (flags & MONO_HINT_CANONICAL_NAME) hints.ai_flags = AI_CANONNAME; if (flags & MONO_HINT_NUMERIC_HOST) hints.ai_flags |= AI_NUMERICHOST; /* Some ancient libc don't define AI_ADDRCONFIG */ #ifdef AI_ADDRCONFIG if (flags & MONO_HINT_CONFIGURED_ONLY) hints.ai_flags |= AI_ADDRCONFIG; #endif sprintf (service_name, "%d", port); MONO_ENTER_GC_SAFE; ret = getaddrinfo (hostname, service_name, &hints, &info); MONO_EXIT_GC_SAFE; if (ret) return 1; /* FIXME propagate the error */ res = info; *result = addr_info = g_new0 (MonoAddressInfo, 1); while (res) { cur = g_new0 (MonoAddressEntry, 1); cur->family = res->ai_family; cur->socktype = res->ai_socktype; cur->protocol = res->ai_protocol; if (cur->family == PF_INET) { cur->address_len = sizeof (struct in_addr); cur->address.v4 = ((struct sockaddr_in*)res->ai_addr)->sin_addr; #ifdef HAVE_STRUCT_SOCKADDR_IN6 } else if (cur->family == PF_INET6) { cur->address_len = sizeof (struct in6_addr); cur->address.v6 = ((struct sockaddr_in6*)res->ai_addr)->sin6_addr; #endif } else { g_warning ("Cannot handle address family %d", cur->family); res = res->ai_next; g_free (cur); continue; } if (res->ai_canonname) cur->canonical_name = g_strdup (res->ai_canonname); if (prev) prev->next = cur; else addr_info->entries = cur; prev = cur; res = res->ai_next; } freeaddrinfo (info); return 0; } #endif #if defined(__linux__) && defined(HAVE_GETPROTOBYNAME_R) static int fetch_protocol (const char *proto_name, int *cache, int *proto, int default_val) { if (!*cache) { struct protoent protoent_buf = { 0 }; struct protoent *pent = NULL; char buf[1024]; getprotobyname_r (proto_name, &protoent_buf, buf, 1024, &pent); *proto = pent ? pent->p_proto : default_val; *cache = 1; } return *proto; } #elif HAVE_GETPROTOBYNAME static int fetch_protocol (const char *proto_name, int *cache, int *proto, int default_val) { if (!*cache) { struct protoent *pent; pent = getprotobyname (proto_name); *proto = pent ? pent->p_proto : default_val; *cache = 1; } return *proto; } #elif defined(HOST_WASI) static int fetch_protocol (const char *proto_name, int *cache, int *proto, int default_val) { g_critical("fetch_protocol is not implemented on WASI\n"); return 0; } #endif int mono_networking_get_tcp_protocol (void) { static int cache, proto; return fetch_protocol ("tcp", &cache, &proto, 6); //6 is SOL_TCP on linux } int mono_networking_get_ip_protocol (void) { static int cache, proto; return fetch_protocol ("ip", &cache, &proto, 0); //0 is SOL_IP on linux } int mono_networking_get_ipv6_protocol (void) { static int cache, proto; return fetch_protocol ("ipv6", &cache, &proto, 41); //41 is SOL_IPV6 on linux } #if defined (HAVE_SIOCGIFCONF) #define IFCONF_BUFF_SIZE 1024 #ifndef _SIZEOF_ADDR_IFREQ #define _SIZEOF_ADDR_IFREQ(ifr) (sizeof (struct ifreq)) #endif #define FOREACH_IFR(IFR, IFC) \ for (IFR = (IFC).ifc_req; \ ifr < (struct ifreq*)((char*)(IFC).ifc_req + (IFC).ifc_len); \ ifr = (struct ifreq*)((char*)(IFR) + _SIZEOF_ADDR_IFREQ (*(IFR)))) void * mono_get_local_interfaces (int family, int *interface_count) { int fd; struct ifconf ifc; struct ifreq *ifr; int if_count = 0; gboolean ignore_loopback = FALSE; void *result = NULL; char *result_ptr; *interface_count = 0; if (!mono_address_size_for_family (family)) return NULL; fd = socket (family, SOCK_STREAM, 0); if (fd == -1) return NULL; memset (&ifc, 0, sizeof (ifc)); ifc.ifc_len = IFCONF_BUFF_SIZE; ifc.ifc_buf = (char *)g_malloc (IFCONF_BUFF_SIZE); /* We can't have such huge buffers on the stack. */ if (ioctl (fd, SIOCGIFCONF, &ifc) < 0) goto done; FOREACH_IFR (ifr, ifc) { struct ifreq iflags; //only return addresses of the same type as @family if (ifr->ifr_addr.sa_family != family) { ifr->ifr_name [0] = '\0'; continue; } strcpy (iflags.ifr_name, ifr->ifr_name); //ignore interfaces we can't get props for if (ioctl (fd, SIOCGIFFLAGS, &iflags) < 0) { ifr->ifr_name [0] = '\0'; continue; } //ignore interfaces that are down if ((iflags.ifr_flags & IFF_UP) == 0) { ifr->ifr_name [0] = '\0'; continue; } //If we have a non-loopback iface, don't return any loopback if ((iflags.ifr_flags & IFF_LOOPBACK) == 0) { ignore_loopback = TRUE; ifr->ifr_name [0] = 1;//1 means non-loopback } else { ifr->ifr_name [0] = 2; //2 means loopback } ++if_count; } result = (char *)g_malloc (if_count * mono_address_size_for_family (family)); result_ptr = (char *)result; FOREACH_IFR (ifr, ifc) { if (ifr->ifr_name [0] == '\0') continue; if (ignore_loopback && ifr->ifr_name [0] == 2) { --if_count; continue; } memcpy (result_ptr, get_address_from_sockaddr (&ifr->ifr_addr), mono_address_size_for_family (family)); result_ptr += mono_address_size_for_family (family); } g_assert (result_ptr <= (char*)result + if_count * mono_address_size_for_family (family)); done: *interface_count = if_count; g_free (ifc.ifc_buf); close (fd); return result; } #elif defined(HAVE_GETIFADDRS) || defined(HAVE_QP2GETIFADDRS) void * mono_get_local_interfaces (int family, int *interface_count) { struct ifaddrs *ifap = NULL, *cur; int if_count = 0; gboolean ignore_loopback = FALSE; void *result; char *result_ptr; *interface_count = 0; if (!mono_address_size_for_family (family)) return NULL; if (getifaddrs (&ifap)) return NULL; for (cur = ifap; cur; cur = cur->ifa_next) { //ignore interfaces with no address assigned if (!cur->ifa_addr) continue; //ignore interfaces that don't belong to @family if (cur->ifa_addr->sa_family != family) continue; //ignore interfaces that are down if ((cur->ifa_flags & IFF_UP) == 0) continue; //If we have a non-loopback iface, don't return any loopback if ((cur->ifa_flags & IFF_LOOPBACK) == 0) ignore_loopback = TRUE; if_count++; } result_ptr = result = g_malloc (if_count * mono_address_size_for_family (family)); for (cur = ifap; cur; cur = cur->ifa_next) { if (!cur->ifa_addr) continue; if (cur->ifa_addr->sa_family != family) continue; if ((cur->ifa_flags & IFF_UP) == 0) continue; //we decrement if_count because it did not on the previous loop. if (ignore_loopback && (cur->ifa_flags & IFF_LOOPBACK)) { --if_count; continue; } memcpy (result_ptr, get_address_from_sockaddr (cur->ifa_addr), mono_address_size_for_family (family)); result_ptr += mono_address_size_for_family (family); } g_assert (result_ptr <= (char*)result + if_count * mono_address_size_for_family (family)); freeifaddrs (ifap); *interface_count = if_count; return result; } #endif #ifdef HAVE_GETNAMEINFO gboolean mono_networking_addr_to_str (MonoAddress *address, char *buffer, socklen_t buflen) { MonoSocketAddress saddr; socklen_t len; mono_socket_address_init (&saddr, &len, address->family, &address->addr, 0); return getnameinfo (&saddr.addr, len, buffer, buflen, NULL, 0, NI_NUMERICHOST) == 0; } #elif HAVE_INET_NTOP gboolean mono_networking_addr_to_str (MonoAddress *address, char *buffer, socklen_t buflen) { return inet_ntop (address->family, &address->addr, buffer, buflen) != NULL; } #endif #ifndef _WIN32 // These are already defined in networking-windows.c for Windows void mono_networking_init (void) { //nothing really } void mono_networking_shutdown (void) { //nothing really } #endif
/** * \file * Modern posix networking code * * Author: * Rodrigo Kumpera ([email protected]) * * (C) 2015 Xamarin */ #include <config.h> #include <glib.h> #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_GETIFADDRS #include <ifaddrs.h> #endif #ifdef HAVE_QP2GETIFADDRS /* Bizarrely, IBM i implements this, but AIX doesn't, so on i, it has a different name... */ #include <as400_types.h> #include <as400_protos.h> /* Defines to just reuse ifaddrs code */ #define ifaddrs ifaddrs_pase #define freeifaddrs Qp2freeifaddrs #define getifaddrs Qp2getifaddrs #endif #include <mono/utils/networking.h> #include <mono/utils/mono-threads-coop.h> #if HAVE_SIOCGIFCONF || HAVE_GETIFADDRS static void* get_address_from_sockaddr (struct sockaddr *sa) { switch (sa->sa_family) { case AF_INET: return &((struct sockaddr_in*)sa)->sin_addr; #ifdef HAVE_STRUCT_SOCKADDR_IN6 case AF_INET6: return &((struct sockaddr_in6*)sa)->sin6_addr; #endif } return NULL; } #endif #ifdef HAVE_GETADDRINFO int mono_get_address_info (const char *hostname, int port, int flags, MonoAddressInfo **result) { char service_name [16]; struct addrinfo hints, *res = NULL, *info; MonoAddressEntry *cur = NULL, *prev = NULL; MonoAddressInfo *addr_info; int ret; memset (&hints, 0, sizeof (struct addrinfo)); *result = NULL; hints.ai_family = PF_UNSPEC; if (flags & MONO_HINT_IPV4) hints.ai_family = PF_INET; else if (flags & MONO_HINT_IPV6) hints.ai_family = PF_INET6; hints.ai_socktype = SOCK_STREAM; if (flags & MONO_HINT_CANONICAL_NAME) hints.ai_flags = AI_CANONNAME; if (flags & MONO_HINT_NUMERIC_HOST) hints.ai_flags |= AI_NUMERICHOST; /* Some ancient libc don't define AI_ADDRCONFIG */ #ifdef AI_ADDRCONFIG if (flags & MONO_HINT_CONFIGURED_ONLY) hints.ai_flags |= AI_ADDRCONFIG; #endif sprintf (service_name, "%d", port); MONO_ENTER_GC_SAFE; ret = getaddrinfo (hostname, service_name, &hints, &info); MONO_EXIT_GC_SAFE; if (ret) return 1; /* FIXME propagate the error */ res = info; *result = addr_info = g_new0 (MonoAddressInfo, 1); while (res) { cur = g_new0 (MonoAddressEntry, 1); cur->family = res->ai_family; cur->socktype = res->ai_socktype; cur->protocol = res->ai_protocol; if (cur->family == PF_INET) { cur->address_len = sizeof (struct in_addr); cur->address.v4 = ((struct sockaddr_in*)res->ai_addr)->sin_addr; #ifdef HAVE_STRUCT_SOCKADDR_IN6 } else if (cur->family == PF_INET6) { cur->address_len = sizeof (struct in6_addr); cur->address.v6 = ((struct sockaddr_in6*)res->ai_addr)->sin6_addr; #endif } else { g_warning ("Cannot handle address family %d", cur->family); res = res->ai_next; g_free (cur); continue; } if (res->ai_canonname) cur->canonical_name = g_strdup (res->ai_canonname); if (prev) prev->next = cur; else addr_info->entries = cur; prev = cur; res = res->ai_next; } freeaddrinfo (info); return 0; } #endif #if defined(__linux__) && defined(HAVE_GETPROTOBYNAME_R) static int fetch_protocol (const char *proto_name, int *cache, int *proto, int default_val) { if (!*cache) { struct protoent protoent_buf = { 0 }; struct protoent *pent = NULL; char buf[1024]; getprotobyname_r (proto_name, &protoent_buf, buf, 1024, &pent); *proto = pent ? pent->p_proto : default_val; *cache = 1; } return *proto; } #elif HAVE_GETPROTOBYNAME static int fetch_protocol (const char *proto_name, int *cache, int *proto, int default_val) { if (!*cache) { struct protoent *pent; pent = getprotobyname (proto_name); *proto = pent ? pent->p_proto : default_val; *cache = 1; } return *proto; } #elif defined(HOST_WASI) static int fetch_protocol (const char *proto_name, int *cache, int *proto, int default_val) { g_critical("fetch_protocol is not implemented on WASI\n"); return 0; } #endif int mono_networking_get_tcp_protocol (void) { static int cache, proto; return fetch_protocol ("tcp", &cache, &proto, 6); //6 is SOL_TCP on linux } int mono_networking_get_ip_protocol (void) { static int cache, proto; return fetch_protocol ("ip", &cache, &proto, 0); //0 is SOL_IP on linux } int mono_networking_get_ipv6_protocol (void) { static int cache, proto; return fetch_protocol ("ipv6", &cache, &proto, 41); //41 is SOL_IPV6 on linux } #if defined (HAVE_SIOCGIFCONF) #define IFCONF_BUFF_SIZE 1024 #ifndef _SIZEOF_ADDR_IFREQ #define _SIZEOF_ADDR_IFREQ(ifr) (sizeof (struct ifreq)) #endif #define FOREACH_IFR(IFR, IFC) \ for (IFR = (IFC).ifc_req; \ ifr < (struct ifreq*)((char*)(IFC).ifc_req + (IFC).ifc_len); \ ifr = (struct ifreq*)((char*)(IFR) + _SIZEOF_ADDR_IFREQ (*(IFR)))) void * mono_get_local_interfaces (int family, int *interface_count) { int fd; struct ifconf ifc; struct ifreq *ifr; int if_count = 0; gboolean ignore_loopback = FALSE; void *result = NULL; char *result_ptr; *interface_count = 0; if (!mono_address_size_for_family (family)) return NULL; fd = socket (family, SOCK_STREAM, 0); if (fd == -1) return NULL; memset (&ifc, 0, sizeof (ifc)); ifc.ifc_len = IFCONF_BUFF_SIZE; ifc.ifc_buf = (char *)g_malloc (IFCONF_BUFF_SIZE); /* We can't have such huge buffers on the stack. */ if (ioctl (fd, SIOCGIFCONF, &ifc) < 0) goto done; FOREACH_IFR (ifr, ifc) { struct ifreq iflags; //only return addresses of the same type as @family if (ifr->ifr_addr.sa_family != family) { ifr->ifr_name [0] = '\0'; continue; } strcpy (iflags.ifr_name, ifr->ifr_name); //ignore interfaces we can't get props for if (ioctl (fd, SIOCGIFFLAGS, &iflags) < 0) { ifr->ifr_name [0] = '\0'; continue; } //ignore interfaces that are down if ((iflags.ifr_flags & IFF_UP) == 0) { ifr->ifr_name [0] = '\0'; continue; } //If we have a non-loopback iface, don't return any loopback if ((iflags.ifr_flags & IFF_LOOPBACK) == 0) { ignore_loopback = TRUE; ifr->ifr_name [0] = 1;//1 means non-loopback } else { ifr->ifr_name [0] = 2; //2 means loopback } ++if_count; } result = (char *)g_malloc (if_count * mono_address_size_for_family (family)); result_ptr = (char *)result; FOREACH_IFR (ifr, ifc) { if (ifr->ifr_name [0] == '\0') continue; if (ignore_loopback && ifr->ifr_name [0] == 2) { --if_count; continue; } memcpy (result_ptr, get_address_from_sockaddr (&ifr->ifr_addr), mono_address_size_for_family (family)); result_ptr += mono_address_size_for_family (family); } g_assert (result_ptr <= (char*)result + if_count * mono_address_size_for_family (family)); done: *interface_count = if_count; g_free (ifc.ifc_buf); close (fd); return result; } #elif defined(HAVE_GETIFADDRS) || defined(HAVE_QP2GETIFADDRS) void * mono_get_local_interfaces (int family, int *interface_count) { struct ifaddrs *ifap = NULL, *cur; int if_count = 0; gboolean ignore_loopback = FALSE; void *result; char *result_ptr; *interface_count = 0; if (!mono_address_size_for_family (family)) return NULL; if (getifaddrs (&ifap)) return NULL; for (cur = ifap; cur; cur = cur->ifa_next) { //ignore interfaces with no address assigned if (!cur->ifa_addr) continue; //ignore interfaces that don't belong to @family if (cur->ifa_addr->sa_family != family) continue; //ignore interfaces that are down if ((cur->ifa_flags & IFF_UP) == 0) continue; //If we have a non-loopback iface, don't return any loopback if ((cur->ifa_flags & IFF_LOOPBACK) == 0) ignore_loopback = TRUE; if_count++; } result_ptr = result = g_malloc (if_count * mono_address_size_for_family (family)); for (cur = ifap; cur; cur = cur->ifa_next) { if (!cur->ifa_addr) continue; if (cur->ifa_addr->sa_family != family) continue; if ((cur->ifa_flags & IFF_UP) == 0) continue; //we decrement if_count because it did not on the previous loop. if (ignore_loopback && (cur->ifa_flags & IFF_LOOPBACK)) { --if_count; continue; } memcpy (result_ptr, get_address_from_sockaddr (cur->ifa_addr), mono_address_size_for_family (family)); result_ptr += mono_address_size_for_family (family); } g_assert (result_ptr <= (char*)result + if_count * mono_address_size_for_family (family)); freeifaddrs (ifap); *interface_count = if_count; return result; } #endif #ifdef HAVE_GETNAMEINFO gboolean mono_networking_addr_to_str (MonoAddress *address, char *buffer, socklen_t buflen) { MonoSocketAddress saddr; socklen_t len; mono_socket_address_init (&saddr, &len, address->family, &address->addr, 0); return getnameinfo (&saddr.addr, len, buffer, buflen, NULL, 0, NI_NUMERICHOST) == 0; } #elif HAVE_INET_NTOP gboolean mono_networking_addr_to_str (MonoAddress *address, char *buffer, socklen_t buflen) { return inet_ntop (address->family, &address->addr, buffer, buflen) != NULL; } #endif #ifndef _WIN32 // These are already defined in networking-windows.c for Windows void mono_networking_init (void) { //nothing really } void mono_networking_shutdown (void) { //nothing really } #endif
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Linq.Expressions/tests/TestExtensions/TestOrderAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Linq.Expressions.Tests { /// <summary>Defines an order in which tests must be taken, enforced by <see cref="TestOrderer"/></summary> /// <remarks>Order must be non-negative. Tests ordered as zero take place in the same batch as those /// with no such attribute set.</remarks> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal class TestOrderAttribute : Attribute { /// <summary> /// Initializes a <see cref="TestOrderAttribute"/> object. /// </summary> /// <param name="order">The order of the batch in which the test must run.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="order"/> was less than zero.</exception> public TestOrderAttribute(int order) { if (order < 0) { throw new ArgumentOutOfRangeException(nameof(order)); } Order = order; } /// <summary>The order of the batch in which the test must run.</summary> public int Order { get; private set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Linq.Expressions.Tests { /// <summary>Defines an order in which tests must be taken, enforced by <see cref="TestOrderer"/></summary> /// <remarks>Order must be non-negative. Tests ordered as zero take place in the same batch as those /// with no such attribute set.</remarks> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal class TestOrderAttribute : Attribute { /// <summary> /// Initializes a <see cref="TestOrderAttribute"/> object. /// </summary> /// <param name="order">The order of the batch in which the test must run.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="order"/> was less than zero.</exception> public TestOrderAttribute(int order) { if (order < 0) { throw new ArgumentOutOfRangeException(nameof(order)); } Order = order; } /// <summary>The order of the batch in which the test must run.</summary> public int Order { get; private set; } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/box-unbox/box-unbox038.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="box-unbox038.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="box-unbox038.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Text.Json/gen/Reflection/MetadataLoadContextInternal.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DotnetRuntime.Extensions; namespace System.Text.Json.Reflection { internal class MetadataLoadContextInternal { private readonly Compilation _compilation; public MetadataLoadContextInternal(Compilation compilation) { _compilation = compilation; } public Compilation Compilation => _compilation; public Type? Resolve(Type type) { Debug.Assert(!type.IsArray, "Resolution logic only capable of handling named types."); return Resolve(type.FullName!); } public Type? Resolve(string fullyQualifiedMetadataName) { INamedTypeSymbol? typeSymbol = _compilation.GetBestTypeByMetadataName(fullyQualifiedMetadataName); return typeSymbol.AsType(this); } public Type Resolve(SpecialType specialType) { INamedTypeSymbol? typeSymbol = _compilation.GetSpecialType(specialType); return typeSymbol.AsType(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.DotnetRuntime.Extensions; namespace System.Text.Json.Reflection { internal class MetadataLoadContextInternal { private readonly Compilation _compilation; public MetadataLoadContextInternal(Compilation compilation) { _compilation = compilation; } public Compilation Compilation => _compilation; public Type? Resolve(Type type) { Debug.Assert(!type.IsArray, "Resolution logic only capable of handling named types."); return Resolve(type.FullName!); } public Type? Resolve(string fullyQualifiedMetadataName) { INamedTypeSymbol? typeSymbol = _compilation.GetBestTypeByMetadataName(fullyQualifiedMetadataName); return typeSymbol.AsType(this); } public Type Resolve(SpecialType specialType) { INamedTypeSymbol? typeSymbol = _compilation.GetSpecialType(specialType); return typeSymbol.AsType(this); } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/HardwareIntrinsics/X86/Sse41/Insert.UInt32.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertUInt321() { var test = new InsertScalarTest__InsertUInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertScalarTest__InsertUInt321 { private struct TestStruct { public Vector128<UInt32> _fld; public UInt32 _scalarFldData; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); testStruct._scalarFldData = (uint)2; return testStruct; } public void RunStructFldScenario(InsertScalarTest__InsertUInt321 testClass) { var result = Sse41.Insert(_fld, _scalarFldData, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, _scalarFldData, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private static UInt32 _scalarClsData = (uint)2; private static Vector128<UInt32> _clsVar; private Vector128<UInt32> _fld; private UInt32 _scalarFldData = (uint)2; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static InsertScalarTest__InsertUInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public InsertScalarTest__InsertUInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); var result = Sse41.Insert( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), (uint)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, (uint)2, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); UInt32 localData = (uint)2; UInt32* ptr = &localData; var result = Sse41.Insert( Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), *ptr, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); UInt32 localData = (uint)2; UInt32* ptr = &localData; var result = Sse41.Insert( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), *ptr, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<UInt32>), typeof(UInt32), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), (uint)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, (uint)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<UInt32>), typeof(UInt32), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), (uint)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, (uint)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<UInt32>), typeof(UInt32), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), (uint)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, (uint)2, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Insert( _clsVar, _scalarClsData, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _scalarClsData,_dataTable.outArrayPtr); } public void RunLclVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario)); UInt32 localData = (uint)2; var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr); var result = Sse41.Insert(firstOp, localData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); UInt32 localData = (uint)2; var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, localData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); UInt32 localData = (uint)2; var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, localData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertScalarTest__InsertUInt321(); var result = Sse41.Insert(test._fld, test._scalarFldData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Insert(_fld, _scalarFldData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _scalarFldData, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Insert(test._fld, test._scalarFldData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> firstOp, UInt32 scalarData, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(void* firstOp, UInt32 scalarData, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32 scalarData, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if ((i == 1 ? result[i] != scalarData : result[i] != firstOp[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<UInt32>(Vector128<UInt32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertUInt321() { var test = new InsertScalarTest__InsertUInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertScalarTest__InsertUInt321 { private struct TestStruct { public Vector128<UInt32> _fld; public UInt32 _scalarFldData; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); testStruct._scalarFldData = (uint)2; return testStruct; } public void RunStructFldScenario(InsertScalarTest__InsertUInt321 testClass) { var result = Sse41.Insert(_fld, _scalarFldData, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, _scalarFldData, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private static UInt32 _scalarClsData = (uint)2; private static Vector128<UInt32> _clsVar; private Vector128<UInt32> _fld; private UInt32 _scalarFldData = (uint)2; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static InsertScalarTest__InsertUInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public InsertScalarTest__InsertUInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); var result = Sse41.Insert( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), (uint)2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, (uint)2, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); UInt32 localData = (uint)2; UInt32* ptr = &localData; var result = Sse41.Insert( Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), *ptr, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); UInt32 localData = (uint)2; UInt32* ptr = &localData; var result = Sse41.Insert( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), *ptr, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<UInt32>), typeof(UInt32), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), (uint)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, (uint)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<UInt32>), typeof(UInt32), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), (uint)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, (uint)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<UInt32>), typeof(UInt32), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), (uint)2, (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, (uint)2, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Insert( _clsVar, _scalarClsData, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _scalarClsData,_dataTable.outArrayPtr); } public void RunLclVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario)); UInt32 localData = (uint)2; var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr); var result = Sse41.Insert(firstOp, localData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); UInt32 localData = (uint)2; var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, localData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); UInt32 localData = (uint)2; var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, localData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertScalarTest__InsertUInt321(); var result = Sse41.Insert(test._fld, test._scalarFldData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Insert(_fld, _scalarFldData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _scalarFldData, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Insert(test._fld, test._scalarFldData, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> firstOp, UInt32 scalarData, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(void* firstOp, UInt32 scalarData, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32 scalarData, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if ((i == 1 ? result[i] != scalarData : result[i] != firstOp[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<UInt32>(Vector128<UInt32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Performance/CodeQuality/SIMD/RayTracer/ISect.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // internal class ISect { public SceneObject Thing; public Ray Ray; public double Dist; public ISect(SceneObject thing, Ray ray, double dist) { Thing = thing; Ray = ray; Dist = dist; } public static bool IsNull(ISect sect) { return sect == null; } public readonly static ISect Null = null; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // internal class ISect { public SceneObject Thing; public Ray Ray; public double Dist; public ISect(SceneObject thing, Ray ray, double dist) { Thing = thing; Ray = ray; Dist = dist; } public static bool IsNull(ISect sect) { return sect == null; } public readonly static ISect Null = null; }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/native/libs/System.Security.Cryptography.Native/pal_ocsp.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_ocsp.h" void CryptoNative_OcspRequestDestroy(OCSP_REQUEST* request) { if (request != NULL) { OCSP_REQUEST_free(request); } } int32_t CryptoNative_GetOcspRequestDerSize(OCSP_REQUEST* req) { ERR_clear_error(); return i2d_OCSP_REQUEST(req, NULL); } int32_t CryptoNative_EncodeOcspRequest(OCSP_REQUEST* req, uint8_t* buf) { ERR_clear_error(); return i2d_OCSP_REQUEST(req, &buf); } OCSP_RESPONSE* CryptoNative_DecodeOcspResponse(const uint8_t* buf, int32_t len) { ERR_clear_error(); if (buf == NULL || len == 0) { return NULL; } return d2i_OCSP_RESPONSE(NULL, &buf, len); } void CryptoNative_OcspResponseDestroy(OCSP_RESPONSE* response) { if (response != NULL) { OCSP_RESPONSE_free(response); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_ocsp.h" void CryptoNative_OcspRequestDestroy(OCSP_REQUEST* request) { if (request != NULL) { OCSP_REQUEST_free(request); } } int32_t CryptoNative_GetOcspRequestDerSize(OCSP_REQUEST* req) { ERR_clear_error(); return i2d_OCSP_REQUEST(req, NULL); } int32_t CryptoNative_EncodeOcspRequest(OCSP_REQUEST* req, uint8_t* buf) { ERR_clear_error(); return i2d_OCSP_REQUEST(req, &buf); } OCSP_RESPONSE* CryptoNative_DecodeOcspResponse(const uint8_t* buf, int32_t len) { ERR_clear_error(); if (buf == NULL || len == 0) { return NULL; } return d2i_OCSP_RESPONSE(NULL, &buf, len); } void CryptoNative_OcspResponseDestroy(OCSP_RESPONSE* response) { if (response != NULL) { OCSP_RESPONSE_free(response); } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Methodical/flowgraph/dev10_bug679053/cpblkInt32.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="cpblkInt32.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="cpblkInt32.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/FunctionalTests/WebAssembly/Browser/RuntimeConfig/index.html
<!DOCTYPE html> <!-- Licensed to the .NET Foundation under one or more agreements. --> <!-- The .NET Foundation licenses this file to you under the MIT license. --> <html> <head> <title>Runtime config test</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h3 id="header">Runtime config test</h3> Result from Sample.Test.TestMeaning: <span id="out"></span> <script type='text/javascript'> function set_exit_code(exit_code, reason) { /* Set result in a tests_done element, to be read by xharness */ var tests_done_elem = document.createElement("label"); tests_done_elem.id = "tests_done"; tests_done_elem.innerHTML = exit_code.toString(); document.body.appendChild(tests_done_elem); console.log(`WASM EXIT ${exit_code}`); }; var App = { init: function () { const testMeaning = BINDING.bind_static_method("[WebAssembly.Browser.RuntimeConfig.Test] Sample.Test:TestMeaning"); var exit_code = testMeaning(); document.getElementById("out").innerHTML = exit_code; console.debug(`exit_code: ${exit_code}`); set_exit_code(exit_code); }, }; </script> <script type="text/javascript" src="main.js"></script> <script defer src="dotnet.js"></script> </body> </html>
<!DOCTYPE html> <!-- Licensed to the .NET Foundation under one or more agreements. --> <!-- The .NET Foundation licenses this file to you under the MIT license. --> <html> <head> <title>Runtime config test</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h3 id="header">Runtime config test</h3> Result from Sample.Test.TestMeaning: <span id="out"></span> <script type='text/javascript'> function set_exit_code(exit_code, reason) { /* Set result in a tests_done element, to be read by xharness */ var tests_done_elem = document.createElement("label"); tests_done_elem.id = "tests_done"; tests_done_elem.innerHTML = exit_code.toString(); document.body.appendChild(tests_done_elem); console.log(`WASM EXIT ${exit_code}`); }; var App = { init: function () { const testMeaning = BINDING.bind_static_method("[WebAssembly.Browser.RuntimeConfig.Test] Sample.Test:TestMeaning"); var exit_code = testMeaning(); document.getElementById("out").innerHTML = exit_code; console.debug(`exit_code: ${exit_code}`); set_exit_code(exit_code); }, }; </script> <script type="text/javascript" src="main.js"></script> <script defer src="dotnet.js"></script> </body> </html>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/jit64/gc/misc/struct5_5.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; struct Pad { #pragma warning disable 0414 public double d1; public double d2; public double d3; public double d4; public double d5; public double d6; public double d7; public double d8; public double d9; public double d10; public double d11; public double d12; public double d13; public double d14; public double d15; public double d16; public double d17; public double d18; public double d19; public double d20; public double d21; public double d22; public double d23; public double d24; public double d25; public double d26; public double d27; public double d28; public double d29; public double d30; #pragma warning restore 0414 } struct S { public String str; public Pad pad; #pragma warning disable 0414 public String str2; #pragma warning restore 0414 public S(String s) { str = s; str2 = s + str; pad.d1 = pad.d2 = pad.d3 = pad.d4 = pad.d5 = pad.d6 = pad.d7 = pad.d8 = pad.d9 = pad.d10 = pad.d11 = pad.d12 = pad.d13 = pad.d14 = pad.d15 = pad.d16 = pad.d17 = pad.d18 = pad.d19 = pad.d20 = pad.d21 = pad.d22 = pad.d23 = pad.d24 = pad.d25 = pad.d26 = pad.d27 = pad.d28 = pad.d29 = pad.d30 = 3.3; } } class Test_struct5_5 { public static void c(S s1, S s2, S s3, S s4) { Console.WriteLine(s1.str + s2.str + s3.str + s4.str); } public static int Main() { S sM = new S("test"); S sM2 = new S("test2"); S sM3 = new S("test3"); S sM4 = new S("test4"); c(sM, sM2, sM3, sM4); return 100; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; struct Pad { #pragma warning disable 0414 public double d1; public double d2; public double d3; public double d4; public double d5; public double d6; public double d7; public double d8; public double d9; public double d10; public double d11; public double d12; public double d13; public double d14; public double d15; public double d16; public double d17; public double d18; public double d19; public double d20; public double d21; public double d22; public double d23; public double d24; public double d25; public double d26; public double d27; public double d28; public double d29; public double d30; #pragma warning restore 0414 } struct S { public String str; public Pad pad; #pragma warning disable 0414 public String str2; #pragma warning restore 0414 public S(String s) { str = s; str2 = s + str; pad.d1 = pad.d2 = pad.d3 = pad.d4 = pad.d5 = pad.d6 = pad.d7 = pad.d8 = pad.d9 = pad.d10 = pad.d11 = pad.d12 = pad.d13 = pad.d14 = pad.d15 = pad.d16 = pad.d17 = pad.d18 = pad.d19 = pad.d20 = pad.d21 = pad.d22 = pad.d23 = pad.d24 = pad.d25 = pad.d26 = pad.d27 = pad.d28 = pad.d29 = pad.d30 = 3.3; } } class Test_struct5_5 { public static void c(S s1, S s2, S s3, S s4) { Console.WriteLine(s1.str + s2.str + s3.str + s4.str); } public static int Main() { S sM = new S("test"); S sM2 = new S("test2"); S sM3 = new S("test3"); S sM4 = new S("test4"); c(sM, sM2, sM3, sM4); return 100; } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyAddBySelectedScalar.Vector64.Int16.Vector128.Int16.7.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] inArray3, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int16> _fld1; public Vector64<Int16> _fld2; public Vector128<Int16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 testClass) { var result = AdvSimd.MultiplyAddBySelectedScalar(_fld1, _fld2, _fld3, 7); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly byte Imm = 7; private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Int16[] _data3 = new Int16[Op3ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private static Vector128<Int16> _clsVar3; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private Vector128<Int16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyAddBySelectedScalar( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddBySelectedScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddBySelectedScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyAddBySelectedScalar( _clsVar1, _clsVar2, _clsVar3, 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) fixed (Vector128<Int16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(pClsVar2)), AdvSimd.LoadVector128((Int16*)(pClsVar3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyAddBySelectedScalar(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyAddBySelectedScalar(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); var result = AdvSimd.MultiplyAddBySelectedScalar(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) fixed (Vector128<Int16>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyAddBySelectedScalar(_fld1, _fld2, _fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddBySelectedScalar(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&test._fld2)), AdvSimd.LoadVector128((Int16*)(&test._fld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, Vector128<Int16> op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] thirdOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyAdd(firstOp[i], secondOp[i], thirdOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyAddBySelectedScalar)}<Int16>(Vector64<Int16>, Vector64<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] inArray3, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int16> _fld1; public Vector64<Int16> _fld2; public Vector128<Int16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 testClass) { var result = AdvSimd.MultiplyAddBySelectedScalar(_fld1, _fld2, _fld3, 7); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly byte Imm = 7; private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Int16[] _data3 = new Int16[Op3ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private static Vector128<Int16> _clsVar3; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private Vector128<Int16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyAddBySelectedScalar( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddBySelectedScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddBySelectedScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyAddBySelectedScalar( _clsVar1, _clsVar2, _clsVar3, 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) fixed (Vector128<Int16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(pClsVar2)), AdvSimd.LoadVector128((Int16*)(pClsVar3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyAddBySelectedScalar(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyAddBySelectedScalar(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); var result = AdvSimd.MultiplyAddBySelectedScalar(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyAddBySelectedScalar_Vector64_Int16_Vector128_Int16_7(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) fixed (Vector128<Int16>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyAddBySelectedScalar(_fld1, _fld2, _fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) fixed (Vector128<Int16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), AdvSimd.LoadVector128((Int16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddBySelectedScalar(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddBySelectedScalar( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&test._fld2)), AdvSimd.LoadVector128((Int16*)(&test._fld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, Vector128<Int16> op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] inArray3 = new Int16[Op3ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] thirdOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyAdd(firstOp[i], secondOp[i], thirdOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyAddBySelectedScalar)}<Int16>(Vector64<Int16>, Vector64<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Speech/src/Internal/SrgsCompiler/CfgRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Speech.Internal.SrgsParser; namespace System.Speech.Internal.SrgsCompiler { internal struct CfgRule { #region Constructors internal CfgRule(int id, int nameOffset, uint flag) { _flag = flag; _nameOffset = nameOffset; _id = id; } internal CfgRule(int id, int nameOffset, SPCFGRULEATTRIBUTES attributes) { _flag = 0; _nameOffset = nameOffset; _id = id; TopLevel = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_TopLevel) != 0); DefaultActive = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_Active) != 0); PropRule = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_Interpreter) != 0); Export = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_Export) != 0); Dynamic = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_Dynamic) != 0); Import = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_Import) != 0); } #endregion #region Internal Properties internal bool TopLevel { get { return ((_flag & 0x0001) != 0); } set { if (value) { _flag |= 0x0001; } else { _flag &= ~(uint)0x0001; } } } internal bool DefaultActive { set { if (value) { _flag |= 0x0002; } else { _flag &= ~(uint)0x0002; } } } internal bool PropRule { set { if (value) { _flag |= 0x0004; } else { _flag &= ~(uint)0x0004; } } } internal bool Import { get { return ((_flag & 0x0008) != 0); } set { if (value) { _flag |= 0x0008; } else { _flag &= ~(uint)0x0008; } } } internal bool Export { get { return ((_flag & 0x0010) != 0); } set { if (value) { _flag |= 0x0010; } else { _flag &= ~(uint)0x0010; } } } internal bool HasResources { get { return ((_flag & 0x0020) != 0); } } internal bool Dynamic { get { return ((_flag & 0x0040) != 0); } set { if (value) { _flag |= 0x0040; } else { _flag &= ~(uint)0x0040; } } } internal bool HasDynamicRef { get { return ((_flag & 0x0080) != 0); } set { if (value) { _flag |= 0x0080; } else { _flag &= ~(uint)0x0080; } } } internal uint FirstArcIndex { get { return (_flag >> 8) & 0x3FFFFF; } set { if (value > 0x3FFFFF) { XmlParser.ThrowSrgsException(SRID.TooManyArcs); } _flag &= ~((uint)0x3FFFFF << 8); _flag |= value << 8; } } internal bool DirtyRule { set { if (value) { _flag |= 0x80000000; } else { _flag &= ~0x80000000; } } } #endregion #region Internal Fields // should be private but the order is absolutely key for marshalling internal uint _flag; internal int _nameOffset; internal int _id; #endregion } #region Internal Enumeration [Flags] internal enum SPCFGRULEATTRIBUTES { SPRAF_TopLevel = (1 << 0), SPRAF_Active = (1 << 1), SPRAF_Export = (1 << 2), SPRAF_Import = (1 << 3), SPRAF_Interpreter = (1 << 4), SPRAF_Dynamic = (1 << 5), SPRAF_Root = (1 << 6), SPRAF_AutoPause = (1 << 16), SPRAF_UserDelimited = (1 << 17) } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Speech.Internal.SrgsParser; namespace System.Speech.Internal.SrgsCompiler { internal struct CfgRule { #region Constructors internal CfgRule(int id, int nameOffset, uint flag) { _flag = flag; _nameOffset = nameOffset; _id = id; } internal CfgRule(int id, int nameOffset, SPCFGRULEATTRIBUTES attributes) { _flag = 0; _nameOffset = nameOffset; _id = id; TopLevel = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_TopLevel) != 0); DefaultActive = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_Active) != 0); PropRule = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_Interpreter) != 0); Export = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_Export) != 0); Dynamic = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_Dynamic) != 0); Import = ((attributes & SPCFGRULEATTRIBUTES.SPRAF_Import) != 0); } #endregion #region Internal Properties internal bool TopLevel { get { return ((_flag & 0x0001) != 0); } set { if (value) { _flag |= 0x0001; } else { _flag &= ~(uint)0x0001; } } } internal bool DefaultActive { set { if (value) { _flag |= 0x0002; } else { _flag &= ~(uint)0x0002; } } } internal bool PropRule { set { if (value) { _flag |= 0x0004; } else { _flag &= ~(uint)0x0004; } } } internal bool Import { get { return ((_flag & 0x0008) != 0); } set { if (value) { _flag |= 0x0008; } else { _flag &= ~(uint)0x0008; } } } internal bool Export { get { return ((_flag & 0x0010) != 0); } set { if (value) { _flag |= 0x0010; } else { _flag &= ~(uint)0x0010; } } } internal bool HasResources { get { return ((_flag & 0x0020) != 0); } } internal bool Dynamic { get { return ((_flag & 0x0040) != 0); } set { if (value) { _flag |= 0x0040; } else { _flag &= ~(uint)0x0040; } } } internal bool HasDynamicRef { get { return ((_flag & 0x0080) != 0); } set { if (value) { _flag |= 0x0080; } else { _flag &= ~(uint)0x0080; } } } internal uint FirstArcIndex { get { return (_flag >> 8) & 0x3FFFFF; } set { if (value > 0x3FFFFF) { XmlParser.ThrowSrgsException(SRID.TooManyArcs); } _flag &= ~((uint)0x3FFFFF << 8); _flag |= value << 8; } } internal bool DirtyRule { set { if (value) { _flag |= 0x80000000; } else { _flag &= ~0x80000000; } } } #endregion #region Internal Fields // should be private but the order is absolutely key for marshalling internal uint _flag; internal int _nameOffset; internal int _id; #endregion } #region Internal Enumeration [Flags] internal enum SPCFGRULEATTRIBUTES { SPRAF_TopLevel = (1 << 0), SPRAF_Active = (1 << 1), SPRAF_Export = (1 << 2), SPRAF_Import = (1 << 3), SPRAF_Interpreter = (1 << 4), SPRAF_Dynamic = (1 << 5), SPRAF_Root = (1 << 6), SPRAF_AutoPause = (1 << 16), SPRAF_UserDelimited = (1 << 17) } #endregion }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Methodical/MDArray/GaussJordan/plainarr_cs_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="plainarr.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="plainarr.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/HardwareIntrinsics/X86/Fma_Vector256/MultiplySubtractAdd.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplySubtractAddSingle() { var test = new AlternatingTernaryOpTest__MultiplySubtractAddSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class AlternatingTernaryOpTest__MultiplySubtractAddSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public Vector256<Single> _fld2; public Vector256<Single> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(AlternatingTernaryOpTest__MultiplySubtractAddSingle testClass) { var result = Fma.MultiplySubtractAdd(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(AlternatingTernaryOpTest__MultiplySubtractAddSingle testClass) { fixed (Vector256<Single>* pFld1 = &_fld1) fixed (Vector256<Single>* pFld2 = &_fld2) fixed (Vector256<Single>* pFld3 = &_fld3) { var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Single*)(pFld2)), Avx.LoadVector256((Single*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Single[] _data3 = new Single[Op3ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private static Vector256<Single> _clsVar3; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private Vector256<Single> _fld3; private DataTable _dataTable; static AlternatingTernaryOpTest__MultiplySubtractAddSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public AlternatingTernaryOpTest__MultiplySubtractAddSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Fma.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Fma.MultiplySubtractAdd( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Fma.MultiplySubtractAdd( Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Fma.MultiplySubtractAdd( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Single>* pClsVar1 = &_clsVar1) fixed (Vector256<Single>* pClsVar2 = &_clsVar2) fixed (Vector256<Single>* pClsVar3 = &_clsVar3) { var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(pClsVar1)), Avx.LoadVector256((Single*)(pClsVar2)), Avx.LoadVector256((Single*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr); var result = Fma.MultiplySubtractAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)); var op3 = Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtractAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)); var op3 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtractAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new AlternatingTernaryOpTest__MultiplySubtractAddSingle(); var result = Fma.MultiplySubtractAdd(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new AlternatingTernaryOpTest__MultiplySubtractAddSingle(); fixed (Vector256<Single>* pFld1 = &test._fld1) fixed (Vector256<Single>* pFld2 = &test._fld2) fixed (Vector256<Single>* pFld3 = &test._fld3) { var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Single*)(pFld2)), Avx.LoadVector256((Single*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Fma.MultiplySubtractAdd(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Single>* pFld1 = &_fld1) fixed (Vector256<Single>* pFld2 = &_fld2) fixed (Vector256<Single>* pFld3 = &_fld3) { var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Single*)(pFld2)), Avx.LoadVector256((Single*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Fma.MultiplySubtractAdd(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(&test._fld1)), Avx.LoadVector256((Single*)(&test._fld2)), Avx.LoadVector256((Single*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, Vector256<Single> op3, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] inArray3 = new Single[Op3ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] inArray3 = new Single[Op3ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i += 2) { if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[i] * secondOp[i]) + thirdOp[i], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i], 3))) { succeeded = false; break; } if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[i + 1] * secondOp[i + 1]) - thirdOp[i + 1], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i + 1], 3))) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractAdd)}<Single>(Vector256<Single>, Vector256<Single>, Vector256<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplySubtractAddSingle() { var test = new AlternatingTernaryOpTest__MultiplySubtractAddSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class AlternatingTernaryOpTest__MultiplySubtractAddSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public Vector256<Single> _fld2; public Vector256<Single> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(AlternatingTernaryOpTest__MultiplySubtractAddSingle testClass) { var result = Fma.MultiplySubtractAdd(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(AlternatingTernaryOpTest__MultiplySubtractAddSingle testClass) { fixed (Vector256<Single>* pFld1 = &_fld1) fixed (Vector256<Single>* pFld2 = &_fld2) fixed (Vector256<Single>* pFld3 = &_fld3) { var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Single*)(pFld2)), Avx.LoadVector256((Single*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Single[] _data3 = new Single[Op3ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private static Vector256<Single> _clsVar3; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private Vector256<Single> _fld3; private DataTable _dataTable; static AlternatingTernaryOpTest__MultiplySubtractAddSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public AlternatingTernaryOpTest__MultiplySubtractAddSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Fma.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Fma.MultiplySubtractAdd( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Fma.MultiplySubtractAdd( Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Fma.MultiplySubtractAdd( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Single>* pClsVar1 = &_clsVar1) fixed (Vector256<Single>* pClsVar2 = &_clsVar2) fixed (Vector256<Single>* pClsVar3 = &_clsVar3) { var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(pClsVar1)), Avx.LoadVector256((Single*)(pClsVar2)), Avx.LoadVector256((Single*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray3Ptr); var result = Fma.MultiplySubtractAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)); var op3 = Avx.LoadVector256((Single*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtractAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)); var op3 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplySubtractAdd(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new AlternatingTernaryOpTest__MultiplySubtractAddSingle(); var result = Fma.MultiplySubtractAdd(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new AlternatingTernaryOpTest__MultiplySubtractAddSingle(); fixed (Vector256<Single>* pFld1 = &test._fld1) fixed (Vector256<Single>* pFld2 = &test._fld2) fixed (Vector256<Single>* pFld3 = &test._fld3) { var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Single*)(pFld2)), Avx.LoadVector256((Single*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Fma.MultiplySubtractAdd(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Single>* pFld1 = &_fld1) fixed (Vector256<Single>* pFld2 = &_fld2) fixed (Vector256<Single>* pFld3 = &_fld3) { var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Single*)(pFld2)), Avx.LoadVector256((Single*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Fma.MultiplySubtractAdd(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Fma.MultiplySubtractAdd( Avx.LoadVector256((Single*)(&test._fld1)), Avx.LoadVector256((Single*)(&test._fld2)), Avx.LoadVector256((Single*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, Vector256<Single> op3, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] inArray3 = new Single[Op3ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] inArray3 = new Single[Op3ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i += 2) { if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[i] * secondOp[i]) + thirdOp[i], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i], 3))) { succeeded = false; break; } if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[i + 1] * secondOp[i + 1]) - thirdOp[i + 1], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i + 1], 3))) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractAdd)}<Single>(Vector256<Single>, Vector256<Single>, Vector256<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/WriterGen.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. class WriterGen : CsWriter { public WriterGen(string fileName) : base(fileName) { } public void EmitSource() { WriteLine("#pragma warning disable 649"); WriteLine(); WriteLine("using System;"); WriteLine("using System.IO;"); WriteLine("using System.Collections.Generic;"); WriteLine("using System.Reflection;"); WriteLine("using System.Threading;"); WriteLine("using Internal.LowLevelLinq;"); WriteLine("using Internal.Metadata.NativeFormat.Writer;"); WriteLine("using Internal.NativeFormat;"); WriteLine("using HandleType = Internal.Metadata.NativeFormat.HandleType;"); WriteLine("using Debug = System.Diagnostics.Debug;"); WriteLine(); OpenScope("namespace Internal.Metadata.NativeFormat.Writer"); foreach (var record in SchemaDef.RecordSchema) { EmitRecord(record); } CloseScope("Internal.Metadata.NativeFormat.Writer"); } private void EmitRecord(RecordDef record) { bool isConstantStringValue = record.Name == "ConstantStringValue"; OpenScope($"public partial class {record.Name} : MetadataRecord"); if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) { OpenScope($"public {record.Name}()"); WriteLine("_equalsReentrancyGuard = new ThreadLocal<ReentrancyGuardStack>(() => new ReentrancyGuardStack());"); CloseScope(); } OpenScope("public override HandleType HandleType"); OpenScope("get"); WriteLine($"return HandleType.{record.Name};"); CloseScope(); CloseScope("HandleType"); OpenScope("internal override void Visit(IRecordVisitor visitor)"); foreach (var member in record.Members) { if ((member.Flags & MemberDefFlags.RecordRef) == 0) continue; WriteLine($"{member.Name} = visitor.Visit(this, {member.Name});"); } CloseScope("Visit"); OpenScope("public override sealed bool Equals(Object obj)"); WriteLine("if (Object.ReferenceEquals(this, obj)) return true;"); WriteLine($"var other = obj as {record.Name};"); WriteLine("if (other == null) return false;"); if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) { WriteLine("if (_equalsReentrancyGuard.Value.Contains(other))"); WriteLine(" return true;"); WriteLine("_equalsReentrancyGuard.Value.Push(other);"); WriteLine("try"); WriteLine("{"); } foreach (var member in record.Members) { if ((member.Flags & MemberDefFlags.NotPersisted) != 0) continue; if ((record.Flags & RecordDefFlags.CustomCompare) != 0 && (member.Flags & MemberDefFlags.Compare) == 0) continue; if ((member.Flags & MemberDefFlags.Sequence) != 0) { if ((member.Flags & MemberDefFlags.CustomCompare) != 0) WriteLine($"if (!{member.Name}.SequenceEqual(other.{member.Name}, {member.TypeName}Comparer.Instance)) return false;"); else WriteLine($"if (!{member.Name}.SequenceEqual(other.{member.Name})) return false;"); } else if ((member.Flags & (MemberDefFlags.Map | MemberDefFlags.RecordRef)) != 0) { WriteLine($"if (!Object.Equals({member.Name}, other.{member.Name})) return false;"); } else if ((member.Flags & MemberDefFlags.CustomCompare) != 0) { WriteLine($"if (!CustomComparer.Equals({member.Name}, other.{member.Name})) return false;"); } else { WriteLine($"if ({member.Name} != other.{member.Name}) return false;"); } } if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) { WriteLine("}"); WriteLine("finally"); WriteLine("{"); WriteLine(" var popped = _equalsReentrancyGuard.Value.Pop();"); WriteLine(" Debug.Assert(Object.ReferenceEquals(other, popped));"); WriteLine("}"); } WriteLine("return true;"); CloseScope("Equals"); if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) WriteLine("private ThreadLocal<ReentrancyGuardStack> _equalsReentrancyGuard;"); OpenScope("public override sealed int GetHashCode()"); WriteLine("if (_hash != 0)"); WriteLine(" return _hash;"); WriteLine("EnterGetHashCode();"); // Compute hash seed using stable hashcode byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(record.Name); byte[] hashBytes = System.Security.Cryptography.SHA256.Create().ComputeHash(nameBytes); int hashSeed = System.BitConverter.ToInt32(hashBytes, 0); WriteLine($"int hash = {hashSeed};"); foreach (var member in record.Members) { if ((member.Flags & MemberDefFlags.NotPersisted) != 0) continue; if ((record.Flags & RecordDefFlags.CustomCompare) != 0 && (member.Flags & MemberDefFlags.Compare) == 0) continue; if (member.TypeName as string == "ConstantStringValue") { WriteLine($"hash = ((hash << 13) - (hash >> 19)) ^ ({member.Name} == null ? 0 : {member.Name}.GetHashCode());"); } else if ((member.Flags & MemberDefFlags.Array) != 0) { WriteLine($"if ({member.Name} != null)"); WriteLine("{"); WriteLine($" for (int i = 0; i < {member.Name}.Length; i++)"); WriteLine(" {"); WriteLine($" hash = ((hash << 13) - (hash >> 19)) ^ {member.Name}[i].GetHashCode();"); WriteLine(" }"); WriteLine("}"); } else if ((member.Flags & (MemberDefFlags.List | MemberDefFlags.Map)) != 0) { if ((member.Flags & MemberDefFlags.EnumerateForHashCode) == 0) continue; WriteLine($"if ({member.Name} != null)"); WriteLine("{"); WriteLine($"for (int i = 0; i < {member.Name}.Count; i++)"); WriteLine(" {"); WriteLine($" hash = ((hash << 13) - (hash >> 19)) ^ ({member.Name}[i] == null ? 0 : {member.Name}[i].GetHashCode());"); WriteLine(" }"); WriteLine("}"); } else if ((member.Flags & MemberDefFlags.RecordRef) != 0 || isConstantStringValue) { WriteLine($"hash = ((hash << 13) - (hash >> 19)) ^ ({member.Name} == null ? 0 : {member.Name}.GetHashCode());"); } else { WriteLine($"hash = ((hash << 13) - (hash >> 19)) ^ {member.Name}.GetHashCode();"); } } WriteLine("LeaveGetHashCode();"); WriteLine("_hash = hash;"); WriteLine("return _hash;"); CloseScope("GetHashCode"); OpenScope("internal override void Save(NativeWriter writer)"); if (isConstantStringValue) { WriteLine("if (Value == null)"); WriteLine(" return;"); WriteLine(); } foreach (var member in record.Members) { if ((member.Flags & MemberDefFlags.NotPersisted) != 0) continue; var typeSet = member.TypeName as string[]; if (typeSet != null) { if ((member.Flags & (MemberDefFlags.List | MemberDefFlags.Map)) != 0) { WriteLine($"Debug.Assert({member.Name}.TrueForAll(handle => handle == null ||"); for (int i = 0; i < typeSet.Length; i++) WriteLine($" handle.HandleType == HandleType.{typeSet[i]}" + ((i == typeSet.Length - 1) ? "));" : " ||")); } else { WriteLine($"Debug.Assert({member.Name} == null ||"); for (int i = 0; i < typeSet.Length; i++) WriteLine($" {member.Name}.HandleType == HandleType.{typeSet[i]}" + ((i == typeSet.Length - 1) ? ");" : " ||")); } } WriteLine($"writer.Write({member.Name});"); } CloseScope("Save"); OpenScope($"internal static {record.Name}Handle AsHandle({record.Name} record)"); WriteLine("if (record == null)"); WriteLine("{"); WriteLine($" return new {record.Name}Handle(0);"); WriteLine("}"); WriteLine("else"); WriteLine("{"); WriteLine(" return record.Handle;"); WriteLine("}"); CloseScope("AsHandle"); OpenScope($"internal new {record.Name}Handle Handle"); OpenScope("get"); if (isConstantStringValue) { WriteLine("if (Value == null)"); WriteLine(" return new ConstantStringValueHandle(0);"); WriteLine("else"); WriteLine(" return new ConstantStringValueHandle(HandleOffset);"); } else { WriteLine($"return new {record.Name}Handle(HandleOffset);"); } CloseScope(); CloseScope("Handle"); WriteLineIfNeeded(); foreach (var member in record.Members) { if ((member.Flags & MemberDefFlags.NotPersisted) != 0) continue; string fieldType = member.GetMemberType(MemberTypeKind.WriterField); if ((member.Flags & (MemberDefFlags.List | MemberDefFlags.Map)) != 0) { WriteLine($"public {fieldType} {member.Name} = new {fieldType}();"); } else { WriteLine($"public {fieldType} {member.Name};"); } } CloseScope(record.Name); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. class WriterGen : CsWriter { public WriterGen(string fileName) : base(fileName) { } public void EmitSource() { WriteLine("#pragma warning disable 649"); WriteLine(); WriteLine("using System;"); WriteLine("using System.IO;"); WriteLine("using System.Collections.Generic;"); WriteLine("using System.Reflection;"); WriteLine("using System.Threading;"); WriteLine("using Internal.LowLevelLinq;"); WriteLine("using Internal.Metadata.NativeFormat.Writer;"); WriteLine("using Internal.NativeFormat;"); WriteLine("using HandleType = Internal.Metadata.NativeFormat.HandleType;"); WriteLine("using Debug = System.Diagnostics.Debug;"); WriteLine(); OpenScope("namespace Internal.Metadata.NativeFormat.Writer"); foreach (var record in SchemaDef.RecordSchema) { EmitRecord(record); } CloseScope("Internal.Metadata.NativeFormat.Writer"); } private void EmitRecord(RecordDef record) { bool isConstantStringValue = record.Name == "ConstantStringValue"; OpenScope($"public partial class {record.Name} : MetadataRecord"); if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) { OpenScope($"public {record.Name}()"); WriteLine("_equalsReentrancyGuard = new ThreadLocal<ReentrancyGuardStack>(() => new ReentrancyGuardStack());"); CloseScope(); } OpenScope("public override HandleType HandleType"); OpenScope("get"); WriteLine($"return HandleType.{record.Name};"); CloseScope(); CloseScope("HandleType"); OpenScope("internal override void Visit(IRecordVisitor visitor)"); foreach (var member in record.Members) { if ((member.Flags & MemberDefFlags.RecordRef) == 0) continue; WriteLine($"{member.Name} = visitor.Visit(this, {member.Name});"); } CloseScope("Visit"); OpenScope("public override sealed bool Equals(Object obj)"); WriteLine("if (Object.ReferenceEquals(this, obj)) return true;"); WriteLine($"var other = obj as {record.Name};"); WriteLine("if (other == null) return false;"); if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) { WriteLine("if (_equalsReentrancyGuard.Value.Contains(other))"); WriteLine(" return true;"); WriteLine("_equalsReentrancyGuard.Value.Push(other);"); WriteLine("try"); WriteLine("{"); } foreach (var member in record.Members) { if ((member.Flags & MemberDefFlags.NotPersisted) != 0) continue; if ((record.Flags & RecordDefFlags.CustomCompare) != 0 && (member.Flags & MemberDefFlags.Compare) == 0) continue; if ((member.Flags & MemberDefFlags.Sequence) != 0) { if ((member.Flags & MemberDefFlags.CustomCompare) != 0) WriteLine($"if (!{member.Name}.SequenceEqual(other.{member.Name}, {member.TypeName}Comparer.Instance)) return false;"); else WriteLine($"if (!{member.Name}.SequenceEqual(other.{member.Name})) return false;"); } else if ((member.Flags & (MemberDefFlags.Map | MemberDefFlags.RecordRef)) != 0) { WriteLine($"if (!Object.Equals({member.Name}, other.{member.Name})) return false;"); } else if ((member.Flags & MemberDefFlags.CustomCompare) != 0) { WriteLine($"if (!CustomComparer.Equals({member.Name}, other.{member.Name})) return false;"); } else { WriteLine($"if ({member.Name} != other.{member.Name}) return false;"); } } if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) { WriteLine("}"); WriteLine("finally"); WriteLine("{"); WriteLine(" var popped = _equalsReentrancyGuard.Value.Pop();"); WriteLine(" Debug.Assert(Object.ReferenceEquals(other, popped));"); WriteLine("}"); } WriteLine("return true;"); CloseScope("Equals"); if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) WriteLine("private ThreadLocal<ReentrancyGuardStack> _equalsReentrancyGuard;"); OpenScope("public override sealed int GetHashCode()"); WriteLine("if (_hash != 0)"); WriteLine(" return _hash;"); WriteLine("EnterGetHashCode();"); // Compute hash seed using stable hashcode byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(record.Name); byte[] hashBytes = System.Security.Cryptography.SHA256.Create().ComputeHash(nameBytes); int hashSeed = System.BitConverter.ToInt32(hashBytes, 0); WriteLine($"int hash = {hashSeed};"); foreach (var member in record.Members) { if ((member.Flags & MemberDefFlags.NotPersisted) != 0) continue; if ((record.Flags & RecordDefFlags.CustomCompare) != 0 && (member.Flags & MemberDefFlags.Compare) == 0) continue; if (member.TypeName as string == "ConstantStringValue") { WriteLine($"hash = ((hash << 13) - (hash >> 19)) ^ ({member.Name} == null ? 0 : {member.Name}.GetHashCode());"); } else if ((member.Flags & MemberDefFlags.Array) != 0) { WriteLine($"if ({member.Name} != null)"); WriteLine("{"); WriteLine($" for (int i = 0; i < {member.Name}.Length; i++)"); WriteLine(" {"); WriteLine($" hash = ((hash << 13) - (hash >> 19)) ^ {member.Name}[i].GetHashCode();"); WriteLine(" }"); WriteLine("}"); } else if ((member.Flags & (MemberDefFlags.List | MemberDefFlags.Map)) != 0) { if ((member.Flags & MemberDefFlags.EnumerateForHashCode) == 0) continue; WriteLine($"if ({member.Name} != null)"); WriteLine("{"); WriteLine($"for (int i = 0; i < {member.Name}.Count; i++)"); WriteLine(" {"); WriteLine($" hash = ((hash << 13) - (hash >> 19)) ^ ({member.Name}[i] == null ? 0 : {member.Name}[i].GetHashCode());"); WriteLine(" }"); WriteLine("}"); } else if ((member.Flags & MemberDefFlags.RecordRef) != 0 || isConstantStringValue) { WriteLine($"hash = ((hash << 13) - (hash >> 19)) ^ ({member.Name} == null ? 0 : {member.Name}.GetHashCode());"); } else { WriteLine($"hash = ((hash << 13) - (hash >> 19)) ^ {member.Name}.GetHashCode();"); } } WriteLine("LeaveGetHashCode();"); WriteLine("_hash = hash;"); WriteLine("return _hash;"); CloseScope("GetHashCode"); OpenScope("internal override void Save(NativeWriter writer)"); if (isConstantStringValue) { WriteLine("if (Value == null)"); WriteLine(" return;"); WriteLine(); } foreach (var member in record.Members) { if ((member.Flags & MemberDefFlags.NotPersisted) != 0) continue; var typeSet = member.TypeName as string[]; if (typeSet != null) { if ((member.Flags & (MemberDefFlags.List | MemberDefFlags.Map)) != 0) { WriteLine($"Debug.Assert({member.Name}.TrueForAll(handle => handle == null ||"); for (int i = 0; i < typeSet.Length; i++) WriteLine($" handle.HandleType == HandleType.{typeSet[i]}" + ((i == typeSet.Length - 1) ? "));" : " ||")); } else { WriteLine($"Debug.Assert({member.Name} == null ||"); for (int i = 0; i < typeSet.Length; i++) WriteLine($" {member.Name}.HandleType == HandleType.{typeSet[i]}" + ((i == typeSet.Length - 1) ? ");" : " ||")); } } WriteLine($"writer.Write({member.Name});"); } CloseScope("Save"); OpenScope($"internal static {record.Name}Handle AsHandle({record.Name} record)"); WriteLine("if (record == null)"); WriteLine("{"); WriteLine($" return new {record.Name}Handle(0);"); WriteLine("}"); WriteLine("else"); WriteLine("{"); WriteLine(" return record.Handle;"); WriteLine("}"); CloseScope("AsHandle"); OpenScope($"internal new {record.Name}Handle Handle"); OpenScope("get"); if (isConstantStringValue) { WriteLine("if (Value == null)"); WriteLine(" return new ConstantStringValueHandle(0);"); WriteLine("else"); WriteLine(" return new ConstantStringValueHandle(HandleOffset);"); } else { WriteLine($"return new {record.Name}Handle(HandleOffset);"); } CloseScope(); CloseScope("Handle"); WriteLineIfNeeded(); foreach (var member in record.Members) { if ((member.Flags & MemberDefFlags.NotPersisted) != 0) continue; string fieldType = member.GetMemberType(MemberTypeKind.WriterField); if ((member.Flags & (MemberDefFlags.List | MemberDefFlags.Map)) != 0) { WriteLine($"public {fieldType} {member.Name} = new {fieldType}();"); } else { WriteLine($"public {fieldType} {member.Name};"); } } CloseScope(record.Name); } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.AddRange.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of the List class. /// </summary> public abstract partial class List_Generic_Tests<T> : IList_Generic_Tests<T> { // Has tests that pass a variably sized TestCollection and MyEnumerable to the AddRange function [Theory] [MemberData(nameof(EnumerableTestData))] public void AddRange(EnumerableType enumerableType, int listLength, int enumerableLength, int numberOfMatchingElements, int numberOfDuplicateElements) { List<T> list = GenericListFactory(listLength); List<T> listBeforeAdd = list.ToList(); IEnumerable<T> enumerable = CreateEnumerable(enumerableType, list, enumerableLength, numberOfMatchingElements, numberOfDuplicateElements); list.AddRange(enumerable); // Check that the first section of the List is unchanged Assert.All(Enumerable.Range(0, listLength), index => { Assert.Equal(listBeforeAdd[index], list[index]); }); // Check that the added elements are correct Assert.All(Enumerable.Range(0, enumerableLength), index => { Assert.Equal(enumerable.ElementAt(index), list[index + listLength]); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void AddRange_NullEnumerable_ThrowsArgumentNullException(int count) { List<T> list = GenericListFactory(count); List<T> listBeforeAdd = list.ToList(); Assert.Throws<ArgumentNullException>(() => list.AddRange(null)); Assert.Equal(listBeforeAdd, list); } [Fact] public void AddRange_AddSelfAsEnumerable_ThrowsExceptionWhenNotEmpty() { List<T> list = GenericListFactory(0); // Succeeds when list is empty. list.AddRange(list); list.AddRange(list.Where(_ => true)); // Succeeds when list has elements and is added as collection. list.Add(default); Assert.Equal(1, list.Count); list.AddRange(list); Assert.Equal(2, list.Count); list.AddRange(list); Assert.Equal(4, list.Count); // Fails version check when list has elements and is added as non-collection. Assert.Throws<InvalidOperationException>(() => list.AddRange(list.Where(_ => true))); Assert.Equal(5, list.Count); Assert.Throws<InvalidOperationException>(() => list.AddRange(list.Where(_ => true))); Assert.Equal(6, list.Count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of the List class. /// </summary> public abstract partial class List_Generic_Tests<T> : IList_Generic_Tests<T> { // Has tests that pass a variably sized TestCollection and MyEnumerable to the AddRange function [Theory] [MemberData(nameof(EnumerableTestData))] public void AddRange(EnumerableType enumerableType, int listLength, int enumerableLength, int numberOfMatchingElements, int numberOfDuplicateElements) { List<T> list = GenericListFactory(listLength); List<T> listBeforeAdd = list.ToList(); IEnumerable<T> enumerable = CreateEnumerable(enumerableType, list, enumerableLength, numberOfMatchingElements, numberOfDuplicateElements); list.AddRange(enumerable); // Check that the first section of the List is unchanged Assert.All(Enumerable.Range(0, listLength), index => { Assert.Equal(listBeforeAdd[index], list[index]); }); // Check that the added elements are correct Assert.All(Enumerable.Range(0, enumerableLength), index => { Assert.Equal(enumerable.ElementAt(index), list[index + listLength]); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void AddRange_NullEnumerable_ThrowsArgumentNullException(int count) { List<T> list = GenericListFactory(count); List<T> listBeforeAdd = list.ToList(); Assert.Throws<ArgumentNullException>(() => list.AddRange(null)); Assert.Equal(listBeforeAdd, list); } [Fact] public void AddRange_AddSelfAsEnumerable_ThrowsExceptionWhenNotEmpty() { List<T> list = GenericListFactory(0); // Succeeds when list is empty. list.AddRange(list); list.AddRange(list.Where(_ => true)); // Succeeds when list has elements and is added as collection. list.Add(default); Assert.Equal(1, list.Count); list.AddRange(list); Assert.Equal(2, list.Count); list.AddRange(list); Assert.Equal(4, list.Count); // Fails version check when list has elements and is added as non-collection. Assert.Throws<InvalidOperationException>(() => list.AddRange(list.Where(_ => true))); Assert.Equal(5, list.Count); Assert.Throws<InvalidOperationException>(() => list.AddRange(list.Where(_ => true))); Assert.Equal(6, list.Count); } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.ComponentModel.EventBasedAsync/tests/AsyncOperationFinalizerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Threading; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.ComponentModel.Tests { public class AsyncOperationFinalizerTests { [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void Finalizer_OperationCompleted_DoesNotCallOperationCompleted() { RemoteExecutor.Invoke(() => { Completed(); GC.Collect(); GC.WaitForPendingFinalizers(); }).Dispose(); } private void Completed() { // This is in a helper method to ensure the JIT doesn't artifically extend the lifetime of the operation. var tracker = new OperationCompletedTracker(); AsyncOperationManager.SynchronizationContext = tracker; AsyncOperation operation = AsyncOperationManager.CreateOperation(new object()); Assert.False(tracker.OperationDidComplete); operation.OperationCompleted(); Assert.True(tracker.OperationDidComplete); } private static bool IsPreciseGcSupportedAndRemoteExecutorSupported => PlatformDetection.IsPreciseGcSupported && RemoteExecutor.IsSupported; [ConditionalFact(nameof(IsPreciseGcSupportedAndRemoteExecutorSupported))] public void Finalizer_OperationNotCompleted_CompletesOperation() { RemoteExecutor.Invoke(() => { var tracker = new OperationCompletedTracker(); NotCompleted(tracker); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(tracker.OperationDidComplete); }).Dispose(); } private void NotCompleted(OperationCompletedTracker tracker) { // This is in a helper method to ensure the JIT doesn't artifically extend the lifetime of the operation. AsyncOperationManager.SynchronizationContext = tracker; AsyncOperation operation = AsyncOperationManager.CreateOperation(new object()); Assert.False(tracker.OperationDidComplete); } public class OperationCompletedTracker : SynchronizationContext { public bool OperationDidComplete { get; set; } public override void OperationCompleted() { Assert.False(OperationDidComplete); OperationDidComplete = true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Threading; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.ComponentModel.Tests { public class AsyncOperationFinalizerTests { [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void Finalizer_OperationCompleted_DoesNotCallOperationCompleted() { RemoteExecutor.Invoke(() => { Completed(); GC.Collect(); GC.WaitForPendingFinalizers(); }).Dispose(); } private void Completed() { // This is in a helper method to ensure the JIT doesn't artifically extend the lifetime of the operation. var tracker = new OperationCompletedTracker(); AsyncOperationManager.SynchronizationContext = tracker; AsyncOperation operation = AsyncOperationManager.CreateOperation(new object()); Assert.False(tracker.OperationDidComplete); operation.OperationCompleted(); Assert.True(tracker.OperationDidComplete); } private static bool IsPreciseGcSupportedAndRemoteExecutorSupported => PlatformDetection.IsPreciseGcSupported && RemoteExecutor.IsSupported; [ConditionalFact(nameof(IsPreciseGcSupportedAndRemoteExecutorSupported))] public void Finalizer_OperationNotCompleted_CompletesOperation() { RemoteExecutor.Invoke(() => { var tracker = new OperationCompletedTracker(); NotCompleted(tracker); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(tracker.OperationDidComplete); }).Dispose(); } private void NotCompleted(OperationCompletedTracker tracker) { // This is in a helper method to ensure the JIT doesn't artifically extend the lifetime of the operation. AsyncOperationManager.SynchronizationContext = tracker; AsyncOperation operation = AsyncOperationManager.CreateOperation(new object()); Assert.False(tracker.OperationDidComplete); } public class OperationCompletedTracker : SynchronizationContext { public bool OperationDidComplete { get; set; } public override void OperationCompleted() { Assert.False(OperationDidComplete); OperationDidComplete = true; } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/AdvSimd_Part10_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Not.Vector128.Int64.cs" /> <Compile Include="Not.Vector128.SByte.cs" /> <Compile Include="Not.Vector128.Single.cs" /> <Compile Include="Not.Vector128.UInt16.cs" /> <Compile Include="Not.Vector128.UInt32.cs" /> <Compile Include="Not.Vector128.UInt64.cs" /> <Compile Include="Or.Vector64.Byte.cs" /> <Compile Include="Or.Vector64.Double.cs" /> <Compile Include="Or.Vector64.Int16.cs" /> <Compile Include="Or.Vector64.Int32.cs" /> <Compile Include="Or.Vector64.Int64.cs" /> <Compile Include="Or.Vector64.SByte.cs" /> <Compile Include="Or.Vector64.Single.cs" /> <Compile Include="Or.Vector64.UInt16.cs" /> <Compile Include="Or.Vector64.UInt32.cs" /> <Compile Include="Or.Vector64.UInt64.cs" /> <Compile Include="Or.Vector128.Byte.cs" /> <Compile Include="Or.Vector128.Double.cs" /> <Compile Include="Or.Vector128.Int16.cs" /> <Compile Include="Or.Vector128.Int32.cs" /> <Compile Include="Or.Vector128.Int64.cs" /> <Compile Include="Or.Vector128.SByte.cs" /> <Compile Include="Or.Vector128.Single.cs" /> <Compile Include="Or.Vector128.UInt16.cs" /> <Compile Include="Or.Vector128.UInt32.cs" /> <Compile Include="Or.Vector128.UInt64.cs" /> <Compile Include="OrNot.Vector64.Byte.cs" /> <Compile Include="OrNot.Vector64.Double.cs" /> <Compile Include="OrNot.Vector64.Int16.cs" /> <Compile Include="OrNot.Vector64.Int32.cs" /> <Compile Include="OrNot.Vector64.Int64.cs" /> <Compile Include="OrNot.Vector64.SByte.cs" /> <Compile Include="OrNot.Vector64.Single.cs" /> <Compile Include="OrNot.Vector64.UInt16.cs" /> <Compile Include="OrNot.Vector64.UInt32.cs" /> <Compile Include="OrNot.Vector64.UInt64.cs" /> <Compile Include="OrNot.Vector128.Byte.cs" /> <Compile Include="OrNot.Vector128.Double.cs" /> <Compile Include="OrNot.Vector128.Int16.cs" /> <Compile Include="OrNot.Vector128.Int32.cs" /> <Compile Include="OrNot.Vector128.Int64.cs" /> <Compile Include="OrNot.Vector128.SByte.cs" /> <Compile Include="OrNot.Vector128.Single.cs" /> <Compile Include="OrNot.Vector128.UInt16.cs" /> <Compile Include="OrNot.Vector128.UInt32.cs" /> <Compile Include="OrNot.Vector128.UInt64.cs" /> <Compile Include="PolynomialMultiply.Vector64.Byte.cs" /> <Compile Include="PolynomialMultiply.Vector64.SByte.cs" /> <Compile Include="PolynomialMultiply.Vector128.Byte.cs" /> <Compile Include="PolynomialMultiply.Vector128.SByte.cs" /> <Compile Include="PolynomialMultiplyWideningLower.Vector64.Byte.cs" /> <Compile Include="PolynomialMultiplyWideningLower.Vector64.SByte.cs" /> <Compile Include="PolynomialMultiplyWideningUpper.Vector128.Byte.cs" /> <Compile Include="PolynomialMultiplyWideningUpper.Vector128.SByte.cs" /> <Compile Include="PopCount.Vector64.Byte.cs" /> <Compile Include="PopCount.Vector64.SByte.cs" /> <Compile Include="PopCount.Vector128.Byte.cs" /> <Compile Include="PopCount.Vector128.SByte.cs" /> <Compile Include="ReciprocalEstimate.Vector64.Single.cs" /> <Compile Include="ReciprocalEstimate.Vector64.UInt32.cs" /> <Compile Include="ReciprocalEstimate.Vector128.Single.cs" /> <Compile Include="ReciprocalEstimate.Vector128.UInt32.cs" /> <Compile Include="ReciprocalSquareRootEstimate.Vector64.Single.cs" /> <Compile Include="ReciprocalSquareRootEstimate.Vector64.UInt32.cs" /> <Compile Include="ReciprocalSquareRootEstimate.Vector128.Single.cs" /> <Compile Include="ReciprocalSquareRootEstimate.Vector128.UInt32.cs" /> <Compile Include="ReciprocalSquareRootStep.Vector64.Single.cs" /> <Compile Include="ReciprocalSquareRootStep.Vector128.Single.cs" /> <Compile Include="ReciprocalStep.Vector64.Single.cs" /> <Compile Include="ReciprocalStep.Vector128.Single.cs" /> <Compile Include="ReverseElement16.Vector64.Int32.cs" /> <Compile Include="ReverseElement16.Vector64.Int64.cs" /> <Compile Include="ReverseElement16.Vector64.UInt32.cs" /> <Compile Include="ReverseElement16.Vector64.UInt64.cs" /> <Compile Include="ReverseElement16.Vector128.Int32.cs" /> <Compile Include="ReverseElement16.Vector128.Int64.cs" /> <Compile Include="ReverseElement16.Vector128.UInt32.cs" /> <Compile Include="ReverseElement16.Vector128.UInt64.cs" /> <Compile Include="ReverseElement32.Vector64.Int64.cs" /> <Compile Include="ReverseElement32.Vector64.UInt64.cs" /> <Compile Include="ReverseElement32.Vector128.Int64.cs" /> <Compile Include="ReverseElement32.Vector128.UInt64.cs" /> <Compile Include="ReverseElement8.Vector64.Int16.cs" /> <Compile Include="ReverseElement8.Vector64.Int32.cs" /> <Compile Include="ReverseElement8.Vector64.Int64.cs" /> <Compile Include="ReverseElement8.Vector64.UInt16.cs" /> <Compile Include="ReverseElement8.Vector64.UInt32.cs" /> <Compile Include="ReverseElement8.Vector64.UInt64.cs" /> <Compile Include="ReverseElement8.Vector128.Int16.cs" /> <Compile Include="ReverseElement8.Vector128.Int32.cs" /> <Compile Include="ReverseElement8.Vector128.Int64.cs" /> <Compile Include="ReverseElement8.Vector128.UInt16.cs" /> <Compile Include="ReverseElement8.Vector128.UInt32.cs" /> <Compile Include="ReverseElement8.Vector128.UInt64.cs" /> <Compile Include="RoundAwayFromZero.Vector64.Single.cs" /> <Compile Include="RoundAwayFromZero.Vector128.Single.cs" /> <Compile Include="RoundAwayFromZeroScalar.Vector64.Double.cs" /> <Compile Include="RoundAwayFromZeroScalar.Vector64.Single.cs" /> <Compile Include="RoundToNearest.Vector64.Single.cs" /> <Compile Include="RoundToNearest.Vector128.Single.cs" /> <Compile Include="Program.AdvSimd_Part10.cs" /> <Compile Include="..\Shared\Helpers.cs" /> <Compile Include="..\Shared\Program.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Not.Vector128.Int64.cs" /> <Compile Include="Not.Vector128.SByte.cs" /> <Compile Include="Not.Vector128.Single.cs" /> <Compile Include="Not.Vector128.UInt16.cs" /> <Compile Include="Not.Vector128.UInt32.cs" /> <Compile Include="Not.Vector128.UInt64.cs" /> <Compile Include="Or.Vector64.Byte.cs" /> <Compile Include="Or.Vector64.Double.cs" /> <Compile Include="Or.Vector64.Int16.cs" /> <Compile Include="Or.Vector64.Int32.cs" /> <Compile Include="Or.Vector64.Int64.cs" /> <Compile Include="Or.Vector64.SByte.cs" /> <Compile Include="Or.Vector64.Single.cs" /> <Compile Include="Or.Vector64.UInt16.cs" /> <Compile Include="Or.Vector64.UInt32.cs" /> <Compile Include="Or.Vector64.UInt64.cs" /> <Compile Include="Or.Vector128.Byte.cs" /> <Compile Include="Or.Vector128.Double.cs" /> <Compile Include="Or.Vector128.Int16.cs" /> <Compile Include="Or.Vector128.Int32.cs" /> <Compile Include="Or.Vector128.Int64.cs" /> <Compile Include="Or.Vector128.SByte.cs" /> <Compile Include="Or.Vector128.Single.cs" /> <Compile Include="Or.Vector128.UInt16.cs" /> <Compile Include="Or.Vector128.UInt32.cs" /> <Compile Include="Or.Vector128.UInt64.cs" /> <Compile Include="OrNot.Vector64.Byte.cs" /> <Compile Include="OrNot.Vector64.Double.cs" /> <Compile Include="OrNot.Vector64.Int16.cs" /> <Compile Include="OrNot.Vector64.Int32.cs" /> <Compile Include="OrNot.Vector64.Int64.cs" /> <Compile Include="OrNot.Vector64.SByte.cs" /> <Compile Include="OrNot.Vector64.Single.cs" /> <Compile Include="OrNot.Vector64.UInt16.cs" /> <Compile Include="OrNot.Vector64.UInt32.cs" /> <Compile Include="OrNot.Vector64.UInt64.cs" /> <Compile Include="OrNot.Vector128.Byte.cs" /> <Compile Include="OrNot.Vector128.Double.cs" /> <Compile Include="OrNot.Vector128.Int16.cs" /> <Compile Include="OrNot.Vector128.Int32.cs" /> <Compile Include="OrNot.Vector128.Int64.cs" /> <Compile Include="OrNot.Vector128.SByte.cs" /> <Compile Include="OrNot.Vector128.Single.cs" /> <Compile Include="OrNot.Vector128.UInt16.cs" /> <Compile Include="OrNot.Vector128.UInt32.cs" /> <Compile Include="OrNot.Vector128.UInt64.cs" /> <Compile Include="PolynomialMultiply.Vector64.Byte.cs" /> <Compile Include="PolynomialMultiply.Vector64.SByte.cs" /> <Compile Include="PolynomialMultiply.Vector128.Byte.cs" /> <Compile Include="PolynomialMultiply.Vector128.SByte.cs" /> <Compile Include="PolynomialMultiplyWideningLower.Vector64.Byte.cs" /> <Compile Include="PolynomialMultiplyWideningLower.Vector64.SByte.cs" /> <Compile Include="PolynomialMultiplyWideningUpper.Vector128.Byte.cs" /> <Compile Include="PolynomialMultiplyWideningUpper.Vector128.SByte.cs" /> <Compile Include="PopCount.Vector64.Byte.cs" /> <Compile Include="PopCount.Vector64.SByte.cs" /> <Compile Include="PopCount.Vector128.Byte.cs" /> <Compile Include="PopCount.Vector128.SByte.cs" /> <Compile Include="ReciprocalEstimate.Vector64.Single.cs" /> <Compile Include="ReciprocalEstimate.Vector64.UInt32.cs" /> <Compile Include="ReciprocalEstimate.Vector128.Single.cs" /> <Compile Include="ReciprocalEstimate.Vector128.UInt32.cs" /> <Compile Include="ReciprocalSquareRootEstimate.Vector64.Single.cs" /> <Compile Include="ReciprocalSquareRootEstimate.Vector64.UInt32.cs" /> <Compile Include="ReciprocalSquareRootEstimate.Vector128.Single.cs" /> <Compile Include="ReciprocalSquareRootEstimate.Vector128.UInt32.cs" /> <Compile Include="ReciprocalSquareRootStep.Vector64.Single.cs" /> <Compile Include="ReciprocalSquareRootStep.Vector128.Single.cs" /> <Compile Include="ReciprocalStep.Vector64.Single.cs" /> <Compile Include="ReciprocalStep.Vector128.Single.cs" /> <Compile Include="ReverseElement16.Vector64.Int32.cs" /> <Compile Include="ReverseElement16.Vector64.Int64.cs" /> <Compile Include="ReverseElement16.Vector64.UInt32.cs" /> <Compile Include="ReverseElement16.Vector64.UInt64.cs" /> <Compile Include="ReverseElement16.Vector128.Int32.cs" /> <Compile Include="ReverseElement16.Vector128.Int64.cs" /> <Compile Include="ReverseElement16.Vector128.UInt32.cs" /> <Compile Include="ReverseElement16.Vector128.UInt64.cs" /> <Compile Include="ReverseElement32.Vector64.Int64.cs" /> <Compile Include="ReverseElement32.Vector64.UInt64.cs" /> <Compile Include="ReverseElement32.Vector128.Int64.cs" /> <Compile Include="ReverseElement32.Vector128.UInt64.cs" /> <Compile Include="ReverseElement8.Vector64.Int16.cs" /> <Compile Include="ReverseElement8.Vector64.Int32.cs" /> <Compile Include="ReverseElement8.Vector64.Int64.cs" /> <Compile Include="ReverseElement8.Vector64.UInt16.cs" /> <Compile Include="ReverseElement8.Vector64.UInt32.cs" /> <Compile Include="ReverseElement8.Vector64.UInt64.cs" /> <Compile Include="ReverseElement8.Vector128.Int16.cs" /> <Compile Include="ReverseElement8.Vector128.Int32.cs" /> <Compile Include="ReverseElement8.Vector128.Int64.cs" /> <Compile Include="ReverseElement8.Vector128.UInt16.cs" /> <Compile Include="ReverseElement8.Vector128.UInt32.cs" /> <Compile Include="ReverseElement8.Vector128.UInt64.cs" /> <Compile Include="RoundAwayFromZero.Vector64.Single.cs" /> <Compile Include="RoundAwayFromZero.Vector128.Single.cs" /> <Compile Include="RoundAwayFromZeroScalar.Vector64.Double.cs" /> <Compile Include="RoundAwayFromZeroScalar.Vector64.Single.cs" /> <Compile Include="RoundToNearest.Vector64.Single.cs" /> <Compile Include="RoundToNearest.Vector128.Single.cs" /> <Compile Include="Program.AdvSimd_Part10.cs" /> <Compile Include="..\Shared\Helpers.cs" /> <Compile Include="..\Shared\Program.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest1245/Generated1245.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated1245 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public G3_C1717`1<T0> extends class G2_C692`2<class BaseClass0,!T0> implements class IBase2`2<class BaseClass0,class BaseClass1> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G3_C1717::Method7.17613<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod4833() cil managed noinlining { ldstr "G3_C1717::ClassMethod4833.17614()" ret } .method public hidebysig newslot virtual instance string ClassMethod4834<M0>() cil managed noinlining { ldstr "G3_C1717::ClassMethod4834.17615<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G2_C692`2<class BaseClass0,!T0>::.ctor() ret } } .class public abstract G2_C692`2<T0, T1> extends class G1_C13`2<class BaseClass0,class BaseClass1> implements IBase0, class IBase1`1<!T0> { .method public hidebysig newslot virtual instance string Method0() cil managed noinlining { ldstr "G2_C692::Method0.11373()" ret } .method public hidebysig virtual instance string Method1() cil managed noinlining { ldstr "G2_C692::Method1.11374()" ret } .method public hidebysig newslot virtual instance string Method2<M0>() cil managed noinlining { ldstr "G2_C692::Method2.11375<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase0.Method2'<M0>() cil managed noinlining { .override method instance string IBase0::Method2<[1]>() ldstr "G2_C692::Method2.MI.11376<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance string Method3<M0>() cil managed noinlining { ldstr "G2_C692::Method3.11377<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance string Method4() cil managed noinlining { ldstr "G2_C692::Method4.11378()" ret } .method public hidebysig newslot virtual instance string 'IBase1<T0>.Method4'() cil managed noinlining { .override method instance string class IBase1`1<!T0>::Method4() ldstr "G2_C692::Method4.MI.11379()" ret } .method public hidebysig virtual instance string Method5() cil managed noinlining { ldstr "G2_C692::Method5.11380()" ret } .method public hidebysig newslot virtual instance string 'IBase1<T0>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<!T0>::Method5() ldstr "G2_C692::Method5.MI.11381()" ret } .method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining { ldstr "G2_C692::Method6.11382<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase1<T0>.Method6'<M0>() cil managed noinlining { .override method instance string class IBase1`1<!T0>::Method6<[1]>() ldstr "G2_C692::Method6.MI.11383<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod2746() cil managed noinlining { ldstr "G2_C692::ClassMethod2746.11384()" ret } .method public hidebysig newslot virtual instance string ClassMethod2747<M0>() cil managed noinlining { ldstr "G2_C692::ClassMethod2747.11385<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G1_C13<class BaseClass0,class BaseClass1>.ClassMethod1348'<M0>() cil managed noinlining { .override method instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<[1]>() ldstr "G2_C692::ClassMethod1348.MI.11386<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G1_C13`2<class BaseClass0,class BaseClass1>::.ctor() ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public abstract G1_C13`2<T0, T1> implements class IBase2`2<!T0,!T1>, class IBase1`1<!T0> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G1_C13::Method7.4871<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string Method4() cil managed noinlining { ldstr "G1_C13::Method4.4872()" ret } .method public hidebysig newslot virtual instance string Method5() cil managed noinlining { ldstr "G1_C13::Method5.4873()" ret } .method public hidebysig newslot virtual instance string 'IBase1<T0>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<!T0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ret } .method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining { ldstr "G1_C13::Method6.4875<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1348<M0>() cil managed noinlining { ldstr "G1_C13::ClassMethod1348.4876<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1349<M0>() cil managed noinlining { ldstr "G1_C13::ClassMethod1349.4877<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class interface public abstract IBase0 { .method public hidebysig newslot abstract virtual instance string Method0() cil managed { } .method public hidebysig newslot abstract virtual instance string Method1() cil managed { } .method public hidebysig newslot abstract virtual instance string Method2<M0>() cil managed { } .method public hidebysig newslot abstract virtual instance string Method3<M0>() cil managed { } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated1245 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1717.T<T0,(class G3_C1717`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1717.T<T0,(class G3_C1717`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod4833() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod4834<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1717.A<(class G3_C1717`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1717.A<(class G3_C1717`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod4833() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod4834<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1717.B<(class G3_C1717`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1717.B<(class G3_C1717`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod4833() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod4834<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.T.T<T0,T1,(class G2_C692`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.T.T<T0,T1,(class G2_C692`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.A.T<T1,(class G2_C692`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.A.T<T1,(class G2_C692`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.A.A<(class G2_C692`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.A.A<(class G2_C692`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.A.B<(class G2_C692`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.A.B<(class G2_C692`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.B.T<T1,(class G2_C692`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.B.T<T1,(class G2_C692`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.B.A<(class G2_C692`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.B.A<(class G2_C692`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.B.B<(class G2_C692`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.B.B<(class G2_C692`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.T.T<T0,T1,(class G1_C13`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.T.T<T0,T1,(class G1_C13`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.T<T1,(class G1_C13`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.T<T1,(class G1_C13`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.A<(class G1_C13`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.A<(class G1_C13`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.B<(class G1_C13`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.B<(class G1_C13`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.T<T1,(class G1_C13`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.T<T1,(class G1_C13`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.A<(class G1_C13`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.A<(class G1_C13`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.B<(class G1_C13`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.B<(class G1_C13`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase0<(IBase0)W>(!!W inst, string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase0<(IBase0)W>(!!W inst, string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method3<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1717`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C692::Method4.MI.11379()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C692::Method5.MI.11381()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C692::Method6.MI.11383<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2747<object>() ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2746() ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method2<object>() ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method1() ldstr "G2_C692::Method1.11374()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method0() ldstr "G2_C692::Method0.11373()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C692::Method0.11373()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C692::Method1.11374()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C692::Method2.MI.11376<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod4834<object>() ldstr "G3_C1717::ClassMethod4834.17615<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod4833() ldstr "G3_C1717::ClassMethod4833.17614()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod2747<object>() ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod2746() ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method6<object>() ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method2<object>() ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method1() ldstr "G2_C692::Method1.11374()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method0() ldstr "G2_C692::Method0.11373()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G3_C1717`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C692::Method4.MI.11379()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C692::Method5.MI.11381()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C692::Method6.MI.11383<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2747<object>() ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2746() ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method2<object>() ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method1() ldstr "G2_C692::Method1.11374()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method0() ldstr "G2_C692::Method0.11373()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C692::Method0.11373()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C692::Method1.11374()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C692::Method2.MI.11376<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod4834<object>() ldstr "G3_C1717::ClassMethod4834.17615<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod4833() ldstr "G3_C1717::ClassMethod4833.17614()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod2747<object>() ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod2746() ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method6<object>() ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method2<object>() ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method1() ldstr "G2_C692::Method1.11374()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method0() ldstr "G2_C692::Method0.11373()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1717`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.T.T<class BaseClass0,class BaseClass1,class G3_C1717`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.A.T<class BaseClass1,class G3_C1717`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.A.B<class G3_C1717`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1717`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.A.T<class BaseClass1,class G3_C1717`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.A.B<class G3_C1717`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C692::Method4.MI.11379()#G2_C692::Method5.MI.11381()#G2_C692::Method6.MI.11383<System.Object>()#" call void Generated1245::M.IBase1.T<class BaseClass0,class G3_C1717`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C692::Method4.MI.11379()#G2_C692::Method5.MI.11381()#G2_C692::Method6.MI.11383<System.Object>()#" call void Generated1245::M.IBase1.A<class G3_C1717`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.T.T<class BaseClass0,class BaseClass0,class G3_C1717`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.A.T<class BaseClass0,class G3_C1717`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.A.A<class G3_C1717`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.MI.11376<System.Object>()#G2_C692::Method3.11377<System.Object>()#" call void Generated1245::M.IBase0<class G3_C1717`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G3_C1717::ClassMethod4833.17614()#G3_C1717::ClassMethod4834.17615<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G3_C1717.T<class BaseClass0,class G3_C1717`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G3_C1717::ClassMethod4833.17614()#G3_C1717::ClassMethod4834.17615<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G3_C1717.A<class G3_C1717`1<class BaseClass0>>(!!0,string) newobj instance void class G3_C1717`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.T.T<class BaseClass0,class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.A.T<class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.A.B<class G3_C1717`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.A.T<class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.A.B<class G3_C1717`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C692::Method4.MI.11379()#G2_C692::Method5.MI.11381()#G2_C692::Method6.MI.11383<System.Object>()#" call void Generated1245::M.IBase1.T<class BaseClass0,class G3_C1717`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C692::Method4.MI.11379()#G2_C692::Method5.MI.11381()#G2_C692::Method6.MI.11383<System.Object>()#" call void Generated1245::M.IBase1.A<class G3_C1717`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.T.T<class BaseClass0,class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.A.T<class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.A.B<class G3_C1717`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.MI.11376<System.Object>()#G2_C692::Method3.11377<System.Object>()#" call void Generated1245::M.IBase0<class G3_C1717`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G3_C1717::ClassMethod4833.17614()#G3_C1717::ClassMethod4834.17615<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G3_C1717.T<class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G3_C1717::ClassMethod4833.17614()#G3_C1717::ClassMethod4834.17615<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G3_C1717.B<class G3_C1717`1<class BaseClass1>>(!!0,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1717`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method5.11380()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method4.11378()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method4.MI.11379()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method5.MI.11381()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method6.MI.11383<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2747<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2746() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method5.11380()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method4.11378()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method3<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method2<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method1() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method1.11374()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method0() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method0.11373()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method0.11373()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method1.11374()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method2.MI.11376<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod4834<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::ClassMethod4834.17615<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod4833() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::ClassMethod4833.17614()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod2747<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod2746() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method5() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method5.11380()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method4() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method4.11378()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method3<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method2<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method1() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method1.11374()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method0() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method0.11373()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G3_C1717`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method5.11380()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method4.11378()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method4.MI.11379()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method5.MI.11381()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method6.MI.11383<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2747<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2746() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method5.11380()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method4.11378()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method3<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method2<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method1() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method1.11374()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method0() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method0.11373()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method0.11373()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method1.11374()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method2.MI.11376<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod4834<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::ClassMethod4834.17615<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod4833() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::ClassMethod4833.17614()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod2747<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod2746() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method5() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method5.11380()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method4() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method4.11378()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method3<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method2<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method1() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method1.11374()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method0() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method0.11373()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated1245::MethodCallingTest() call void Generated1245::ConstrainedCallsTest() call void Generated1245::StructConstrainedInterfaceCallsTest() call void Generated1245::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated1245 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public G3_C1717`1<T0> extends class G2_C692`2<class BaseClass0,!T0> implements class IBase2`2<class BaseClass0,class BaseClass1> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G3_C1717::Method7.17613<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod4833() cil managed noinlining { ldstr "G3_C1717::ClassMethod4833.17614()" ret } .method public hidebysig newslot virtual instance string ClassMethod4834<M0>() cil managed noinlining { ldstr "G3_C1717::ClassMethod4834.17615<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G2_C692`2<class BaseClass0,!T0>::.ctor() ret } } .class public abstract G2_C692`2<T0, T1> extends class G1_C13`2<class BaseClass0,class BaseClass1> implements IBase0, class IBase1`1<!T0> { .method public hidebysig newslot virtual instance string Method0() cil managed noinlining { ldstr "G2_C692::Method0.11373()" ret } .method public hidebysig virtual instance string Method1() cil managed noinlining { ldstr "G2_C692::Method1.11374()" ret } .method public hidebysig newslot virtual instance string Method2<M0>() cil managed noinlining { ldstr "G2_C692::Method2.11375<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase0.Method2'<M0>() cil managed noinlining { .override method instance string IBase0::Method2<[1]>() ldstr "G2_C692::Method2.MI.11376<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance string Method3<M0>() cil managed noinlining { ldstr "G2_C692::Method3.11377<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance string Method4() cil managed noinlining { ldstr "G2_C692::Method4.11378()" ret } .method public hidebysig newslot virtual instance string 'IBase1<T0>.Method4'() cil managed noinlining { .override method instance string class IBase1`1<!T0>::Method4() ldstr "G2_C692::Method4.MI.11379()" ret } .method public hidebysig virtual instance string Method5() cil managed noinlining { ldstr "G2_C692::Method5.11380()" ret } .method public hidebysig newslot virtual instance string 'IBase1<T0>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<!T0>::Method5() ldstr "G2_C692::Method5.MI.11381()" ret } .method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining { ldstr "G2_C692::Method6.11382<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase1<T0>.Method6'<M0>() cil managed noinlining { .override method instance string class IBase1`1<!T0>::Method6<[1]>() ldstr "G2_C692::Method6.MI.11383<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod2746() cil managed noinlining { ldstr "G2_C692::ClassMethod2746.11384()" ret } .method public hidebysig newslot virtual instance string ClassMethod2747<M0>() cil managed noinlining { ldstr "G2_C692::ClassMethod2747.11385<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G1_C13<class BaseClass0,class BaseClass1>.ClassMethod1348'<M0>() cil managed noinlining { .override method instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<[1]>() ldstr "G2_C692::ClassMethod1348.MI.11386<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G1_C13`2<class BaseClass0,class BaseClass1>::.ctor() ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public abstract G1_C13`2<T0, T1> implements class IBase2`2<!T0,!T1>, class IBase1`1<!T0> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G1_C13::Method7.4871<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string Method4() cil managed noinlining { ldstr "G1_C13::Method4.4872()" ret } .method public hidebysig newslot virtual instance string Method5() cil managed noinlining { ldstr "G1_C13::Method5.4873()" ret } .method public hidebysig newslot virtual instance string 'IBase1<T0>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<!T0>::Method5() ldstr "G1_C13::Method5.MI.4874()" ret } .method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining { ldstr "G1_C13::Method6.4875<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1348<M0>() cil managed noinlining { ldstr "G1_C13::ClassMethod1348.4876<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1349<M0>() cil managed noinlining { ldstr "G1_C13::ClassMethod1349.4877<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class interface public abstract IBase0 { .method public hidebysig newslot abstract virtual instance string Method0() cil managed { } .method public hidebysig newslot abstract virtual instance string Method1() cil managed { } .method public hidebysig newslot abstract virtual instance string Method2<M0>() cil managed { } .method public hidebysig newslot abstract virtual instance string Method3<M0>() cil managed { } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated1245 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1717.T<T0,(class G3_C1717`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1717.T<T0,(class G3_C1717`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod4833() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::ClassMethod4834<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1717.A<(class G3_C1717`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1717.A<(class G3_C1717`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod4833() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod4834<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1717.B<(class G3_C1717`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 19 .locals init (string[] actualResults) ldc.i4.s 14 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1717.B<(class G3_C1717`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 14 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod4833() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod4834<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 12 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 13 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1717`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.T.T<T0,T1,(class G2_C692`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.T.T<T0,T1,(class G2_C692`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.A.T<T1,(class G2_C692`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.A.T<T1,(class G2_C692`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.A.A<(class G2_C692`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.A.A<(class G2_C692`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.A.B<(class G2_C692`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.A.B<(class G2_C692`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.B.T<T1,(class G2_C692`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.B.T<T1,(class G2_C692`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.B.A<(class G2_C692`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.B.A<(class G2_C692`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C692.B.B<(class G2_C692`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 17 .locals init (string[] actualResults) ldc.i4.s 12 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C692.B.B<(class G2_C692`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 12 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::ClassMethod2746() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::ClassMethod2747<object>() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method3<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 11 ldarga.s 0 constrained. !!W callvirt instance string class G2_C692`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.T.T<T0,T1,(class G1_C13`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.T.T<T0,T1,(class G1_C13`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.T<T1,(class G1_C13`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.T<T1,(class G1_C13`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.A<(class G1_C13`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.A<(class G1_C13`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.A.B<(class G1_C13`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.A.B<(class G1_C13`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.T<T1,(class G1_C13`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.T<T1,(class G1_C13`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.A<(class G1_C13`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.A<(class G1_C13`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C13.B.B<(class G1_C13`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 11 .locals init (string[] actualResults) ldc.i4.s 6 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C13.B.B<(class G1_C13`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 6 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1348<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::ClassMethod1349<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G1_C13`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase0<(IBase0)W>(!!W inst, string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase0<(IBase0)W>(!!W inst, string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method0() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method1() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method2<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string IBase0::Method3<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1717`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C692::Method4.MI.11379()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C692::Method5.MI.11381()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C692::Method6.MI.11383<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2747<object>() ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2746() ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method2<object>() ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method1() ldstr "G2_C692::Method1.11374()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method0() ldstr "G2_C692::Method0.11373()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C692::Method0.11373()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C692::Method1.11374()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C692::Method2.MI.11376<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod4834<object>() ldstr "G3_C1717::ClassMethod4834.17615<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod4833() ldstr "G3_C1717::ClassMethod4833.17614()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod2747<object>() ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod2746() ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method6<object>() ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method2<object>() ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method1() ldstr "G2_C692::Method1.11374()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::Method0() ldstr "G2_C692::Method0.11373()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass0> callvirt instance string class G3_C1717`1<class BaseClass0>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G3_C1717`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C13`2<class BaseClass0,class BaseClass1> callvirt instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C692::Method4.MI.11379()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C692::Method5.MI.11381()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C692::Method6.MI.11383<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2747<object>() ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2746() ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method2<object>() ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method1() ldstr "G2_C692::Method1.11374()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method0() ldstr "G2_C692::Method0.11373()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C692`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string IBase0::Method0() ldstr "G2_C692::Method0.11373()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method1() ldstr "G2_C692::Method1.11374()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method2<object>() ldstr "G2_C692::Method2.MI.11376<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string IBase0::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod4834<object>() ldstr "G3_C1717::ClassMethod4834.17615<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod4833() ldstr "G3_C1717::ClassMethod4833.17614()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method7<object>() ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod2747<object>() ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod2746() ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method6<object>() ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method5() ldstr "G2_C692::Method5.11380()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method4() ldstr "G2_C692::Method4.11378()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method3<object>() ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method2<object>() ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method1() ldstr "G2_C692::Method1.11374()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::Method0() ldstr "G2_C692::Method0.11373()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod1349<object>() ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1717`1<class BaseClass1> callvirt instance string class G3_C1717`1<class BaseClass1>::ClassMethod1348<object>() ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1717`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.T.T<class BaseClass0,class BaseClass1,class G3_C1717`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.A.T<class BaseClass1,class G3_C1717`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.A.B<class G3_C1717`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1717`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.A.T<class BaseClass1,class G3_C1717`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.A.B<class G3_C1717`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C692::Method4.MI.11379()#G2_C692::Method5.MI.11381()#G2_C692::Method6.MI.11383<System.Object>()#" call void Generated1245::M.IBase1.T<class BaseClass0,class G3_C1717`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C692::Method4.MI.11379()#G2_C692::Method5.MI.11381()#G2_C692::Method6.MI.11383<System.Object>()#" call void Generated1245::M.IBase1.A<class G3_C1717`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.T.T<class BaseClass0,class BaseClass0,class G3_C1717`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.A.T<class BaseClass0,class G3_C1717`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.A.A<class G3_C1717`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.MI.11376<System.Object>()#G2_C692::Method3.11377<System.Object>()#" call void Generated1245::M.IBase0<class G3_C1717`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G3_C1717::ClassMethod4833.17614()#G3_C1717::ClassMethod4834.17615<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G3_C1717.T<class BaseClass0,class G3_C1717`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G3_C1717::ClassMethod4833.17614()#G3_C1717::ClassMethod4834.17615<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G3_C1717.A<class G3_C1717`1<class BaseClass0>>(!!0,string) newobj instance void class G3_C1717`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.T.T<class BaseClass0,class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.A.T<class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G1_C13::Method6.4875<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G1_C13.A.B<class G3_C1717`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.A.T<class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.IBase2.A.B<class G3_C1717`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C692::Method4.MI.11379()#G2_C692::Method5.MI.11381()#G2_C692::Method6.MI.11383<System.Object>()#" call void Generated1245::M.IBase1.T<class BaseClass0,class G3_C1717`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C692::Method4.MI.11379()#G2_C692::Method5.MI.11381()#G2_C692::Method6.MI.11383<System.Object>()#" call void Generated1245::M.IBase1.A<class G3_C1717`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.T.T<class BaseClass0,class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.A.T<class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G2_C692.A.B<class G3_C1717`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.MI.11376<System.Object>()#G2_C692::Method3.11377<System.Object>()#" call void Generated1245::M.IBase0<class G3_C1717`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G3_C1717::ClassMethod4833.17614()#G3_C1717::ClassMethod4834.17615<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G3_C1717.T<class BaseClass1,class G3_C1717`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()#G1_C13::ClassMethod1349.4877<System.Object>()#G2_C692::ClassMethod2746.11384()#G2_C692::ClassMethod2747.11385<System.Object>()#G3_C1717::ClassMethod4833.17614()#G3_C1717::ClassMethod4834.17615<System.Object>()#G2_C692::Method0.11373()#G2_C692::Method1.11374()#G2_C692::Method2.11375<System.Object>()#G2_C692::Method3.11377<System.Object>()#G2_C692::Method4.11378()#G2_C692::Method5.11380()#G2_C692::Method6.11382<System.Object>()#G3_C1717::Method7.17613<System.Object>()#" call void Generated1245::M.G3_C1717.B<class G3_C1717`1<class BaseClass1>>(!!0,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1717`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method5.11380()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method4.11378()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method4.MI.11379()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method5.MI.11381()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method6.MI.11383<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2747<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod2746() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method5.11380()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method4.11378()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method3<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method2<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method1() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method1.11374()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method0() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method0.11373()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method0.11373()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method1.11374()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method2.MI.11376<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod4834<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::ClassMethod4834.17615<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod4833() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::ClassMethod4833.17614()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod2747<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod2746() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method5() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method5.11380()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method4() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method4.11378()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method3<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method2<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method1() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method1.11374()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::Method0() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::Method0.11373()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass0>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass0>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G3_C1717`1<class BaseClass0> on type class G3_C1717`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G3_C1717`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G1_C13::Method6.4875<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method5.11380()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method4.11378()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C13`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C13`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G1_C13`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method4.MI.11379()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method5.MI.11381()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method6.MI.11383<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2747<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod2746() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method5() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method5.11380()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method4() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method4.11378()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method3<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method2<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method1() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method1.11374()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method0() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method0.11373()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C692`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C692`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G2_C692`2<class BaseClass0,class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method0() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method0.11373()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method1() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method1.11374()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method2<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method2.MI.11376<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string IBase0::Method3<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "IBase0 on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod4834<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::ClassMethod4834.17615<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod4833() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::ClassMethod4833.17614()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G3_C1717::Method7.17613<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod2747<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod2747.11385<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod2746() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod2746.11384()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method6.11382<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method5() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method5.11380()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method4() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method4.11378()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method3<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method3.11377<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method2<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method2.11375<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method1() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method1.11374()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::Method0() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::Method0.11373()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod1349<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G1_C13::ClassMethod1349.4877<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1717`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1717`1<class BaseClass1>::ClassMethod1348<object>() calli default string(class G3_C1717`1<class BaseClass1>) ldstr "G2_C692::ClassMethod1348.MI.11386<System.Object>()" ldstr "class G3_C1717`1<class BaseClass1> on type class G3_C1717`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated1245::MethodCallingTest() call void Generated1245::ConstrainedCallsTest() call void Generated1245::StructConstrainedInterfaceCallsTest() call void Generated1245::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/BuildWasmApps/Wasm.Build.Tests/BuildEnvironment.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; #nullable enable namespace Wasm.Build.Tests { public class BuildEnvironment { public string DotNet { get; init; } public string RuntimePackDir { get; init; } public bool IsWorkload { get; init; } public string DefaultBuildArgs { get; init; } public IDictionary<string, string> EnvVars { get; init; } public string DirectoryBuildPropsContents { get; init; } public string DirectoryBuildTargetsContents { get; init; } public string RuntimeNativeDir { get; init; } public string LogRootPath { get; init; } public static readonly string RelativeTestAssetsPath = @"..\testassets\"; public static readonly string TestAssetsPath = Path.Combine(AppContext.BaseDirectory, "testassets"); public static readonly string TestDataPath = Path.Combine(AppContext.BaseDirectory, "data"); private static string s_runtimeConfig = "Release"; public BuildEnvironment() { DirectoryInfo? solutionRoot = new (AppContext.BaseDirectory); while (solutionRoot != null) { if (File.Exists(Path.Combine(solutionRoot.FullName, "NuGet.config"))) { break; } solutionRoot = solutionRoot.Parent; } string? sdkForWorkloadPath = EnvironmentVariables.SdkForWorkloadTestingPath; if (string.IsNullOrEmpty(sdkForWorkloadPath)) throw new Exception($"Environment variable SDK_FOR_WORKLOAD_TESTING_PATH not set"); if (!Directory.Exists(sdkForWorkloadPath)) throw new Exception($"Could not find SDK_FOR_WORKLOAD_TESTING_PATH={sdkForWorkloadPath}"); bool workloadInstalled = EnvironmentVariables.SdkHasWorkloadInstalled != null && EnvironmentVariables.SdkHasWorkloadInstalled == "true"; if (workloadInstalled) { var workloadPacksVersion = EnvironmentVariables.WorkloadPacksVersion; if (string.IsNullOrEmpty(workloadPacksVersion)) throw new Exception($"Cannot test with workloads without WORKLOAD_PACKS_VER environment variable being set"); RuntimePackDir = Path.Combine(sdkForWorkloadPath, "packs", "Microsoft.NETCore.App.Runtime.Mono.browser-wasm", workloadPacksVersion); DirectoryBuildPropsContents = s_directoryBuildPropsForWorkloads; DirectoryBuildTargetsContents = s_directoryBuildTargetsForWorkloads; EnvVars = new Dictionary<string, string>(); var appRefDir = EnvironmentVariables.AppRefDir; if (string.IsNullOrEmpty(appRefDir)) throw new Exception($"Cannot test with workloads without AppRefDir environment variable being set"); DefaultBuildArgs = $" /p:AppRefDir={appRefDir}"; IsWorkload = true; } else { string emsdkPath; if (solutionRoot == null) { string? buildDir = EnvironmentVariables.WasmBuildSupportDir; if (buildDir == null || !Directory.Exists(buildDir)) throw new Exception($"Could not find the solution root, or a build dir: {buildDir}"); emsdkPath = Path.Combine(buildDir, "emsdk"); RuntimePackDir = Path.Combine(buildDir, "microsoft.netcore.app.runtime.browser-wasm"); DefaultBuildArgs = $" /p:WasmBuildSupportDir={buildDir} /p:EMSDK_PATH={emsdkPath} "; } else { string artifactsBinDir = Path.Combine(solutionRoot.FullName, "artifacts", "bin"); RuntimePackDir = Path.Combine(artifactsBinDir, "microsoft.netcore.app.runtime.browser-wasm", s_runtimeConfig); if (string.IsNullOrEmpty(EnvironmentVariables.EMSDK_PATH)) emsdkPath = Path.Combine(solutionRoot.FullName, "src", "mono", "wasm", "emsdk"); else emsdkPath = EnvironmentVariables.EMSDK_PATH; DefaultBuildArgs = $" /p:RuntimeSrcDir={solutionRoot.FullName} /p:RuntimeConfig={s_runtimeConfig} /p:EMSDK_PATH={emsdkPath} "; } IsWorkload = false; EnvVars = new Dictionary<string, string>() { ["EMSDK_PATH"] = emsdkPath }; DirectoryBuildPropsContents = s_directoryBuildPropsForLocal; DirectoryBuildTargetsContents = s_directoryBuildTargetsForLocal; } // `runtime` repo's build environment sets these, and they // mess up the build for the test project, which is using a different // dotnet EnvVars["DOTNET_INSTALL_DIR"] = sdkForWorkloadPath; EnvVars["DOTNET_MULTILEVEL_LOOKUP"] = "0"; EnvVars["DOTNET_SKIP_FIRST_TIME_EXPERIENCE"] = "1"; EnvVars["_WasmStrictVersionMatch"] = "true"; EnvVars["MSBuildSDKsPath"] = string.Empty; EnvVars["PATH"] = $"{sdkForWorkloadPath}{Path.PathSeparator}{Environment.GetEnvironmentVariable("PATH")}"; // helps with debugging EnvVars["WasmNativeStrip"] = "false"; if (OperatingSystem.IsWindows()) { EnvVars["WasmCachePath"] = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".emscripten-cache"); } RuntimeNativeDir = Path.Combine(RuntimePackDir, "runtimes", "browser-wasm", "native"); DotNet = Path.Combine(sdkForWorkloadPath!, "dotnet"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) DotNet += ".exe"; if (!string.IsNullOrEmpty(EnvironmentVariables.TestLogPath)) { LogRootPath = EnvironmentVariables.TestLogPath; if (!Directory.Exists(LogRootPath)) { Directory.CreateDirectory(LogRootPath); } } else { LogRootPath = Environment.CurrentDirectory; } } protected static string s_directoryBuildPropsForWorkloads = File.ReadAllText(Path.Combine(TestDataPath, "Workloads.Directory.Build.props")); protected static string s_directoryBuildTargetsForWorkloads = File.ReadAllText(Path.Combine(TestDataPath, "Workloads.Directory.Build.targets")); protected static string s_directoryBuildPropsForLocal = File.ReadAllText(Path.Combine(TestDataPath, "Local.Directory.Build.props")); protected static string s_directoryBuildTargetsForLocal = File.ReadAllText(Path.Combine(TestDataPath, "Local.Directory.Build.targets")); protected static string s_directoryBuildPropsForBlazorLocal = File.ReadAllText(Path.Combine(TestDataPath, "Blazor.Local.Directory.Build.props")); protected static string s_directoryBuildTargetsForBlazorLocal = File.ReadAllText(Path.Combine(TestDataPath, "Blazor.Local.Directory.Build.targets")); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; #nullable enable namespace Wasm.Build.Tests { public class BuildEnvironment { public string DotNet { get; init; } public string RuntimePackDir { get; init; } public bool IsWorkload { get; init; } public string DefaultBuildArgs { get; init; } public IDictionary<string, string> EnvVars { get; init; } public string DirectoryBuildPropsContents { get; init; } public string DirectoryBuildTargetsContents { get; init; } public string RuntimeNativeDir { get; init; } public string LogRootPath { get; init; } public static readonly string RelativeTestAssetsPath = @"..\testassets\"; public static readonly string TestAssetsPath = Path.Combine(AppContext.BaseDirectory, "testassets"); public static readonly string TestDataPath = Path.Combine(AppContext.BaseDirectory, "data"); private static string s_runtimeConfig = "Release"; public BuildEnvironment() { DirectoryInfo? solutionRoot = new (AppContext.BaseDirectory); while (solutionRoot != null) { if (File.Exists(Path.Combine(solutionRoot.FullName, "NuGet.config"))) { break; } solutionRoot = solutionRoot.Parent; } string? sdkForWorkloadPath = EnvironmentVariables.SdkForWorkloadTestingPath; if (string.IsNullOrEmpty(sdkForWorkloadPath)) throw new Exception($"Environment variable SDK_FOR_WORKLOAD_TESTING_PATH not set"); if (!Directory.Exists(sdkForWorkloadPath)) throw new Exception($"Could not find SDK_FOR_WORKLOAD_TESTING_PATH={sdkForWorkloadPath}"); bool workloadInstalled = EnvironmentVariables.SdkHasWorkloadInstalled != null && EnvironmentVariables.SdkHasWorkloadInstalled == "true"; if (workloadInstalled) { var workloadPacksVersion = EnvironmentVariables.WorkloadPacksVersion; if (string.IsNullOrEmpty(workloadPacksVersion)) throw new Exception($"Cannot test with workloads without WORKLOAD_PACKS_VER environment variable being set"); RuntimePackDir = Path.Combine(sdkForWorkloadPath, "packs", "Microsoft.NETCore.App.Runtime.Mono.browser-wasm", workloadPacksVersion); DirectoryBuildPropsContents = s_directoryBuildPropsForWorkloads; DirectoryBuildTargetsContents = s_directoryBuildTargetsForWorkloads; EnvVars = new Dictionary<string, string>(); var appRefDir = EnvironmentVariables.AppRefDir; if (string.IsNullOrEmpty(appRefDir)) throw new Exception($"Cannot test with workloads without AppRefDir environment variable being set"); DefaultBuildArgs = $" /p:AppRefDir={appRefDir}"; IsWorkload = true; } else { string emsdkPath; if (solutionRoot == null) { string? buildDir = EnvironmentVariables.WasmBuildSupportDir; if (buildDir == null || !Directory.Exists(buildDir)) throw new Exception($"Could not find the solution root, or a build dir: {buildDir}"); emsdkPath = Path.Combine(buildDir, "emsdk"); RuntimePackDir = Path.Combine(buildDir, "microsoft.netcore.app.runtime.browser-wasm"); DefaultBuildArgs = $" /p:WasmBuildSupportDir={buildDir} /p:EMSDK_PATH={emsdkPath} "; } else { string artifactsBinDir = Path.Combine(solutionRoot.FullName, "artifacts", "bin"); RuntimePackDir = Path.Combine(artifactsBinDir, "microsoft.netcore.app.runtime.browser-wasm", s_runtimeConfig); if (string.IsNullOrEmpty(EnvironmentVariables.EMSDK_PATH)) emsdkPath = Path.Combine(solutionRoot.FullName, "src", "mono", "wasm", "emsdk"); else emsdkPath = EnvironmentVariables.EMSDK_PATH; DefaultBuildArgs = $" /p:RuntimeSrcDir={solutionRoot.FullName} /p:RuntimeConfig={s_runtimeConfig} /p:EMSDK_PATH={emsdkPath} "; } IsWorkload = false; EnvVars = new Dictionary<string, string>() { ["EMSDK_PATH"] = emsdkPath }; DirectoryBuildPropsContents = s_directoryBuildPropsForLocal; DirectoryBuildTargetsContents = s_directoryBuildTargetsForLocal; } // `runtime` repo's build environment sets these, and they // mess up the build for the test project, which is using a different // dotnet EnvVars["DOTNET_INSTALL_DIR"] = sdkForWorkloadPath; EnvVars["DOTNET_MULTILEVEL_LOOKUP"] = "0"; EnvVars["DOTNET_SKIP_FIRST_TIME_EXPERIENCE"] = "1"; EnvVars["_WasmStrictVersionMatch"] = "true"; EnvVars["MSBuildSDKsPath"] = string.Empty; EnvVars["PATH"] = $"{sdkForWorkloadPath}{Path.PathSeparator}{Environment.GetEnvironmentVariable("PATH")}"; // helps with debugging EnvVars["WasmNativeStrip"] = "false"; if (OperatingSystem.IsWindows()) { EnvVars["WasmCachePath"] = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".emscripten-cache"); } RuntimeNativeDir = Path.Combine(RuntimePackDir, "runtimes", "browser-wasm", "native"); DotNet = Path.Combine(sdkForWorkloadPath!, "dotnet"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) DotNet += ".exe"; if (!string.IsNullOrEmpty(EnvironmentVariables.TestLogPath)) { LogRootPath = EnvironmentVariables.TestLogPath; if (!Directory.Exists(LogRootPath)) { Directory.CreateDirectory(LogRootPath); } } else { LogRootPath = Environment.CurrentDirectory; } } protected static string s_directoryBuildPropsForWorkloads = File.ReadAllText(Path.Combine(TestDataPath, "Workloads.Directory.Build.props")); protected static string s_directoryBuildTargetsForWorkloads = File.ReadAllText(Path.Combine(TestDataPath, "Workloads.Directory.Build.targets")); protected static string s_directoryBuildPropsForLocal = File.ReadAllText(Path.Combine(TestDataPath, "Local.Directory.Build.props")); protected static string s_directoryBuildTargetsForLocal = File.ReadAllText(Path.Combine(TestDataPath, "Local.Directory.Build.targets")); protected static string s_directoryBuildPropsForBlazorLocal = File.ReadAllText(Path.Combine(TestDataPath, "Blazor.Local.Directory.Build.props")); protected static string s_directoryBuildTargetsForBlazorLocal = File.ReadAllText(Path.Combine(TestDataPath, "Blazor.Local.Directory.Build.targets")); } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/mono/System.Private.CoreLib/src/Mono/RuntimeMarshal.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace Mono { internal static class RuntimeMarshal { internal static string PtrToUtf8String(IntPtr ptr) { unsafe { if (ptr == IntPtr.Zero) return string.Empty; byte* bytes = (byte*)ptr; int length = 0; try { while (bytes++[0] != 0) length++; } catch (NullReferenceException) { throw new ArgumentOutOfRangeException(nameof(ptr), "Value does not refer to a valid string."); } return new string((sbyte*)ptr, 0, length, System.Text.Encoding.UTF8); } } internal static SafeStringMarshal MarshalString(string? str) { return new SafeStringMarshal(str); } private static int DecodeBlobSize(IntPtr in_ptr, out IntPtr out_ptr) { uint size; unsafe { byte* ptr = (byte*)in_ptr; if ((*ptr & 0x80) == 0) { size = (uint)(ptr[0] & 0x7f); ptr++; } else if ((*ptr & 0x40) == 0) { size = (uint)(((ptr[0] & 0x3f) << 8) + ptr[1]); ptr += 2; } else { size = (uint)(((ptr[0] & 0x1f) << 24) + (ptr[1] << 16) + (ptr[2] << 8) + ptr[3]); ptr += 4; } out_ptr = (IntPtr)ptr; } return (int)size; } internal static byte[] DecodeBlobArray(IntPtr ptr) { IntPtr out_ptr; int size = DecodeBlobSize(ptr, out out_ptr); byte[] res = new byte[size]; Marshal.Copy(out_ptr, res, 0, size); return res; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void FreeAssemblyName(ref MonoAssemblyName name, bool freeStruct); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace Mono { internal static class RuntimeMarshal { internal static string PtrToUtf8String(IntPtr ptr) { unsafe { if (ptr == IntPtr.Zero) return string.Empty; byte* bytes = (byte*)ptr; int length = 0; try { while (bytes++[0] != 0) length++; } catch (NullReferenceException) { throw new ArgumentOutOfRangeException(nameof(ptr), "Value does not refer to a valid string."); } return new string((sbyte*)ptr, 0, length, System.Text.Encoding.UTF8); } } internal static SafeStringMarshal MarshalString(string? str) { return new SafeStringMarshal(str); } private static int DecodeBlobSize(IntPtr in_ptr, out IntPtr out_ptr) { uint size; unsafe { byte* ptr = (byte*)in_ptr; if ((*ptr & 0x80) == 0) { size = (uint)(ptr[0] & 0x7f); ptr++; } else if ((*ptr & 0x40) == 0) { size = (uint)(((ptr[0] & 0x3f) << 8) + ptr[1]); ptr += 2; } else { size = (uint)(((ptr[0] & 0x1f) << 24) + (ptr[1] << 16) + (ptr[2] << 8) + ptr[3]); ptr += 4; } out_ptr = (IntPtr)ptr; } return (int)size; } internal static byte[] DecodeBlobArray(IntPtr ptr) { IntPtr out_ptr; int size = DecodeBlobSize(ptr, out out_ptr); byte[] res = new byte[size]; Marshal.Copy(out_ptr, res, 0, size); return res; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void FreeAssemblyName(ref MonoAssemblyName name, bool freeStruct); } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/Loader/classloader/DefaultInterfaceMethods/regressions/github58394.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/StandardTests/xsd10/attributeGroup/attgC026vInc.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:attributeGroup name="car"> <xsd:attribute name="model"/> <xsd:attribute name="age" type="xsd:int"/> <xsd:attribute name="attFix" type="xsd:int" fixed="37"/> </xsd:attributeGroup> </xsd:schema>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:attributeGroup name="car"> <xsd:attribute name="model"/> <xsd:attribute name="age" type="xsd:int"/> <xsd:attribute name="attFix" type="xsd:int" fixed="37"/> </xsd:attributeGroup> </xsd:schema>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest685/Generated685.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated685.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated685.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Directed/cmov/Bool_No_Op_cs_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Bool_No_Op.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Bool_No_Op.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SimpleGatewayIPAddressInformation.Unix.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Net.NetworkInformation { internal sealed class SimpleGatewayIPAddressInformation : GatewayIPAddressInformation { private readonly IPAddress _address; public SimpleGatewayIPAddressInformation(IPAddress address) { _address = address; } public override IPAddress Address { get { return _address; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Net.NetworkInformation { internal sealed class SimpleGatewayIPAddressInformation : GatewayIPAddressInformation { private readonly IPAddress _address; public SimpleGatewayIPAddressInformation(IPAddress address) { _address = address; } public override IPAddress Address { get { return _address; } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/HardwareIntrinsics/X86/Sse41/Insert.SByte.129.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertSByte129() { var test = new InsertScalarTest__InsertSByte129(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertScalarTest__InsertSByte129 { private struct TestStruct { public Vector128<SByte> _fld; public SByte _scalarFldData; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); testStruct._scalarFldData = (sbyte)2; return testStruct; } public void RunStructFldScenario(InsertScalarTest__InsertSByte129 testClass) { var result = Sse41.Insert(_fld, _scalarFldData, 129); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, _scalarFldData, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data = new SByte[Op1ElementCount]; private static SByte _scalarClsData = (sbyte)2; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private SByte _scalarFldData = (sbyte)2; private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable; static InsertScalarTest__InsertSByte129() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public InsertScalarTest__InsertSByte129() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); var result = Sse41.Insert( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (sbyte)2, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); SByte localData = (sbyte)2; SByte* ptr = &localData; var result = Sse41.Insert( Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)), *ptr, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); SByte localData = (sbyte)2; SByte* ptr = &localData; var result = Sse41.Insert( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)), *ptr, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (sbyte)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Insert( _clsVar, _scalarClsData, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _scalarClsData,_dataTable.outArrayPtr); } public void RunLclVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario)); SByte localData = (sbyte)2; var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = Sse41.Insert(firstOp, localData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); SByte localData = (sbyte)2; var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, localData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); SByte localData = (sbyte)2; var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, localData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertScalarTest__InsertSByte129(); var result = Sse41.Insert(test._fld, test._scalarFldData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Insert(_fld, _scalarFldData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _scalarFldData, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Insert(test._fld, test._scalarFldData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> firstOp, SByte scalarData, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(void* firstOp, SByte scalarData, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte scalarData, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if ((i == 1 ? result[i] != scalarData : result[i] != firstOp[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<SByte>(Vector128<SByte><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertSByte129() { var test = new InsertScalarTest__InsertSByte129(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertScalarTest__InsertSByte129 { private struct TestStruct { public Vector128<SByte> _fld; public SByte _scalarFldData; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); testStruct._scalarFldData = (sbyte)2; return testStruct; } public void RunStructFldScenario(InsertScalarTest__InsertSByte129 testClass) { var result = Sse41.Insert(_fld, _scalarFldData, 129); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, _scalarFldData, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data = new SByte[Op1ElementCount]; private static SByte _scalarClsData = (sbyte)2; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private SByte _scalarFldData = (sbyte)2; private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable; static InsertScalarTest__InsertSByte129() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public InsertScalarTest__InsertSByte129() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); var result = Sse41.Insert( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (sbyte)2, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); SByte localData = (sbyte)2; SByte* ptr = &localData; var result = Sse41.Insert( Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)), *ptr, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public unsafe void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); SByte localData = (sbyte)2; SByte* ptr = &localData; var result = Sse41.Insert( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)), *ptr, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (sbyte)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Insert( _clsVar, _scalarClsData, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _scalarClsData,_dataTable.outArrayPtr); } public void RunLclVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario)); SByte localData = (sbyte)2; var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = Sse41.Insert(firstOp, localData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); SByte localData = (sbyte)2; var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, localData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); SByte localData = (sbyte)2; var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, localData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, localData, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertScalarTest__InsertSByte129(); var result = Sse41.Insert(test._fld, test._scalarFldData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Insert(_fld, _scalarFldData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _scalarFldData, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Insert(test._fld, test._scalarFldData, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> firstOp, SByte scalarData, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(void* firstOp, SByte scalarData, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray, scalarData, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte scalarData, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if ((i == 1 ? result[i] != scalarData : result[i] != firstOp[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<SByte>(Vector128<SByte><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/Common/tests/StreamConformanceTests/StreamConformanceTests.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> </PropertyGroup> <ItemGroup> <Compile Include="System\IO\*.cs" /> </ItemGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\IO\ConnectedStreams.cs" Link="System\IO\ConnectedStreams.cs" /> <Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs" Link="System\Threading\Tasks\TaskToApm.cs" /> <Compile Include="$(CommonPath)System\Net\ArrayBuffer.cs" Link="Common\System\Net\ArrayBuffer.cs" /> <Compile Include="$(CommonPath)System\Net\MultiArrayBuffer.cs" Link="Common\System\Net\MultiArrayBuffer.cs" /> <Compile Include="$(CommonPath)System\Net\StreamBuffer.cs" Link="Common\System\Net\StreamBuffer.cs" /> <Compile Include="$(CommonPath)System\IO\DelegatingStream.cs" Link="Common\System\IO\DelegatingStream.cs" /> <Compile Include="$(CommonTestPath)System\IO\CallTrackingStream.cs" Link="Common\System\IO\CallTrackingStream.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.DotNet.XUnitExtensions" Version="$(MicrosoftDotNetXUnitExtensionsVersion)" /> <PackageReference Include="xunit.core" Version="$(XUnitVersion)" ExcludeAssets="build" /> <PackageReference Include="xunit.assert" Version="$(XUnitVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(CommonTestPath)TestUtilities\TestUtilities.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> </PropertyGroup> <ItemGroup> <Compile Include="System\IO\*.cs" /> </ItemGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\IO\ConnectedStreams.cs" Link="System\IO\ConnectedStreams.cs" /> <Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs" Link="System\Threading\Tasks\TaskToApm.cs" /> <Compile Include="$(CommonPath)System\Net\ArrayBuffer.cs" Link="Common\System\Net\ArrayBuffer.cs" /> <Compile Include="$(CommonPath)System\Net\MultiArrayBuffer.cs" Link="Common\System\Net\MultiArrayBuffer.cs" /> <Compile Include="$(CommonPath)System\Net\StreamBuffer.cs" Link="Common\System\Net\StreamBuffer.cs" /> <Compile Include="$(CommonPath)System\IO\DelegatingStream.cs" Link="Common\System\IO\DelegatingStream.cs" /> <Compile Include="$(CommonTestPath)System\IO\CallTrackingStream.cs" Link="Common\System\IO\CallTrackingStream.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.DotNet.XUnitExtensions" Version="$(MicrosoftDotNetXUnitExtensionsVersion)" /> <PackageReference Include="xunit.core" Version="$(XUnitVersion)" ExcludeAssets="build" /> <PackageReference Include="xunit.assert" Version="$(XUnitVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(CommonTestPath)TestUtilities\TestUtilities.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b77713/b77713.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace Test { using System; public class BB { public static void Main1() { bool local2 = false; try { if (local2) return; } finally { throw new Exception(); } } public static int Main() { try { Main1(); } catch (Exception) { return 100; } return 101; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace Test { using System; public class BB { public static void Main1() { bool local2 = false; try { if (local2) return; } finally { throw new Exception(); } } public static int Main() { try { Main1(); } catch (Exception) { return 100; } return 101; } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Directed/TypedReference/TypedReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; public class BringUpTest_TypedReference { const int Pass = 100; const int Fail = -1; const string Apple = "apple"; const string Orange = "orange"; public static int Main() { int i = Fail; F(__makeref(i)); if (i != Pass) return Fail; string j = Apple; G(__makeref(j)); if (j != Orange) return Fail; return Pass; } static void F(System.TypedReference t) { __refvalue(t, int) = Pass; } static void G(System.TypedReference t) { __refvalue(t, string) = Orange; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; public class BringUpTest_TypedReference { const int Pass = 100; const int Fail = -1; const string Apple = "apple"; const string Orange = "orange"; public static int Main() { int i = Fail; F(__makeref(i)); if (i != Pass) return Fail; string j = Apple; G(__makeref(j)); if (j != Orange) return Fail; return Pass; } static void F(System.TypedReference t) { __refvalue(t, int) = Pass; } static void G(System.TypedReference t) { __refvalue(t, string) = Orange; } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/Program.AdvSimd.Arm64_Part1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { static Program() { TestList = new Dictionary<string, Action>() { ["CompareGreaterThanScalar.Vector64.UInt64"] = CompareGreaterThanScalar_Vector64_UInt64, ["CompareGreaterThanOrEqual.Vector128.Double"] = CompareGreaterThanOrEqual_Vector128_Double, ["CompareGreaterThanOrEqual.Vector128.Int64"] = CompareGreaterThanOrEqual_Vector128_Int64, ["CompareGreaterThanOrEqual.Vector128.UInt64"] = CompareGreaterThanOrEqual_Vector128_UInt64, ["CompareGreaterThanOrEqualScalar.Vector64.Double"] = CompareGreaterThanOrEqualScalar_Vector64_Double, ["CompareGreaterThanOrEqualScalar.Vector64.Int64"] = CompareGreaterThanOrEqualScalar_Vector64_Int64, ["CompareGreaterThanOrEqualScalar.Vector64.Single"] = CompareGreaterThanOrEqualScalar_Vector64_Single, ["CompareGreaterThanOrEqualScalar.Vector64.UInt64"] = CompareGreaterThanOrEqualScalar_Vector64_UInt64, ["CompareLessThan.Vector128.Double"] = CompareLessThan_Vector128_Double, ["CompareLessThan.Vector128.Int64"] = CompareLessThan_Vector128_Int64, ["CompareLessThan.Vector128.UInt64"] = CompareLessThan_Vector128_UInt64, ["CompareLessThanScalar.Vector64.Double"] = CompareLessThanScalar_Vector64_Double, ["CompareLessThanScalar.Vector64.Int64"] = CompareLessThanScalar_Vector64_Int64, ["CompareLessThanScalar.Vector64.Single"] = CompareLessThanScalar_Vector64_Single, ["CompareLessThanScalar.Vector64.UInt64"] = CompareLessThanScalar_Vector64_UInt64, ["CompareLessThanOrEqual.Vector128.Double"] = CompareLessThanOrEqual_Vector128_Double, ["CompareLessThanOrEqual.Vector128.Int64"] = CompareLessThanOrEqual_Vector128_Int64, ["CompareLessThanOrEqual.Vector128.UInt64"] = CompareLessThanOrEqual_Vector128_UInt64, ["CompareLessThanOrEqualScalar.Vector64.Double"] = CompareLessThanOrEqualScalar_Vector64_Double, ["CompareLessThanOrEqualScalar.Vector64.Int64"] = CompareLessThanOrEqualScalar_Vector64_Int64, ["CompareLessThanOrEqualScalar.Vector64.Single"] = CompareLessThanOrEqualScalar_Vector64_Single, ["CompareLessThanOrEqualScalar.Vector64.UInt64"] = CompareLessThanOrEqualScalar_Vector64_UInt64, ["CompareTest.Vector128.Double"] = CompareTest_Vector128_Double, ["CompareTest.Vector128.Int64"] = CompareTest_Vector128_Int64, ["CompareTest.Vector128.UInt64"] = CompareTest_Vector128_UInt64, ["CompareTestScalar.Vector64.Double"] = CompareTestScalar_Vector64_Double, ["CompareTestScalar.Vector64.Int64"] = CompareTestScalar_Vector64_Int64, ["CompareTestScalar.Vector64.UInt64"] = CompareTestScalar_Vector64_UInt64, ["ConvertToDouble.Vector64.Single"] = ConvertToDouble_Vector64_Single, ["ConvertToDouble.Vector128.Int64"] = ConvertToDouble_Vector128_Int64, ["ConvertToDouble.Vector128.UInt64"] = ConvertToDouble_Vector128_UInt64, ["ConvertToDoubleScalar.Vector64.Int64"] = ConvertToDoubleScalar_Vector64_Int64, ["ConvertToDoubleScalar.Vector64.UInt64"] = ConvertToDoubleScalar_Vector64_UInt64, ["ConvertToDoubleUpper.Vector128.Single"] = ConvertToDoubleUpper_Vector128_Single, ["ConvertToInt64RoundAwayFromZero.Vector128.Double"] = ConvertToInt64RoundAwayFromZero_Vector128_Double, ["ConvertToInt64RoundAwayFromZeroScalar.Vector64.Double"] = ConvertToInt64RoundAwayFromZeroScalar_Vector64_Double, ["ConvertToInt64RoundToEven.Vector128.Double"] = ConvertToInt64RoundToEven_Vector128_Double, ["ConvertToInt64RoundToEvenScalar.Vector64.Double"] = ConvertToInt64RoundToEvenScalar_Vector64_Double, ["ConvertToInt64RoundToNegativeInfinity.Vector128.Double"] = ConvertToInt64RoundToNegativeInfinity_Vector128_Double, ["ConvertToInt64RoundToNegativeInfinityScalar.Vector64.Double"] = ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double, ["ConvertToInt64RoundToPositiveInfinity.Vector128.Double"] = ConvertToInt64RoundToPositiveInfinity_Vector128_Double, ["ConvertToInt64RoundToPositiveInfinityScalar.Vector64.Double"] = ConvertToInt64RoundToPositiveInfinityScalar_Vector64_Double, ["ConvertToInt64RoundToZero.Vector128.Double"] = ConvertToInt64RoundToZero_Vector128_Double, ["ConvertToInt64RoundToZeroScalar.Vector64.Double"] = ConvertToInt64RoundToZeroScalar_Vector64_Double, ["ConvertToSingleLower.Vector64.Single"] = ConvertToSingleLower_Vector64_Single, ["ConvertToSingleRoundToOddLower.Vector64.Single"] = ConvertToSingleRoundToOddLower_Vector64_Single, ["ConvertToSingleRoundToOddUpper.Vector128.Single"] = ConvertToSingleRoundToOddUpper_Vector128_Single, ["ConvertToSingleUpper.Vector128.Single"] = ConvertToSingleUpper_Vector128_Single, ["ConvertToUInt64RoundAwayFromZero.Vector128.Double"] = ConvertToUInt64RoundAwayFromZero_Vector128_Double, ["ConvertToUInt64RoundAwayFromZeroScalar.Vector64.Double"] = ConvertToUInt64RoundAwayFromZeroScalar_Vector64_Double, ["ConvertToUInt64RoundToEven.Vector128.Double"] = ConvertToUInt64RoundToEven_Vector128_Double, ["ConvertToUInt64RoundToEvenScalar.Vector64.Double"] = ConvertToUInt64RoundToEvenScalar_Vector64_Double, ["ConvertToUInt64RoundToNegativeInfinity.Vector128.Double"] = ConvertToUInt64RoundToNegativeInfinity_Vector128_Double, ["ConvertToUInt64RoundToNegativeInfinityScalar.Vector64.Double"] = ConvertToUInt64RoundToNegativeInfinityScalar_Vector64_Double, ["ConvertToUInt64RoundToPositiveInfinity.Vector128.Double"] = ConvertToUInt64RoundToPositiveInfinity_Vector128_Double, ["ConvertToUInt64RoundToPositiveInfinityScalar.Vector64.Double"] = ConvertToUInt64RoundToPositiveInfinityScalar_Vector64_Double, ["ConvertToUInt64RoundToZero.Vector128.Double"] = ConvertToUInt64RoundToZero_Vector128_Double, ["ConvertToUInt64RoundToZeroScalar.Vector64.Double"] = ConvertToUInt64RoundToZeroScalar_Vector64_Double, ["Divide.Vector64.Single"] = Divide_Vector64_Single, ["Divide.Vector128.Double"] = Divide_Vector128_Double, ["Divide.Vector128.Single"] = Divide_Vector128_Single, ["DuplicateSelectedScalarToVector128.V128.Double.1"] = DuplicateSelectedScalarToVector128_V128_Double_1, ["DuplicateSelectedScalarToVector128.V128.Int64.1"] = DuplicateSelectedScalarToVector128_V128_Int64_1, ["DuplicateSelectedScalarToVector128.V128.UInt64.1"] = DuplicateSelectedScalarToVector128_V128_UInt64_1, ["DuplicateToVector128.Double"] = DuplicateToVector128_Double, ["DuplicateToVector128.Double.31"] = DuplicateToVector128_Double_31, ["DuplicateToVector128.Int64"] = DuplicateToVector128_Int64, ["DuplicateToVector128.Int64.31"] = DuplicateToVector128_Int64_31, ["DuplicateToVector128.UInt64"] = DuplicateToVector128_UInt64, ["DuplicateToVector128.UInt64.31"] = DuplicateToVector128_UInt64_31, ["ExtractNarrowingSaturateScalar.Vector64.Byte"] = ExtractNarrowingSaturateScalar_Vector64_Byte, ["ExtractNarrowingSaturateScalar.Vector64.Int16"] = ExtractNarrowingSaturateScalar_Vector64_Int16, ["ExtractNarrowingSaturateScalar.Vector64.Int32"] = ExtractNarrowingSaturateScalar_Vector64_Int32, ["ExtractNarrowingSaturateScalar.Vector64.SByte"] = ExtractNarrowingSaturateScalar_Vector64_SByte, ["ExtractNarrowingSaturateScalar.Vector64.UInt16"] = ExtractNarrowingSaturateScalar_Vector64_UInt16, ["ExtractNarrowingSaturateScalar.Vector64.UInt32"] = ExtractNarrowingSaturateScalar_Vector64_UInt32, ["ExtractNarrowingSaturateUnsignedScalar.Vector64.Byte"] = ExtractNarrowingSaturateUnsignedScalar_Vector64_Byte, ["ExtractNarrowingSaturateUnsignedScalar.Vector64.UInt16"] = ExtractNarrowingSaturateUnsignedScalar_Vector64_UInt16, ["ExtractNarrowingSaturateUnsignedScalar.Vector64.UInt32"] = ExtractNarrowingSaturateUnsignedScalar_Vector64_UInt32, ["Floor.Vector128.Double"] = Floor_Vector128_Double, ["FusedMultiplyAdd.Vector128.Double"] = FusedMultiplyAdd_Vector128_Double, ["FusedMultiplyAddByScalar.Vector64.Single"] = FusedMultiplyAddByScalar_Vector64_Single, ["FusedMultiplyAddByScalar.Vector128.Double"] = FusedMultiplyAddByScalar_Vector128_Double, ["FusedMultiplyAddByScalar.Vector128.Single"] = FusedMultiplyAddByScalar_Vector128_Single, ["FusedMultiplyAddBySelectedScalar.Vector64.Single.Vector64.Single.1"] = FusedMultiplyAddBySelectedScalar_Vector64_Single_Vector64_Single_1, ["FusedMultiplyAddBySelectedScalar.Vector64.Single.Vector128.Single.3"] = FusedMultiplyAddBySelectedScalar_Vector64_Single_Vector128_Single_3, ["FusedMultiplyAddBySelectedScalar.Vector128.Double.Vector128.Double.1"] = FusedMultiplyAddBySelectedScalar_Vector128_Double_Vector128_Double_1, ["FusedMultiplyAddBySelectedScalar.Vector128.Single.Vector64.Single.1"] = FusedMultiplyAddBySelectedScalar_Vector128_Single_Vector64_Single_1, ["FusedMultiplyAddBySelectedScalar.Vector128.Single.Vector128.Single.3"] = FusedMultiplyAddBySelectedScalar_Vector128_Single_Vector128_Single_3, ["FusedMultiplyAddScalarBySelectedScalar.Vector64.Double.Vector128.Double.1"] = FusedMultiplyAddScalarBySelectedScalar_Vector64_Double_Vector128_Double_1, ["FusedMultiplyAddScalarBySelectedScalar.Vector64.Single.Vector64.Single.1"] = FusedMultiplyAddScalarBySelectedScalar_Vector64_Single_Vector64_Single_1, ["FusedMultiplyAddScalarBySelectedScalar.Vector64.Single.Vector128.Single.3"] = FusedMultiplyAddScalarBySelectedScalar_Vector64_Single_Vector128_Single_3, ["FusedMultiplySubtract.Vector128.Double"] = FusedMultiplySubtract_Vector128_Double, ["FusedMultiplySubtractByScalar.Vector64.Single"] = FusedMultiplySubtractByScalar_Vector64_Single, ["FusedMultiplySubtractByScalar.Vector128.Double"] = FusedMultiplySubtractByScalar_Vector128_Double, ["FusedMultiplySubtractByScalar.Vector128.Single"] = FusedMultiplySubtractByScalar_Vector128_Single, ["FusedMultiplySubtractBySelectedScalar.Vector64.Single.Vector64.Single.1"] = FusedMultiplySubtractBySelectedScalar_Vector64_Single_Vector64_Single_1, ["FusedMultiplySubtractBySelectedScalar.Vector64.Single.Vector128.Single.3"] = FusedMultiplySubtractBySelectedScalar_Vector64_Single_Vector128_Single_3, ["FusedMultiplySubtractBySelectedScalar.Vector128.Double.Vector128.Double.1"] = FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1, ["FusedMultiplySubtractBySelectedScalar.Vector128.Single.Vector64.Single.1"] = FusedMultiplySubtractBySelectedScalar_Vector128_Single_Vector64_Single_1, }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { static Program() { TestList = new Dictionary<string, Action>() { ["CompareGreaterThanScalar.Vector64.UInt64"] = CompareGreaterThanScalar_Vector64_UInt64, ["CompareGreaterThanOrEqual.Vector128.Double"] = CompareGreaterThanOrEqual_Vector128_Double, ["CompareGreaterThanOrEqual.Vector128.Int64"] = CompareGreaterThanOrEqual_Vector128_Int64, ["CompareGreaterThanOrEqual.Vector128.UInt64"] = CompareGreaterThanOrEqual_Vector128_UInt64, ["CompareGreaterThanOrEqualScalar.Vector64.Double"] = CompareGreaterThanOrEqualScalar_Vector64_Double, ["CompareGreaterThanOrEqualScalar.Vector64.Int64"] = CompareGreaterThanOrEqualScalar_Vector64_Int64, ["CompareGreaterThanOrEqualScalar.Vector64.Single"] = CompareGreaterThanOrEqualScalar_Vector64_Single, ["CompareGreaterThanOrEqualScalar.Vector64.UInt64"] = CompareGreaterThanOrEqualScalar_Vector64_UInt64, ["CompareLessThan.Vector128.Double"] = CompareLessThan_Vector128_Double, ["CompareLessThan.Vector128.Int64"] = CompareLessThan_Vector128_Int64, ["CompareLessThan.Vector128.UInt64"] = CompareLessThan_Vector128_UInt64, ["CompareLessThanScalar.Vector64.Double"] = CompareLessThanScalar_Vector64_Double, ["CompareLessThanScalar.Vector64.Int64"] = CompareLessThanScalar_Vector64_Int64, ["CompareLessThanScalar.Vector64.Single"] = CompareLessThanScalar_Vector64_Single, ["CompareLessThanScalar.Vector64.UInt64"] = CompareLessThanScalar_Vector64_UInt64, ["CompareLessThanOrEqual.Vector128.Double"] = CompareLessThanOrEqual_Vector128_Double, ["CompareLessThanOrEqual.Vector128.Int64"] = CompareLessThanOrEqual_Vector128_Int64, ["CompareLessThanOrEqual.Vector128.UInt64"] = CompareLessThanOrEqual_Vector128_UInt64, ["CompareLessThanOrEqualScalar.Vector64.Double"] = CompareLessThanOrEqualScalar_Vector64_Double, ["CompareLessThanOrEqualScalar.Vector64.Int64"] = CompareLessThanOrEqualScalar_Vector64_Int64, ["CompareLessThanOrEqualScalar.Vector64.Single"] = CompareLessThanOrEqualScalar_Vector64_Single, ["CompareLessThanOrEqualScalar.Vector64.UInt64"] = CompareLessThanOrEqualScalar_Vector64_UInt64, ["CompareTest.Vector128.Double"] = CompareTest_Vector128_Double, ["CompareTest.Vector128.Int64"] = CompareTest_Vector128_Int64, ["CompareTest.Vector128.UInt64"] = CompareTest_Vector128_UInt64, ["CompareTestScalar.Vector64.Double"] = CompareTestScalar_Vector64_Double, ["CompareTestScalar.Vector64.Int64"] = CompareTestScalar_Vector64_Int64, ["CompareTestScalar.Vector64.UInt64"] = CompareTestScalar_Vector64_UInt64, ["ConvertToDouble.Vector64.Single"] = ConvertToDouble_Vector64_Single, ["ConvertToDouble.Vector128.Int64"] = ConvertToDouble_Vector128_Int64, ["ConvertToDouble.Vector128.UInt64"] = ConvertToDouble_Vector128_UInt64, ["ConvertToDoubleScalar.Vector64.Int64"] = ConvertToDoubleScalar_Vector64_Int64, ["ConvertToDoubleScalar.Vector64.UInt64"] = ConvertToDoubleScalar_Vector64_UInt64, ["ConvertToDoubleUpper.Vector128.Single"] = ConvertToDoubleUpper_Vector128_Single, ["ConvertToInt64RoundAwayFromZero.Vector128.Double"] = ConvertToInt64RoundAwayFromZero_Vector128_Double, ["ConvertToInt64RoundAwayFromZeroScalar.Vector64.Double"] = ConvertToInt64RoundAwayFromZeroScalar_Vector64_Double, ["ConvertToInt64RoundToEven.Vector128.Double"] = ConvertToInt64RoundToEven_Vector128_Double, ["ConvertToInt64RoundToEvenScalar.Vector64.Double"] = ConvertToInt64RoundToEvenScalar_Vector64_Double, ["ConvertToInt64RoundToNegativeInfinity.Vector128.Double"] = ConvertToInt64RoundToNegativeInfinity_Vector128_Double, ["ConvertToInt64RoundToNegativeInfinityScalar.Vector64.Double"] = ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double, ["ConvertToInt64RoundToPositiveInfinity.Vector128.Double"] = ConvertToInt64RoundToPositiveInfinity_Vector128_Double, ["ConvertToInt64RoundToPositiveInfinityScalar.Vector64.Double"] = ConvertToInt64RoundToPositiveInfinityScalar_Vector64_Double, ["ConvertToInt64RoundToZero.Vector128.Double"] = ConvertToInt64RoundToZero_Vector128_Double, ["ConvertToInt64RoundToZeroScalar.Vector64.Double"] = ConvertToInt64RoundToZeroScalar_Vector64_Double, ["ConvertToSingleLower.Vector64.Single"] = ConvertToSingleLower_Vector64_Single, ["ConvertToSingleRoundToOddLower.Vector64.Single"] = ConvertToSingleRoundToOddLower_Vector64_Single, ["ConvertToSingleRoundToOddUpper.Vector128.Single"] = ConvertToSingleRoundToOddUpper_Vector128_Single, ["ConvertToSingleUpper.Vector128.Single"] = ConvertToSingleUpper_Vector128_Single, ["ConvertToUInt64RoundAwayFromZero.Vector128.Double"] = ConvertToUInt64RoundAwayFromZero_Vector128_Double, ["ConvertToUInt64RoundAwayFromZeroScalar.Vector64.Double"] = ConvertToUInt64RoundAwayFromZeroScalar_Vector64_Double, ["ConvertToUInt64RoundToEven.Vector128.Double"] = ConvertToUInt64RoundToEven_Vector128_Double, ["ConvertToUInt64RoundToEvenScalar.Vector64.Double"] = ConvertToUInt64RoundToEvenScalar_Vector64_Double, ["ConvertToUInt64RoundToNegativeInfinity.Vector128.Double"] = ConvertToUInt64RoundToNegativeInfinity_Vector128_Double, ["ConvertToUInt64RoundToNegativeInfinityScalar.Vector64.Double"] = ConvertToUInt64RoundToNegativeInfinityScalar_Vector64_Double, ["ConvertToUInt64RoundToPositiveInfinity.Vector128.Double"] = ConvertToUInt64RoundToPositiveInfinity_Vector128_Double, ["ConvertToUInt64RoundToPositiveInfinityScalar.Vector64.Double"] = ConvertToUInt64RoundToPositiveInfinityScalar_Vector64_Double, ["ConvertToUInt64RoundToZero.Vector128.Double"] = ConvertToUInt64RoundToZero_Vector128_Double, ["ConvertToUInt64RoundToZeroScalar.Vector64.Double"] = ConvertToUInt64RoundToZeroScalar_Vector64_Double, ["Divide.Vector64.Single"] = Divide_Vector64_Single, ["Divide.Vector128.Double"] = Divide_Vector128_Double, ["Divide.Vector128.Single"] = Divide_Vector128_Single, ["DuplicateSelectedScalarToVector128.V128.Double.1"] = DuplicateSelectedScalarToVector128_V128_Double_1, ["DuplicateSelectedScalarToVector128.V128.Int64.1"] = DuplicateSelectedScalarToVector128_V128_Int64_1, ["DuplicateSelectedScalarToVector128.V128.UInt64.1"] = DuplicateSelectedScalarToVector128_V128_UInt64_1, ["DuplicateToVector128.Double"] = DuplicateToVector128_Double, ["DuplicateToVector128.Double.31"] = DuplicateToVector128_Double_31, ["DuplicateToVector128.Int64"] = DuplicateToVector128_Int64, ["DuplicateToVector128.Int64.31"] = DuplicateToVector128_Int64_31, ["DuplicateToVector128.UInt64"] = DuplicateToVector128_UInt64, ["DuplicateToVector128.UInt64.31"] = DuplicateToVector128_UInt64_31, ["ExtractNarrowingSaturateScalar.Vector64.Byte"] = ExtractNarrowingSaturateScalar_Vector64_Byte, ["ExtractNarrowingSaturateScalar.Vector64.Int16"] = ExtractNarrowingSaturateScalar_Vector64_Int16, ["ExtractNarrowingSaturateScalar.Vector64.Int32"] = ExtractNarrowingSaturateScalar_Vector64_Int32, ["ExtractNarrowingSaturateScalar.Vector64.SByte"] = ExtractNarrowingSaturateScalar_Vector64_SByte, ["ExtractNarrowingSaturateScalar.Vector64.UInt16"] = ExtractNarrowingSaturateScalar_Vector64_UInt16, ["ExtractNarrowingSaturateScalar.Vector64.UInt32"] = ExtractNarrowingSaturateScalar_Vector64_UInt32, ["ExtractNarrowingSaturateUnsignedScalar.Vector64.Byte"] = ExtractNarrowingSaturateUnsignedScalar_Vector64_Byte, ["ExtractNarrowingSaturateUnsignedScalar.Vector64.UInt16"] = ExtractNarrowingSaturateUnsignedScalar_Vector64_UInt16, ["ExtractNarrowingSaturateUnsignedScalar.Vector64.UInt32"] = ExtractNarrowingSaturateUnsignedScalar_Vector64_UInt32, ["Floor.Vector128.Double"] = Floor_Vector128_Double, ["FusedMultiplyAdd.Vector128.Double"] = FusedMultiplyAdd_Vector128_Double, ["FusedMultiplyAddByScalar.Vector64.Single"] = FusedMultiplyAddByScalar_Vector64_Single, ["FusedMultiplyAddByScalar.Vector128.Double"] = FusedMultiplyAddByScalar_Vector128_Double, ["FusedMultiplyAddByScalar.Vector128.Single"] = FusedMultiplyAddByScalar_Vector128_Single, ["FusedMultiplyAddBySelectedScalar.Vector64.Single.Vector64.Single.1"] = FusedMultiplyAddBySelectedScalar_Vector64_Single_Vector64_Single_1, ["FusedMultiplyAddBySelectedScalar.Vector64.Single.Vector128.Single.3"] = FusedMultiplyAddBySelectedScalar_Vector64_Single_Vector128_Single_3, ["FusedMultiplyAddBySelectedScalar.Vector128.Double.Vector128.Double.1"] = FusedMultiplyAddBySelectedScalar_Vector128_Double_Vector128_Double_1, ["FusedMultiplyAddBySelectedScalar.Vector128.Single.Vector64.Single.1"] = FusedMultiplyAddBySelectedScalar_Vector128_Single_Vector64_Single_1, ["FusedMultiplyAddBySelectedScalar.Vector128.Single.Vector128.Single.3"] = FusedMultiplyAddBySelectedScalar_Vector128_Single_Vector128_Single_3, ["FusedMultiplyAddScalarBySelectedScalar.Vector64.Double.Vector128.Double.1"] = FusedMultiplyAddScalarBySelectedScalar_Vector64_Double_Vector128_Double_1, ["FusedMultiplyAddScalarBySelectedScalar.Vector64.Single.Vector64.Single.1"] = FusedMultiplyAddScalarBySelectedScalar_Vector64_Single_Vector64_Single_1, ["FusedMultiplyAddScalarBySelectedScalar.Vector64.Single.Vector128.Single.3"] = FusedMultiplyAddScalarBySelectedScalar_Vector64_Single_Vector128_Single_3, ["FusedMultiplySubtract.Vector128.Double"] = FusedMultiplySubtract_Vector128_Double, ["FusedMultiplySubtractByScalar.Vector64.Single"] = FusedMultiplySubtractByScalar_Vector64_Single, ["FusedMultiplySubtractByScalar.Vector128.Double"] = FusedMultiplySubtractByScalar_Vector128_Double, ["FusedMultiplySubtractByScalar.Vector128.Single"] = FusedMultiplySubtractByScalar_Vector128_Single, ["FusedMultiplySubtractBySelectedScalar.Vector64.Single.Vector64.Single.1"] = FusedMultiplySubtractBySelectedScalar_Vector64_Single_Vector64_Single_1, ["FusedMultiplySubtractBySelectedScalar.Vector64.Single.Vector128.Single.3"] = FusedMultiplySubtractBySelectedScalar_Vector64_Single_Vector128_Single_3, ["FusedMultiplySubtractBySelectedScalar.Vector128.Double.Vector128.Double.1"] = FusedMultiplySubtractBySelectedScalar_Vector128_Double_Vector128_Double_1, ["FusedMultiplySubtractBySelectedScalar.Vector128.Single.Vector64.Single.1"] = FusedMultiplySubtractBySelectedScalar_Vector128_Single_Vector64_Single_1, }; } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/CodeGenBringUpTests/JTrueGeFP.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; using System.Runtime.CompilerServices; public class BringUpTest_JTrueGeFP { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static int JTrueGeFP(float x) { int returnValue = -1; if (x >= 2f) returnValue = 4; else if (x >= 1f) returnValue = 3; else if (x >= 0f) returnValue = 2; else if (x >= -1f) returnValue = 1; return returnValue; } public static int Main() { int returnValue = Pass; if (JTrueGeFP(-1f) != 1) returnValue = Fail; if (JTrueGeFP(0f) != 2) returnValue = Fail; if (JTrueGeFP(1f) != 3) returnValue = Fail; if (JTrueGeFP(2f) != 4) returnValue = Fail; return returnValue; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; using System.Runtime.CompilerServices; public class BringUpTest_JTrueGeFP { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static int JTrueGeFP(float x) { int returnValue = -1; if (x >= 2f) returnValue = 4; else if (x >= 1f) returnValue = 3; else if (x >= 0f) returnValue = 2; else if (x >= -1f) returnValue = 1; return returnValue; } public static int Main() { int returnValue = Pass; if (JTrueGeFP(-1f) != 1) returnValue = Fail; if (JTrueGeFP(0f) != 2) returnValue = Fail; if (JTrueGeFP(1f) != 3) returnValue = Fail; if (JTrueGeFP(2f) != 4) returnValue = Fail; return returnValue; } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/Loader/classloader/Casting/punninglib.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern System.Runtime { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) } .assembly punninglib { } .class public sequential ansi sealed beforefieldinit Caller.Struct extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit Caller.Struct`1<T> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public auto ansi abstract sealed beforefieldinit Caller.Class extends [System.Runtime]System.Object { .method public hidebysig static int32 CallGetField ( valuetype Caller.Struct s, native int callbackRaw, object inst ) cil managed { ldarg.2 ldnull ceq brfalse.s FALSE TRUE: nop ldarg.0 ldarg.1 calli int32(valuetype Caller.Struct) br.s DONE FALSE: nop ldarg.2 ldarg.0 ldarg.1 calli instance int32(valuetype Caller.Struct) br.s DONE DONE: ret } .method public hidebysig static int32 CallGetField<T> ( valuetype Caller.Struct`1<!!T> s, native int callbackRaw, object inst ) cil managed { ldarg.2 ldnull ceq brfalse.s FALSE TRUE: nop ldarg.0 ldarg.1 calli int32(valuetype Caller.Struct`1<!!T>) br.s DONE FALSE: nop ldarg.2 ldarg.0 ldarg.1 calli instance int32(valuetype Caller.Struct`1<!!T>) br.s DONE DONE: ret } } // // Used for GetFunctionPointer() // .class public sequential ansi sealed beforefieldinit A.Struct extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit A.Struct`1<T> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public auto ansi beforefieldinit A.Class extends [System.Runtime]System.Object { .method public hidebysig static int32 GetField (valuetype A.Struct s) cil managed { ldarg.0 ldfld int32 A.Struct::Field ret } .method public hidebysig static int32 GetFieldGeneric<T> (valuetype A.Struct`1<!!T> s) cil managed { ldarg.0 ldfld int32 valuetype A.Struct`1<!!T>::Field ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [System.Runtime]System.Object::.ctor() ret } } // // Used for ldftn // .class public sequential ansi sealed beforefieldinit B.Struct extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit B.Struct`1<T> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit B.Struct`2<T, U> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit B.Struct`3<T, U, V> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit B.Struct`4<T, U, V, W> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public auto ansi beforefieldinit B.Class extends [System.Runtime]System.Object { .method public hidebysig static native int GetFunctionPointer () cil managed { ldftn int32 B.Class::GetField(valuetype B.Struct) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig static int32 GetField (valuetype B.Struct s) cil managed { ldarg.0 ldfld int32 B.Struct::Field ret } .method public hidebysig static native int GetFunctionPointerGeneric () cil managed { ldftn int32 B.Class::GetFieldGeneric<object>(valuetype B.Struct`1<!!0>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig static int32 GetFieldGeneric<T> (valuetype B.Struct`1<!!T> s) cil managed { ldarg.0 ldfld int32 valuetype B.Struct`1<!!T>::Field ret } .method public hidebysig static native int GetFunctionPointer<T> () cil managed { ldftn int32 B.Class::GetFieldGeneric<!!T>(valuetype B.Struct`2<!!T, !!T>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig static int32 GetFieldGeneric<T> (valuetype B.Struct`2<!!T, !!T> s) cil managed { ldarg.0 ldfld int32 valuetype B.Struct`2<!!T, !!T>::Field ret } .method public hidebysig static native int GetFunctionPointerGeneric ( object inst ) cil managed { ldftn instance int32 B.Class::GetFieldGeneric<object>(valuetype B.Struct`3<!!0, !!0, !!0>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig newslot virtual instance int32 GetFieldGeneric<T> (valuetype B.Struct`3<!!T, !!T, !!T> s) cil managed { ldarg.1 ldfld int32 valuetype B.Struct`3<!!T, !!T, !!T>::Field ret } .method public hidebysig static native int GetFunctionPointer<T> ( object inst ) cil managed { ldftn instance int32 B.Class::GetFieldGeneric<!!T>(valuetype B.Struct`4<!!T, !!T, !!T, !!T>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig newslot virtual instance int32 GetFieldGeneric<T> (valuetype B.Struct`4<!!T, !!T, !!T, !!T> s) cil managed { ldarg.1 ldfld int32 valuetype B.Struct`4<!!T, !!T, !!T, !!T>::Field ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [System.Runtime]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit B.Derived extends B.Class { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void B.Class::.ctor() ret } } // // Used for ldvirtftn // .class public sequential ansi sealed beforefieldinit C.Struct extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit C.Struct`1<T> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit C.Struct`2<T, U> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public auto ansi beforefieldinit C.Class extends [System.Runtime]System.Object { .method public hidebysig static native int GetFunctionPointer ( object inst ) cil managed { ldarg.0 ldvirtftn instance int32 C.Class::GetField(valuetype C.Struct) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig newslot virtual instance int32 GetField (valuetype C.Struct s) cil managed { newobj instance void [System.Runtime]System.NotImplementedException::.ctor() throw } .method public hidebysig static native int GetFunctionPointerGeneric ( object inst ) cil managed { ldarg.0 ldvirtftn instance int32 C.Class::GetFieldGeneric<object>(valuetype C.Struct`1<!!0>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig newslot virtual instance int32 GetFieldGeneric<T> (valuetype C.Struct`1<!!T> s) cil managed { newobj instance void [System.Runtime]System.NotImplementedException::.ctor() throw } .method public hidebysig static native int GetFunctionPointer<T> ( object inst ) cil managed { ldarg.0 ldvirtftn instance int32 C.Class::GetFieldGeneric<!!T>(valuetype C.Struct`2<!!T, !!T>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig newslot virtual instance int32 GetFieldGeneric<T> (valuetype C.Struct`2<!!T, !!T> s) cil managed { newobj instance void [System.Runtime]System.NotImplementedException::.ctor() throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [System.Runtime]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit C.Derived extends C.Class { .method public hidebysig virtual instance int32 GetField (valuetype C.Struct s) cil managed { ldarg.1 ldfld int32 C.Struct::Field ret } .method public hidebysig virtual instance int32 GetFieldGeneric<T> (valuetype C.Struct`1<!!T> s) cil managed { ldarg.1 ldfld int32 valuetype C.Struct`1<!!T>::Field ret } .method public hidebysig virtual instance int32 GetFieldGeneric<T> (valuetype C.Struct`2<!!T, !!T> s) cil managed { ldarg.1 ldfld int32 valuetype C.Struct`2<!!T, !!T>::Field ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void C.Class::.ctor() ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern System.Runtime { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) } .assembly punninglib { } .class public sequential ansi sealed beforefieldinit Caller.Struct extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit Caller.Struct`1<T> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public auto ansi abstract sealed beforefieldinit Caller.Class extends [System.Runtime]System.Object { .method public hidebysig static int32 CallGetField ( valuetype Caller.Struct s, native int callbackRaw, object inst ) cil managed { ldarg.2 ldnull ceq brfalse.s FALSE TRUE: nop ldarg.0 ldarg.1 calli int32(valuetype Caller.Struct) br.s DONE FALSE: nop ldarg.2 ldarg.0 ldarg.1 calli instance int32(valuetype Caller.Struct) br.s DONE DONE: ret } .method public hidebysig static int32 CallGetField<T> ( valuetype Caller.Struct`1<!!T> s, native int callbackRaw, object inst ) cil managed { ldarg.2 ldnull ceq brfalse.s FALSE TRUE: nop ldarg.0 ldarg.1 calli int32(valuetype Caller.Struct`1<!!T>) br.s DONE FALSE: nop ldarg.2 ldarg.0 ldarg.1 calli instance int32(valuetype Caller.Struct`1<!!T>) br.s DONE DONE: ret } } // // Used for GetFunctionPointer() // .class public sequential ansi sealed beforefieldinit A.Struct extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit A.Struct`1<T> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public auto ansi beforefieldinit A.Class extends [System.Runtime]System.Object { .method public hidebysig static int32 GetField (valuetype A.Struct s) cil managed { ldarg.0 ldfld int32 A.Struct::Field ret } .method public hidebysig static int32 GetFieldGeneric<T> (valuetype A.Struct`1<!!T> s) cil managed { ldarg.0 ldfld int32 valuetype A.Struct`1<!!T>::Field ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [System.Runtime]System.Object::.ctor() ret } } // // Used for ldftn // .class public sequential ansi sealed beforefieldinit B.Struct extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit B.Struct`1<T> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit B.Struct`2<T, U> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit B.Struct`3<T, U, V> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit B.Struct`4<T, U, V, W> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public auto ansi beforefieldinit B.Class extends [System.Runtime]System.Object { .method public hidebysig static native int GetFunctionPointer () cil managed { ldftn int32 B.Class::GetField(valuetype B.Struct) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig static int32 GetField (valuetype B.Struct s) cil managed { ldarg.0 ldfld int32 B.Struct::Field ret } .method public hidebysig static native int GetFunctionPointerGeneric () cil managed { ldftn int32 B.Class::GetFieldGeneric<object>(valuetype B.Struct`1<!!0>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig static int32 GetFieldGeneric<T> (valuetype B.Struct`1<!!T> s) cil managed { ldarg.0 ldfld int32 valuetype B.Struct`1<!!T>::Field ret } .method public hidebysig static native int GetFunctionPointer<T> () cil managed { ldftn int32 B.Class::GetFieldGeneric<!!T>(valuetype B.Struct`2<!!T, !!T>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig static int32 GetFieldGeneric<T> (valuetype B.Struct`2<!!T, !!T> s) cil managed { ldarg.0 ldfld int32 valuetype B.Struct`2<!!T, !!T>::Field ret } .method public hidebysig static native int GetFunctionPointerGeneric ( object inst ) cil managed { ldftn instance int32 B.Class::GetFieldGeneric<object>(valuetype B.Struct`3<!!0, !!0, !!0>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig newslot virtual instance int32 GetFieldGeneric<T> (valuetype B.Struct`3<!!T, !!T, !!T> s) cil managed { ldarg.1 ldfld int32 valuetype B.Struct`3<!!T, !!T, !!T>::Field ret } .method public hidebysig static native int GetFunctionPointer<T> ( object inst ) cil managed { ldftn instance int32 B.Class::GetFieldGeneric<!!T>(valuetype B.Struct`4<!!T, !!T, !!T, !!T>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig newslot virtual instance int32 GetFieldGeneric<T> (valuetype B.Struct`4<!!T, !!T, !!T, !!T> s) cil managed { ldarg.1 ldfld int32 valuetype B.Struct`4<!!T, !!T, !!T, !!T>::Field ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [System.Runtime]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit B.Derived extends B.Class { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void B.Class::.ctor() ret } } // // Used for ldvirtftn // .class public sequential ansi sealed beforefieldinit C.Struct extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit C.Struct`1<T> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public sequential ansi sealed beforefieldinit C.Struct`2<T, U> extends [System.Runtime]System.ValueType { .field public int32 Field } .class public auto ansi beforefieldinit C.Class extends [System.Runtime]System.Object { .method public hidebysig static native int GetFunctionPointer ( object inst ) cil managed { ldarg.0 ldvirtftn instance int32 C.Class::GetField(valuetype C.Struct) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig newslot virtual instance int32 GetField (valuetype C.Struct s) cil managed { newobj instance void [System.Runtime]System.NotImplementedException::.ctor() throw } .method public hidebysig static native int GetFunctionPointerGeneric ( object inst ) cil managed { ldarg.0 ldvirtftn instance int32 C.Class::GetFieldGeneric<object>(valuetype C.Struct`1<!!0>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig newslot virtual instance int32 GetFieldGeneric<T> (valuetype C.Struct`1<!!T> s) cil managed { newobj instance void [System.Runtime]System.NotImplementedException::.ctor() throw } .method public hidebysig static native int GetFunctionPointer<T> ( object inst ) cil managed { ldarg.0 ldvirtftn instance int32 C.Class::GetFieldGeneric<!!T>(valuetype C.Struct`2<!!T, !!T>) call native int [System.Runtime]System.IntPtr::op_Explicit(void*) ret } .method public hidebysig newslot virtual instance int32 GetFieldGeneric<T> (valuetype C.Struct`2<!!T, !!T> s) cil managed { newobj instance void [System.Runtime]System.NotImplementedException::.ctor() throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [System.Runtime]System.Object::.ctor() ret } } .class public auto ansi beforefieldinit C.Derived extends C.Class { .method public hidebysig virtual instance int32 GetField (valuetype C.Struct s) cil managed { ldarg.1 ldfld int32 C.Struct::Field ret } .method public hidebysig virtual instance int32 GetFieldGeneric<T> (valuetype C.Struct`1<!!T> s) cil managed { ldarg.1 ldfld int32 valuetype C.Struct`1<!!T>::Field ret } .method public hidebysig virtual instance int32 GetFieldGeneric<T> (valuetype C.Struct`2<!!T, !!T> s) cil managed { ldarg.1 ldfld int32 valuetype C.Struct`2<!!T, !!T>::Field ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void C.Class::.ctor() ret } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/CodeGenBringUpTests/Rotate_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Rotate.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Rotate.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Runtime.Serialization.Formatters/tests/BinaryFormatterEventSourceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics.Tracing; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using Xunit; namespace System.Runtime.Serialization.Formatters.Tests { [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))] public static class BinaryFormatterEventSourceTests { private const string BinaryFormatterEventSourceName = "System.Runtime.Serialization.Formatters.Binary.BinaryFormatterEventSource"; [Fact] public static void RecordsSerialization() { using LoggingEventListener listener = new LoggingEventListener(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(Stream.Null, CreatePerson()); string[] capturedLog = listener.CaptureLog(); string[] expected = new string[] { "SerializationStart [Start, 00000001]: <no payload>", "SerializingObject [Info, 00000001]: " + typeof(Person).AssemblyQualifiedName, "SerializingObject [Info, 00000001]: " + typeof(Address).AssemblyQualifiedName, "SerializationStop [Stop, 00000001]: <no payload>", }; Assert.Equal(expected, capturedLog); } [Fact] public static void RecordsDeserialization() { MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, CreatePerson()); ms.Position = 0; using LoggingEventListener listener = new LoggingEventListener(); formatter.Deserialize(ms); string[] capturedLog = listener.CaptureLog(); string[] expected = new string[] { "DeserializationStart [Start, 00000002]: <no payload>", "DeserializingObject [Info, 00000002]: " + typeof(Person).AssemblyQualifiedName, "DeserializingObject [Info, 00000002]: " + typeof(Address).AssemblyQualifiedName, "DeserializationStop [Stop, 00000002]: <no payload>", }; Assert.Equal(expected, capturedLog); } [Fact] public static void RecordsNestedSerializationCalls() { // First, serialization using LoggingEventListener listener = new LoggingEventListener(); MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, new ClassWithNestedDeserialization()); string[] capturedLog = listener.CaptureLog(); ms.Position = 0; string[] expected = new string[] { "SerializationStart [Start, 00000001]: <no payload>", "SerializingObject [Info, 00000001]: " + typeof(ClassWithNestedDeserialization).AssemblyQualifiedName, "SerializationStart [Start, 00000001]: <no payload>", "SerializingObject [Info, 00000001]: " + typeof(Address).AssemblyQualifiedName, "SerializationStop [Stop, 00000001]: <no payload>", "SerializationStop [Stop, 00000001]: <no payload>", }; Assert.Equal(expected, capturedLog); listener.ClearLog(); // Then, deserialization ms.Position = 0; formatter.Deserialize(ms); capturedLog = listener.CaptureLog(); expected = new string[] { "DeserializationStart [Start, 00000002]: <no payload>", "DeserializingObject [Info, 00000002]: " + typeof(ClassWithNestedDeserialization).AssemblyQualifiedName, "DeserializationStart [Start, 00000002]: <no payload>", "DeserializingObject [Info, 00000002]: " + typeof(Address).AssemblyQualifiedName, "DeserializationStop [Stop, 00000002]: <no payload>", "DeserializationStop [Stop, 00000002]: <no payload>", }; Assert.Equal(expected, capturedLog); } private static Person CreatePerson() { return new Person() { Name = "Some Chap", HomeAddress = new Address() { Street = "123 Anywhere Ln", City = "Anywhere ST 00000 United States" } }; } private sealed class LoggingEventListener : EventListener { private readonly Thread _activeThread = Thread.CurrentThread; private readonly List<string> _log = new List<string>(); private void AddToLog(FormattableString message) { _log.Add(FormattableString.Invariant(message)); } // Captures the current log public string[] CaptureLog() { return _log.ToArray(); } public void ClearLog() { _log.Clear(); } protected override void OnEventSourceCreated(EventSource eventSource) { if (eventSource.Name == BinaryFormatterEventSourceName) { EnableEvents(eventSource, EventLevel.Verbose); } base.OnEventSourceCreated(eventSource); } protected override void OnEventWritten(EventWrittenEventArgs eventData) { // The test project is parallelized. We want to filter to only events that fired // on the current thread, otherwise we could throw off the test results. if (Thread.CurrentThread != _activeThread) { return; } AddToLog($"{eventData.EventName} [{eventData.Opcode}, {(int)eventData.Keywords & int.MaxValue:X8}]: {ParsePayload(eventData.Payload)}"); base.OnEventWritten(eventData); } private static string ParsePayload(IReadOnlyCollection<object> collection) { if (collection?.Count > 0) { return string.Join("; ", collection.Select(o => o?.ToString() ?? "<null>")); } else { return "<no payload>"; } } } [Serializable] private class Person { public string Name { get; set; } public Address HomeAddress { get; set; } } [Serializable] private class Address { public string Street { get; set; } public string City { get; set; } } [Serializable] public class ClassWithNestedDeserialization : ISerializable { public ClassWithNestedDeserialization() { } protected ClassWithNestedDeserialization(SerializationInfo info, StreamingContext context) { byte[] serializedData = (byte[])info.GetValue("SomeField", typeof(byte[])); MemoryStream ms = new MemoryStream(serializedData); BinaryFormatter formatter = new BinaryFormatter(); formatter.Deserialize(ms); // should deserialize an 'Address' instance } public void GetObjectData(SerializationInfo info, StreamingContext context) { MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, new Address()); info.AddValue("SomeField", ms.ToArray()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics.Tracing; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using Xunit; namespace System.Runtime.Serialization.Formatters.Tests { [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))] public static class BinaryFormatterEventSourceTests { private const string BinaryFormatterEventSourceName = "System.Runtime.Serialization.Formatters.Binary.BinaryFormatterEventSource"; [Fact] public static void RecordsSerialization() { using LoggingEventListener listener = new LoggingEventListener(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(Stream.Null, CreatePerson()); string[] capturedLog = listener.CaptureLog(); string[] expected = new string[] { "SerializationStart [Start, 00000001]: <no payload>", "SerializingObject [Info, 00000001]: " + typeof(Person).AssemblyQualifiedName, "SerializingObject [Info, 00000001]: " + typeof(Address).AssemblyQualifiedName, "SerializationStop [Stop, 00000001]: <no payload>", }; Assert.Equal(expected, capturedLog); } [Fact] public static void RecordsDeserialization() { MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, CreatePerson()); ms.Position = 0; using LoggingEventListener listener = new LoggingEventListener(); formatter.Deserialize(ms); string[] capturedLog = listener.CaptureLog(); string[] expected = new string[] { "DeserializationStart [Start, 00000002]: <no payload>", "DeserializingObject [Info, 00000002]: " + typeof(Person).AssemblyQualifiedName, "DeserializingObject [Info, 00000002]: " + typeof(Address).AssemblyQualifiedName, "DeserializationStop [Stop, 00000002]: <no payload>", }; Assert.Equal(expected, capturedLog); } [Fact] public static void RecordsNestedSerializationCalls() { // First, serialization using LoggingEventListener listener = new LoggingEventListener(); MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, new ClassWithNestedDeserialization()); string[] capturedLog = listener.CaptureLog(); ms.Position = 0; string[] expected = new string[] { "SerializationStart [Start, 00000001]: <no payload>", "SerializingObject [Info, 00000001]: " + typeof(ClassWithNestedDeserialization).AssemblyQualifiedName, "SerializationStart [Start, 00000001]: <no payload>", "SerializingObject [Info, 00000001]: " + typeof(Address).AssemblyQualifiedName, "SerializationStop [Stop, 00000001]: <no payload>", "SerializationStop [Stop, 00000001]: <no payload>", }; Assert.Equal(expected, capturedLog); listener.ClearLog(); // Then, deserialization ms.Position = 0; formatter.Deserialize(ms); capturedLog = listener.CaptureLog(); expected = new string[] { "DeserializationStart [Start, 00000002]: <no payload>", "DeserializingObject [Info, 00000002]: " + typeof(ClassWithNestedDeserialization).AssemblyQualifiedName, "DeserializationStart [Start, 00000002]: <no payload>", "DeserializingObject [Info, 00000002]: " + typeof(Address).AssemblyQualifiedName, "DeserializationStop [Stop, 00000002]: <no payload>", "DeserializationStop [Stop, 00000002]: <no payload>", }; Assert.Equal(expected, capturedLog); } private static Person CreatePerson() { return new Person() { Name = "Some Chap", HomeAddress = new Address() { Street = "123 Anywhere Ln", City = "Anywhere ST 00000 United States" } }; } private sealed class LoggingEventListener : EventListener { private readonly Thread _activeThread = Thread.CurrentThread; private readonly List<string> _log = new List<string>(); private void AddToLog(FormattableString message) { _log.Add(FormattableString.Invariant(message)); } // Captures the current log public string[] CaptureLog() { return _log.ToArray(); } public void ClearLog() { _log.Clear(); } protected override void OnEventSourceCreated(EventSource eventSource) { if (eventSource.Name == BinaryFormatterEventSourceName) { EnableEvents(eventSource, EventLevel.Verbose); } base.OnEventSourceCreated(eventSource); } protected override void OnEventWritten(EventWrittenEventArgs eventData) { // The test project is parallelized. We want to filter to only events that fired // on the current thread, otherwise we could throw off the test results. if (Thread.CurrentThread != _activeThread) { return; } AddToLog($"{eventData.EventName} [{eventData.Opcode}, {(int)eventData.Keywords & int.MaxValue:X8}]: {ParsePayload(eventData.Payload)}"); base.OnEventWritten(eventData); } private static string ParsePayload(IReadOnlyCollection<object> collection) { if (collection?.Count > 0) { return string.Join("; ", collection.Select(o => o?.ToString() ?? "<null>")); } else { return "<no payload>"; } } } [Serializable] private class Person { public string Name { get; set; } public Address HomeAddress { get; set; } } [Serializable] private class Address { public string Street { get; set; } public string City { get; set; } } [Serializable] public class ClassWithNestedDeserialization : ISerializable { public ClassWithNestedDeserialization() { } protected ClassWithNestedDeserialization(SerializationInfo info, StreamingContext context) { byte[] serializedData = (byte[])info.GetValue("SomeField", typeof(byte[])); MemoryStream ms = new MemoryStream(serializedData); BinaryFormatter formatter = new BinaryFormatter(); formatter.Deserialize(ms); // should deserialize an 'Address' instance } public void GetObjectData(SerializationInfo info, StreamingContext context) { MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, new Address()); info.AddValue("SomeField", ms.ToArray()); } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/mono/mono/tests/bug-60843.cs
using System; using System.Runtime.CompilerServices; class A : Attribute { public object X; public static void Main() { var x = (C<int>.E)AttributeTest(typeof(C<>.E)); Assert(C<int>.E.V == x); var y = (C<int>.E2[])AttributeTest(typeof(C<>.E2)); Assert(y.Length == 2); Assert(y[0] == C<int>.E2.A); Assert(y[1] == C<int>.E2.B); } public static object AttributeTest (Type t) { var cas = t.GetCustomAttributes(false); Assert(cas.Length == 1); Assert(cas[0] is A); var a = (A)cas[0]; return a.X; } private static int AssertCount = 0; public static void Assert ( bool b, [CallerFilePath] string sourceFile = null, [CallerLineNumber] int lineNumber = 0 ) { AssertCount++; if (!b) { Console.Error.WriteLine($"Assert failed at {sourceFile}:{lineNumber}"); Environment.Exit(AssertCount); } } } public class C<T> { [A(X = C<int>.E.V)] public enum E { V } [A(X = new [] { C<int>.E2.A, C<int>.E2.B })] public enum E2 { A, B } }
using System; using System.Runtime.CompilerServices; class A : Attribute { public object X; public static void Main() { var x = (C<int>.E)AttributeTest(typeof(C<>.E)); Assert(C<int>.E.V == x); var y = (C<int>.E2[])AttributeTest(typeof(C<>.E2)); Assert(y.Length == 2); Assert(y[0] == C<int>.E2.A); Assert(y[1] == C<int>.E2.B); } public static object AttributeTest (Type t) { var cas = t.GetCustomAttributes(false); Assert(cas.Length == 1); Assert(cas[0] is A); var a = (A)cas[0]; return a.X; } private static int AssertCount = 0; public static void Assert ( bool b, [CallerFilePath] string sourceFile = null, [CallerLineNumber] int lineNumber = 0 ) { AssertCount++; if (!b) { Console.Error.WriteLine($"Assert failed at {sourceFile}:{lineNumber}"); Environment.Exit(AssertCount); } } } public class C<T> { [A(X = C<int>.E.V)] public enum E { V } [A(X = new [] { C<int>.E2.A, C<int>.E2.B })] public enum E2 { A, B } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexFindOptimizations.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { /// <summary>Contains state and provides operations related to finding the next location a match could possibly begin.</summary> internal sealed class RegexFindOptimizations { /// <summary>True if the input should be processed right-to-left rather than left-to-right.</summary> private readonly bool _rightToLeft; /// <summary>Provides the ToLower routine for lowercasing characters.</summary> private readonly TextInfo _textInfo; /// <summary>Lookup table used for optimizing ASCII when doing set queries.</summary> private readonly uint[]?[]? _asciiLookups; public RegexFindOptimizations(RegexNode root, RegexOptions options, CultureInfo culture) { _rightToLeft = (options & RegexOptions.RightToLeft) != 0; _textInfo = culture.TextInfo; MinRequiredLength = root.ComputeMinLength(); // Compute any anchor starting the expression. If there is one, we won't need to search for anything, // as we can just match at that single location. LeadingAnchor = RegexPrefixAnalyzer.FindLeadingAnchor(root); if (_rightToLeft && LeadingAnchor == RegexNodeKind.Bol) { // Filter out Bol for RightToLeft, as we don't currently optimize for it. LeadingAnchor = RegexNodeKind.Unknown; } if (LeadingAnchor is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.EndZ or RegexNodeKind.End) { FindMode = (LeadingAnchor, _rightToLeft) switch { (RegexNodeKind.Beginning, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning, (RegexNodeKind.Beginning, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning, (RegexNodeKind.Start, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start, (RegexNodeKind.Start, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start, (RegexNodeKind.End, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End, (RegexNodeKind.End, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End, (_, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ, (_, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ, }; return; } // Compute any anchor trailing the expression. If there is one, and we can also compute a fixed length // for the whole expression, we can use that to quickly jump to the right location in the input. if (!_rightToLeft) // haven't added FindNextStartingPositionMode support for RTL { bool triedToComputeMaxLength = false; TrailingAnchor = RegexPrefixAnalyzer.FindTrailingAnchor(root); if (TrailingAnchor is RegexNodeKind.End or RegexNodeKind.EndZ) { triedToComputeMaxLength = true; if (root.ComputeMaxLength() is int maxLength) { Debug.Assert(maxLength >= MinRequiredLength, $"{maxLength} should have been greater than {MinRequiredLength} minimum"); MaxPossibleLength = maxLength; if (MinRequiredLength == maxLength) { FindMode = TrailingAnchor == RegexNodeKind.End ? FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End : FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ; return; } } } if ((options & RegexOptions.NonBacktracking) != 0 && !triedToComputeMaxLength) { // NonBacktracking also benefits from knowing whether the pattern is a fixed length, as it can use that // knowledge to avoid multiple match phases in some situations. MaxPossibleLength = root.ComputeMaxLength(); } } // If there's a leading case-sensitive substring, just use IndexOf and inherit all of its optimizations. string caseSensitivePrefix = RegexPrefixAnalyzer.FindCaseSensitivePrefix(root); if (caseSensitivePrefix.Length > 1) { LeadingCaseSensitivePrefix = caseSensitivePrefix; FindMode = _rightToLeft ? FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive : FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive; return; } // At this point there are no fast-searchable anchors or case-sensitive prefixes. We can now analyze the // pattern for sets and then use any found sets to determine what kind of search to perform. // If we're compiling, then the compilation process already handles sets that reduce to a single literal, // so we can simplify and just always go for the sets. bool dfa = (options & RegexOptions.NonBacktracking) != 0; bool compiled = (options & RegexOptions.Compiled) != 0 && !dfa; // for now, we never generate code for NonBacktracking, so treat it as non-compiled bool interpreter = !compiled && !dfa; // For interpreter, we want to employ optimizations, but we don't want to make construction significantly // more expensive; someone who wants to pay to do more work can specify Compiled. So for the interpreter // we focus only on creating a set for the first character. Same for right-to-left, which is used very // rarely and thus we don't need to invest in special-casing it. if (_rightToLeft) { // Determine a set for anything that can possibly start the expression. if (RegexPrefixAnalyzer.FindFirstCharClass(root, culture) is (string CharClass, bool CaseInsensitive) set) { // See if the set is limited to holding only a few characters. Span<char> scratch = stackalloc char[5]; // max optimized by IndexOfAny today int scratchCount; char[]? chars = null; if (!RegexCharClass.IsNegated(set.CharClass) && (scratchCount = RegexCharClass.GetSetChars(set.CharClass, scratch)) > 0) { chars = scratch.Slice(0, scratchCount).ToArray(); } if (!compiled && chars is { Length: 1 }) { // The set contains one and only one character, meaning every match starts // with the same literal value (potentially case-insensitive). Search for that. FixedDistanceLiteral = (chars[0], 0); FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive; } else { // The set may match multiple characters. Search for that. FixedDistanceSets = new() { (chars, set.CharClass, 0, set.CaseInsensitive) }; FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive; _asciiLookups = new uint[1][]; } } return; } // We're now left-to-right only and looking for sets. // As a backup, see if we can find a literal after a leading atomic loop. That might be better than whatever sets we find, so // we want to know whether we have one in our pocket before deciding whether to use a leading set. (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? literalAfterLoop = RegexPrefixAnalyzer.FindLiteralFollowingLeadingLoop(root); // Build up a list of all of the sets that are a fixed distance from the start of the expression. List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? fixedDistanceSets = RegexPrefixAnalyzer.FindFixedDistanceSets(root, culture, thorough: !interpreter); Debug.Assert(fixedDistanceSets is null || fixedDistanceSets.Count != 0); // If we got such sets, we'll likely use them. However, if the best of them is something that doesn't support a vectorized // search and we did successfully find a literal after an atomic loop we could search instead, we prefer the vectorizable search. if (fixedDistanceSets is not null && (fixedDistanceSets[0].Chars is not null || literalAfterLoop is null)) { // Determine whether to do searching based on one or more sets or on a single literal. Compiled engines // don't need to special-case literals as they already do codegen to create the optimal lookup based on // the set's characteristics. if (!compiled && fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Chars is { Length: 1 }) { FixedDistanceLiteral = (fixedDistanceSets[0].Chars![0], fixedDistanceSets[0].Distance); FindMode = fixedDistanceSets[0].CaseInsensitive ? FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive : FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive; } else { // Limit how many sets we use to avoid doing lots of unnecessary work. The list was already // sorted from best to worst, so just keep the first ones up to our limit. const int MaxSetsToUse = 3; // arbitrary tuned limit if (fixedDistanceSets.Count > MaxSetsToUse) { fixedDistanceSets.RemoveRange(MaxSetsToUse, fixedDistanceSets.Count - MaxSetsToUse); } // Store the sets, and compute which mode to use. FixedDistanceSets = fixedDistanceSets; FindMode = (fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Distance == 0, fixedDistanceSets[0].CaseInsensitive) switch { (true, true) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive, (true, false) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive, (false, true) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive, (false, false) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive, }; _asciiLookups = new uint[fixedDistanceSets.Count][]; } return; } // If we found a literal we can search for after a leading set loop, use it. if (literalAfterLoop is not null) { FindMode = FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive; LiteralAfterLoop = literalAfterLoop; _asciiLookups = new uint[1][]; return; } } /// <summary>Gets the selected mode for performing the next <see cref="TryFindNextStartingPosition"/> operation</summary> public FindNextStartingPositionMode FindMode { get; } = FindNextStartingPositionMode.NoSearch; /// <summary>Gets the leading anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind LeadingAnchor { get; } /// <summary>Gets the trailing anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind TrailingAnchor { get; } /// <summary>Gets the minimum required length an input need be to match the pattern.</summary> /// <remarks>0 is a valid minimum length. This value may also be the max (and hence fixed) length of the expression.</remarks> public int MinRequiredLength { get; } /// <summary>The maximum possible length an input could be to match the pattern.</summary> /// <remarks> /// This is currently only set when <see cref="TrailingAnchor"/> is found to be an end anchor. /// That can be expanded in the future as needed. /// </remarks> public int? MaxPossibleLength { get; } /// <summary>Gets the leading prefix. May be an empty string.</summary> public string LeadingCaseSensitivePrefix { get; } = string.Empty; /// <summary>When in fixed distance literal mode, gets the literal and how far it is from the start of the pattern.</summary> public (char Literal, int Distance) FixedDistanceLiteral { get; } /// <summary>When in fixed distance set mode, gets the set and how far it is from the start of the pattern.</summary> /// <remarks>The case-insensitivity of the 0th entry will always match the mode selected, but subsequent entries may not.</remarks> public List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? FixedDistanceSets { get; } /// <summary>When in literal after set loop node, gets the literal to search for and the RegexNode representing the leading loop.</summary> public (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? LiteralAfterLoop { get; } /// <summary>Try to advance to the next starting position that might be a location for a match.</summary> /// <param name="textSpan">The text to search.</param> /// <param name="pos">The position in <paramref name="textSpan"/>. This is updated with the found position.</param> /// <param name="beginning">The index in <paramref name="textSpan"/> to consider the beginning for beginning anchor purposes.</param> /// <param name="start">The index in <paramref name="textSpan"/> to consider the start for start anchor purposes.</param> /// <param name="end">The index in <paramref name="textSpan"/> to consider the non-inclusive end of the string.</param> /// <returns>true if a position to attempt a match was found; false if none was found.</returns> public bool TryFindNextStartingPosition(ReadOnlySpan<char> textSpan, ref int pos, int beginning, int start, int end) { // Return early if we know there's not enough input left to match. if (!_rightToLeft) { if (pos > end - MinRequiredLength) { pos = end; return false; } } else { if (pos - MinRequiredLength < beginning) { pos = beginning; return false; } } // Optimize the handling of a Beginning-Of-Line (BOL) anchor (only for left-to-right). BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. if (LeadingAnchor == RegexNodeKind.Bol) { // If we're not currently positioned at the beginning of a line (either // the beginning of the string or just after a line feed), find the next // newline and position just after it. Debug.Assert(!_rightToLeft); if (pos > beginning && textSpan[pos - 1] != '\n') { int newline = textSpan.Slice(pos).IndexOf('\n'); if (newline == -1 || newline + 1 + pos > end) { pos = end; return false; } pos = newline + 1 + pos; } } switch (FindMode) { // There's an anchor. For some, we can simply compare against the current position. // For others, we can jump to the relevant location. case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: if (pos > beginning) { pos = end; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: if (pos > start) { pos = end; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: if (pos < end - 1) { pos = end - 1; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: if (pos < end) { pos = end; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: if (pos > beginning) { pos = beginning; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: if (pos < start) { pos = beginning; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: if (pos < end - 1 || (pos == end - 1 && textSpan[pos] != '\n')) { pos = beginning; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: if (pos < end) { pos = beginning; return false; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: if (pos < end - MinRequiredLength - 1) { pos = end - MinRequiredLength - 1; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: if (pos < end - MinRequiredLength) { pos = end - MinRequiredLength; } return true; // There's a case-sensitive prefix. Search for it with ordinal IndexOf. case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: { int i = textSpan.Slice(pos, end - pos).IndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos += i; return true; } pos = end; return false; } case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: { int i = textSpan.Slice(beginning, pos - beginning).LastIndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos = beginning + i + LeadingCaseSensitivePrefix.Length; return true; } pos = beginning; return false; } // There's a literal at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive: { int i = textSpan.Slice(beginning, pos - beginning).LastIndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos = beginning + i + 1; return true; } pos = beginning; return false; } case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive: { char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(beginning, pos - beginning); for (int i = span.Length - 1; i >= 0; i--) { if (ti.ToLower(span[i]) == ch) { pos = beginning + i + 1; return true; } } pos = beginning; return false; } // There's a set at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: { (char[]? chars, string set, _, _) = FixedDistanceSets![0]; ReadOnlySpan<char> span = textSpan.Slice(pos, end - pos); if (chars is not null) { int i = span.IndexOfAny(chars); if (i >= 0) { pos += i; return true; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos += i; return true; } } } pos = end; return false; } case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos, end - pos); for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos += i; return true; } } pos = end; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; ReadOnlySpan<char> span = textSpan.Slice(beginning, pos - beginning); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos = beginning + i + 1; return true; } } pos = beginning; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(beginning, pos - beginning); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos = beginning + i + 1; return true; } } pos = beginning; return false; } // There's a literal at a fixed offset from the beginning of the pattern. Search for it. case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); int i = textSpan.Slice(pos + FixedDistanceLiteral.Distance, end - pos - FixedDistanceLiteral.Distance).IndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos += i; return true; } pos = end; return false; } case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos + FixedDistanceLiteral.Distance, end - pos - FixedDistanceLiteral.Distance); for (int i = 0; i < span.Length; i++) { if (ti.ToLower(span[i]) == ch) { pos += i; return true; } } pos = end; return false; } // There are one or more sets at fixed offsets from the start of the pattern. case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (char[]? primaryChars, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = end - Math.Max(1, MinRequiredLength); if (primaryChars is not null) { for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { int offset = inputPosition + primaryDistance; int index = textSpan.Slice(offset, end - offset).IndexOfAny(primaryChars); if (index < 0) { break; } index += offset; // The index here will be offset indexed due to the use of span, so we add offset to get // real position on the string. inputPosition = index - primaryDistance; if (inputPosition > endMinusRequiredLength) { break; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; char c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(c, primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } pos = end; return false; } case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (_, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = end - Math.Max(1, MinRequiredLength); TextInfo ti = _textInfo; ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(ti.ToLower(c), primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } pos = end; return false; } // There's a literal after a leading set loop. Find the literal, then walk backwards through the loop to find the starting position. case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: { Debug.Assert(LiteralAfterLoop is not null); (RegexNode loopNode, (char Char, string? String, char[]? Chars) literal) = LiteralAfterLoop.GetValueOrDefault(); Debug.Assert(loopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(loopNode.N == int.MaxValue); int startingPos = pos; while (true) { ReadOnlySpan<char> slice = textSpan.Slice(startingPos, end - startingPos); // Find the literal. If we can't find it, we're done searching. int i = literal.String is not null ? slice.IndexOf(literal.String.AsSpan()) : literal.Chars is not null ? slice.IndexOfAny(literal.Chars.AsSpan()) : slice.IndexOf(literal.Char); if (i < 0) { break; } // We found the literal. Walk backwards from it finding as many matches as we can against the loop. int prev = i; while ((uint)--prev < (uint)slice.Length && RegexCharClass.CharInClass(slice[prev], loopNode.Str!, ref _asciiLookups![0])) ; // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. if ((i - prev - 1) < loopNode.M) { startingPos += i + 1; continue; } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate literalPos as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. This might only be feasible for RegexCompiler // and the source generator after we refactor them to generate a single Scan method rather than separate // FindFirstChar / Go methods. pos = startingPos + prev + 1; return true; } pos = end; return false; } // Nothing special to look for. Just return true indicating this is a valid position to try to match. default: Debug.Assert(FindMode == FindNextStartingPositionMode.NoSearch); return true; } } } /// <summary>Mode to use for searching for the next location of a possible match.</summary> internal enum FindNextStartingPositionMode { /// <summary>A "beginning" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Beginning, /// <summary>A "start" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Start, /// <summary>An "endz" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_EndZ, /// <summary>An "end" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_End, /// <summary>A "beginning" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Beginning, /// <summary>A "start" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Start, /// <summary>An "endz" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_EndZ, /// <summary>An "end" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_End, /// <summary>An "end" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_End, /// <summary>An "endz" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_EndZ, /// <summary>A case-sensitive multi-character substring at the beginning of the pattern.</summary> LeadingPrefix_LeftToRight_CaseSensitive, /// <summary>A case-sensitive multi-character substring at the beginning of the right-to-left pattern.</summary> LeadingPrefix_RightToLeft_CaseSensitive, /// <summary>A case-sensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseSensitive, /// <summary>A case-insensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseInsensitive, /// <summary>A case-sensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseSensitive, /// <summary>A case-insensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseInsensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-sensitive.</summary> FixedSets_LeftToRight_CaseSensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-insensitive.</summary> FixedSets_LeftToRight_CaseInsensitive, /// <summary>A literal after a non-overlapping set loop at the start of the pattern. The literal is case-sensitive.</summary> LiteralAfterLoop_LeftToRight_CaseSensitive, /// <summary>Nothing to search for. Nop.</summary> NoSearch, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { /// <summary>Contains state and provides operations related to finding the next location a match could possibly begin.</summary> internal sealed class RegexFindOptimizations { /// <summary>True if the input should be processed right-to-left rather than left-to-right.</summary> private readonly bool _rightToLeft; /// <summary>Provides the ToLower routine for lowercasing characters.</summary> private readonly TextInfo _textInfo; /// <summary>Lookup table used for optimizing ASCII when doing set queries.</summary> private readonly uint[]?[]? _asciiLookups; public RegexFindOptimizations(RegexNode root, RegexOptions options, CultureInfo culture) { _rightToLeft = (options & RegexOptions.RightToLeft) != 0; _textInfo = culture.TextInfo; MinRequiredLength = root.ComputeMinLength(); // Compute any anchor starting the expression. If there is one, we won't need to search for anything, // as we can just match at that single location. LeadingAnchor = RegexPrefixAnalyzer.FindLeadingAnchor(root); if (_rightToLeft && LeadingAnchor == RegexNodeKind.Bol) { // Filter out Bol for RightToLeft, as we don't currently optimize for it. LeadingAnchor = RegexNodeKind.Unknown; } if (LeadingAnchor is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.EndZ or RegexNodeKind.End) { FindMode = (LeadingAnchor, _rightToLeft) switch { (RegexNodeKind.Beginning, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning, (RegexNodeKind.Beginning, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning, (RegexNodeKind.Start, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start, (RegexNodeKind.Start, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start, (RegexNodeKind.End, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End, (RegexNodeKind.End, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End, (_, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ, (_, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ, }; return; } // Compute any anchor trailing the expression. If there is one, and we can also compute a fixed length // for the whole expression, we can use that to quickly jump to the right location in the input. if (!_rightToLeft) // haven't added FindNextStartingPositionMode support for RTL { bool triedToComputeMaxLength = false; TrailingAnchor = RegexPrefixAnalyzer.FindTrailingAnchor(root); if (TrailingAnchor is RegexNodeKind.End or RegexNodeKind.EndZ) { triedToComputeMaxLength = true; if (root.ComputeMaxLength() is int maxLength) { Debug.Assert(maxLength >= MinRequiredLength, $"{maxLength} should have been greater than {MinRequiredLength} minimum"); MaxPossibleLength = maxLength; if (MinRequiredLength == maxLength) { FindMode = TrailingAnchor == RegexNodeKind.End ? FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End : FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ; return; } } } if ((options & RegexOptions.NonBacktracking) != 0 && !triedToComputeMaxLength) { // NonBacktracking also benefits from knowing whether the pattern is a fixed length, as it can use that // knowledge to avoid multiple match phases in some situations. MaxPossibleLength = root.ComputeMaxLength(); } } // If there's a leading case-sensitive substring, just use IndexOf and inherit all of its optimizations. string caseSensitivePrefix = RegexPrefixAnalyzer.FindCaseSensitivePrefix(root); if (caseSensitivePrefix.Length > 1) { LeadingCaseSensitivePrefix = caseSensitivePrefix; FindMode = _rightToLeft ? FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive : FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive; return; } // At this point there are no fast-searchable anchors or case-sensitive prefixes. We can now analyze the // pattern for sets and then use any found sets to determine what kind of search to perform. // If we're compiling, then the compilation process already handles sets that reduce to a single literal, // so we can simplify and just always go for the sets. bool dfa = (options & RegexOptions.NonBacktracking) != 0; bool compiled = (options & RegexOptions.Compiled) != 0 && !dfa; // for now, we never generate code for NonBacktracking, so treat it as non-compiled bool interpreter = !compiled && !dfa; // For interpreter, we want to employ optimizations, but we don't want to make construction significantly // more expensive; someone who wants to pay to do more work can specify Compiled. So for the interpreter // we focus only on creating a set for the first character. Same for right-to-left, which is used very // rarely and thus we don't need to invest in special-casing it. if (_rightToLeft) { // Determine a set for anything that can possibly start the expression. if (RegexPrefixAnalyzer.FindFirstCharClass(root, culture) is (string CharClass, bool CaseInsensitive) set) { // See if the set is limited to holding only a few characters. Span<char> scratch = stackalloc char[5]; // max optimized by IndexOfAny today int scratchCount; char[]? chars = null; if (!RegexCharClass.IsNegated(set.CharClass) && (scratchCount = RegexCharClass.GetSetChars(set.CharClass, scratch)) > 0) { chars = scratch.Slice(0, scratchCount).ToArray(); } if (!compiled && chars is { Length: 1 }) { // The set contains one and only one character, meaning every match starts // with the same literal value (potentially case-insensitive). Search for that. FixedDistanceLiteral = (chars[0], 0); FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive; } else { // The set may match multiple characters. Search for that. FixedDistanceSets = new() { (chars, set.CharClass, 0, set.CaseInsensitive) }; FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive; _asciiLookups = new uint[1][]; } } return; } // We're now left-to-right only and looking for sets. // As a backup, see if we can find a literal after a leading atomic loop. That might be better than whatever sets we find, so // we want to know whether we have one in our pocket before deciding whether to use a leading set. (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? literalAfterLoop = RegexPrefixAnalyzer.FindLiteralFollowingLeadingLoop(root); // Build up a list of all of the sets that are a fixed distance from the start of the expression. List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? fixedDistanceSets = RegexPrefixAnalyzer.FindFixedDistanceSets(root, culture, thorough: !interpreter); Debug.Assert(fixedDistanceSets is null || fixedDistanceSets.Count != 0); // If we got such sets, we'll likely use them. However, if the best of them is something that doesn't support a vectorized // search and we did successfully find a literal after an atomic loop we could search instead, we prefer the vectorizable search. if (fixedDistanceSets is not null && (fixedDistanceSets[0].Chars is not null || literalAfterLoop is null)) { // Determine whether to do searching based on one or more sets or on a single literal. Compiled engines // don't need to special-case literals as they already do codegen to create the optimal lookup based on // the set's characteristics. if (!compiled && fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Chars is { Length: 1 }) { FixedDistanceLiteral = (fixedDistanceSets[0].Chars![0], fixedDistanceSets[0].Distance); FindMode = fixedDistanceSets[0].CaseInsensitive ? FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive : FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive; } else { // Limit how many sets we use to avoid doing lots of unnecessary work. The list was already // sorted from best to worst, so just keep the first ones up to our limit. const int MaxSetsToUse = 3; // arbitrary tuned limit if (fixedDistanceSets.Count > MaxSetsToUse) { fixedDistanceSets.RemoveRange(MaxSetsToUse, fixedDistanceSets.Count - MaxSetsToUse); } // Store the sets, and compute which mode to use. FixedDistanceSets = fixedDistanceSets; FindMode = (fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Distance == 0, fixedDistanceSets[0].CaseInsensitive) switch { (true, true) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive, (true, false) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive, (false, true) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive, (false, false) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive, }; _asciiLookups = new uint[fixedDistanceSets.Count][]; } return; } // If we found a literal we can search for after a leading set loop, use it. if (literalAfterLoop is not null) { FindMode = FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive; LiteralAfterLoop = literalAfterLoop; _asciiLookups = new uint[1][]; return; } } /// <summary>Gets the selected mode for performing the next <see cref="TryFindNextStartingPosition"/> operation</summary> public FindNextStartingPositionMode FindMode { get; } = FindNextStartingPositionMode.NoSearch; /// <summary>Gets the leading anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind LeadingAnchor { get; } /// <summary>Gets the trailing anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind TrailingAnchor { get; } /// <summary>Gets the minimum required length an input need be to match the pattern.</summary> /// <remarks>0 is a valid minimum length. This value may also be the max (and hence fixed) length of the expression.</remarks> public int MinRequiredLength { get; } /// <summary>The maximum possible length an input could be to match the pattern.</summary> /// <remarks> /// This is currently only set when <see cref="TrailingAnchor"/> is found to be an end anchor. /// That can be expanded in the future as needed. /// </remarks> public int? MaxPossibleLength { get; } /// <summary>Gets the leading prefix. May be an empty string.</summary> public string LeadingCaseSensitivePrefix { get; } = string.Empty; /// <summary>When in fixed distance literal mode, gets the literal and how far it is from the start of the pattern.</summary> public (char Literal, int Distance) FixedDistanceLiteral { get; } /// <summary>When in fixed distance set mode, gets the set and how far it is from the start of the pattern.</summary> /// <remarks>The case-insensitivity of the 0th entry will always match the mode selected, but subsequent entries may not.</remarks> public List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? FixedDistanceSets { get; } /// <summary>When in literal after set loop node, gets the literal to search for and the RegexNode representing the leading loop.</summary> public (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? LiteralAfterLoop { get; } /// <summary>Try to advance to the next starting position that might be a location for a match.</summary> /// <param name="textSpan">The text to search.</param> /// <param name="pos">The position in <paramref name="textSpan"/>. This is updated with the found position.</param> /// <param name="start">The index in <paramref name="textSpan"/> to consider the start for start anchor purposes.</param> /// <returns>true if a position to attempt a match was found; false if none was found.</returns> public bool TryFindNextStartingPosition(ReadOnlySpan<char> textSpan, ref int pos, int start) { // Return early if we know there's not enough input left to match. if (!_rightToLeft) { if (pos > textSpan.Length - MinRequiredLength) { pos = textSpan.Length; return false; } } else { if (pos < MinRequiredLength) { pos = 0; return false; } } // Optimize the handling of a Beginning-Of-Line (BOL) anchor (only for left-to-right). BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. if (LeadingAnchor == RegexNodeKind.Bol) { // If we're not currently positioned at the beginning of a line (either // the beginning of the string or just after a line feed), find the next // newline and position just after it. Debug.Assert(!_rightToLeft); int posm1 = pos - 1; if ((uint)posm1 < (uint)textSpan.Length && textSpan[posm1] != '\n') { int newline = textSpan.Slice(pos).IndexOf('\n'); if ((uint)newline > textSpan.Length - 1 - pos) { pos = textSpan.Length; return false; } pos = newline + 1 + pos; } } switch (FindMode) { // There's an anchor. For some, we can simply compare against the current position. // For others, we can jump to the relevant location. case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: if (pos > 0) { pos = textSpan.Length; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: if (pos > start) { pos = textSpan.Length; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: if (pos < textSpan.Length - 1) { pos = textSpan.Length - 1; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: if (pos < textSpan.Length) { pos = textSpan.Length; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: if (pos > 0) { pos = 0; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: if (pos < start) { pos = 0; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: if (pos < textSpan.Length - 1 || ((uint)pos < (uint)textSpan.Length && textSpan[pos] != '\n')) { pos = 0; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: if (pos < textSpan.Length) { pos = 0; return false; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: if (pos < textSpan.Length - MinRequiredLength - 1) { pos = textSpan.Length - MinRequiredLength - 1; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: if (pos < textSpan.Length - MinRequiredLength) { pos = textSpan.Length - MinRequiredLength; } return true; // There's a case-sensitive prefix. Search for it with ordinal IndexOf. case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: { int i = textSpan.Slice(pos).IndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos += i; return true; } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: { int i = textSpan.Slice(0, pos).LastIndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos = i + LeadingCaseSensitivePrefix.Length; return true; } pos = 0; return false; } // There's a literal at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive: { int i = textSpan.Slice(0, pos).LastIndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos = i + 1; return true; } pos = 0; return false; } case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive: { char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (ti.ToLower(span[i]) == ch) { pos = i + 1; return true; } } pos = 0; return false; } // There's a set at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: { (char[]? chars, string set, _, _) = FixedDistanceSets![0]; ReadOnlySpan<char> span = textSpan.Slice(pos); if (chars is not null) { int i = span.IndexOfAny(chars); if (i >= 0) { pos += i; return true; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos += i; return true; } } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos); for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos += i; return true; } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos = i + 1; return true; } } pos = 0; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos = i + 1; return true; } } pos = 0; return false; } // There's a literal at a fixed offset from the beginning of the pattern. Search for it. case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); int i = textSpan.Slice(pos + FixedDistanceLiteral.Distance).IndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos += i; return true; } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos + FixedDistanceLiteral.Distance); for (int i = 0; i < span.Length; i++) { if (ti.ToLower(span[i]) == ch) { pos += i; return true; } } pos = textSpan.Length; return false; } // There are one or more sets at fixed offsets from the start of the pattern. case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (char[]? primaryChars, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = textSpan.Length - Math.Max(1, MinRequiredLength); if (primaryChars is not null) { for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { int offset = inputPosition + primaryDistance; int index = textSpan.Slice(offset).IndexOfAny(primaryChars); if (index < 0) { break; } index += offset; // The index here will be offset indexed due to the use of span, so we add offset to get // real position on the string. inputPosition = index - primaryDistance; if (inputPosition > endMinusRequiredLength) { break; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; char c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(c, primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (_, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = textSpan.Length - Math.Max(1, MinRequiredLength); TextInfo ti = _textInfo; ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(ti.ToLower(c), primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } pos = textSpan.Length; return false; } // There's a literal after a leading set loop. Find the literal, then walk backwards through the loop to find the starting position. case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: { Debug.Assert(LiteralAfterLoop is not null); (RegexNode loopNode, (char Char, string? String, char[]? Chars) literal) = LiteralAfterLoop.GetValueOrDefault(); Debug.Assert(loopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(loopNode.N == int.MaxValue); int startingPos = pos; while (true) { ReadOnlySpan<char> slice = textSpan.Slice(startingPos); // Find the literal. If we can't find it, we're done searching. int i = literal.String is not null ? slice.IndexOf(literal.String.AsSpan()) : literal.Chars is not null ? slice.IndexOfAny(literal.Chars.AsSpan()) : slice.IndexOf(literal.Char); if (i < 0) { break; } // We found the literal. Walk backwards from it finding as many matches as we can against the loop. int prev = i; while ((uint)--prev < (uint)slice.Length && RegexCharClass.CharInClass(slice[prev], loopNode.Str!, ref _asciiLookups![0])) ; // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. if ((i - prev - 1) < loopNode.M) { startingPos += i + 1; continue; } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate literalPos as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. This might only be feasible for RegexCompiler // and the source generator after we refactor them to generate a single Scan method rather than separate // FindFirstChar / Go methods. pos = startingPos + prev + 1; return true; } pos = textSpan.Length; return false; } // Nothing special to look for. Just return true indicating this is a valid position to try to match. default: Debug.Assert(FindMode == FindNextStartingPositionMode.NoSearch); return true; } } } /// <summary>Mode to use for searching for the next location of a possible match.</summary> internal enum FindNextStartingPositionMode { /// <summary>A "beginning" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Beginning, /// <summary>A "start" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Start, /// <summary>An "endz" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_EndZ, /// <summary>An "end" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_End, /// <summary>A "beginning" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Beginning, /// <summary>A "start" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Start, /// <summary>An "endz" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_EndZ, /// <summary>An "end" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_End, /// <summary>An "end" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_End, /// <summary>An "endz" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_EndZ, /// <summary>A case-sensitive multi-character substring at the beginning of the pattern.</summary> LeadingPrefix_LeftToRight_CaseSensitive, /// <summary>A case-sensitive multi-character substring at the beginning of the right-to-left pattern.</summary> LeadingPrefix_RightToLeft_CaseSensitive, /// <summary>A case-sensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseSensitive, /// <summary>A case-insensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseInsensitive, /// <summary>A case-sensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseSensitive, /// <summary>A case-insensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseInsensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-sensitive.</summary> FixedSets_LeftToRight_CaseSensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-insensitive.</summary> FixedSets_LeftToRight_CaseInsensitive, /// <summary>A literal after a non-overlapping set loop at the start of the pattern. The literal is case-sensitive.</summary> LiteralAfterLoop_LeftToRight_CaseSensitive, /// <summary>Nothing to search for. Nop.</summary> NoSearch, } }
1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexInterpreter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; namespace System.Text.RegularExpressions { /// <summary>A <see cref="RegexRunnerFactory"/> for creating <see cref="RegexInterpreter"/>s.</summary> internal sealed class RegexInterpreterFactory : RegexRunnerFactory { private readonly RegexInterpreterCode _code; public RegexInterpreterFactory(RegexTree tree, CultureInfo culture) => // Generate and store the RegexInterpretedCode for the RegexTree and the specified culture _code = RegexWriter.Write(tree, culture); protected internal override RegexRunner CreateInstance() => // Create a new interpreter instance. new RegexInterpreter(_code, RegexParser.GetTargetCulture(_code.Options)); } /// <summary>Executes a block of regular expression codes while consuming input.</summary> internal sealed class RegexInterpreter : RegexRunner { private const int LoopTimeoutCheckCount = 2048; // conservative value to provide reasonably-accurate timeout handling. private readonly RegexInterpreterCode _code; private readonly TextInfo _textInfo; private RegexOpcode _operator; private int _codepos; private bool _rightToLeft; private bool _caseInsensitive; public RegexInterpreter(RegexInterpreterCode code, CultureInfo culture) { Debug.Assert(code != null, "code must not be null."); Debug.Assert(culture != null, "culture must not be null."); _code = code; _textInfo = culture.TextInfo; } protected override void InitTrackCount() => runtrackcount = _code.TrackCount; private void Advance(int i) { _codepos += i + 1; SetOperator((RegexOpcode)_code.Codes[_codepos]); } private void Goto(int newpos) { // When branching backward, ensure storage. if (newpos < _codepos) { EnsureStorage(); } _codepos = newpos; SetOperator((RegexOpcode)_code.Codes[newpos]); } private void Trackto(int newpos) => runtrackpos = runtrack!.Length - newpos; private int Trackpos() => runtrack!.Length - runtrackpos; /// <summary>Push onto the backtracking stack.</summary> private void TrackPush() => runtrack![--runtrackpos] = _codepos; private void TrackPush(int i1) { int[] localruntrack = runtrack!; int localruntrackpos = runtrackpos; localruntrack[--localruntrackpos] = i1; localruntrack[--localruntrackpos] = _codepos; runtrackpos = localruntrackpos; } private void TrackPush(int i1, int i2) { int[] localruntrack = runtrack!; int localruntrackpos = runtrackpos; localruntrack[--localruntrackpos] = i1; localruntrack[--localruntrackpos] = i2; localruntrack[--localruntrackpos] = _codepos; runtrackpos = localruntrackpos; } private void TrackPush(int i1, int i2, int i3) { int[] localruntrack = runtrack!; int localruntrackpos = runtrackpos; localruntrack[--localruntrackpos] = i1; localruntrack[--localruntrackpos] = i2; localruntrack[--localruntrackpos] = i3; localruntrack[--localruntrackpos] = _codepos; runtrackpos = localruntrackpos; } private void TrackPush2(int i1) { int[] localruntrack = runtrack!; int localruntrackpos = runtrackpos; localruntrack[--localruntrackpos] = i1; localruntrack[--localruntrackpos] = -_codepos; runtrackpos = localruntrackpos; } private void TrackPush2(int i1, int i2) { int[] localruntrack = runtrack!; int localruntrackpos = runtrackpos; localruntrack[--localruntrackpos] = i1; localruntrack[--localruntrackpos] = i2; localruntrack[--localruntrackpos] = -_codepos; runtrackpos = localruntrackpos; } private void Backtrack() { int newpos = runtrack![runtrackpos]; runtrackpos++; #if DEBUG Debug.WriteLineIf(Regex.EnableDebugTracing, $" Backtracking{(newpos < 0 ? " (back2)" : "")} to code position {Math.Abs(newpos)}"); #endif int back = (int)RegexOpcode.Backtracking; if (newpos < 0) { newpos = -newpos; back = (int)RegexOpcode.BacktrackingSecond; } SetOperator((RegexOpcode)(_code.Codes[newpos] | back)); // When branching backward, ensure storage. if (newpos < _codepos) { EnsureStorage(); } _codepos = newpos; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SetOperator(RegexOpcode op) { _operator = op & ~(RegexOpcode.RightToLeft | RegexOpcode.CaseInsensitive); _caseInsensitive = (op & RegexOpcode.CaseInsensitive) != 0; _rightToLeft = (op & RegexOpcode.RightToLeft) != 0; } private void TrackPop() => runtrackpos++; /// <summary>Pop framesize items from the backtracking stack.</summary> private void TrackPop(int framesize) => runtrackpos += framesize; /// <summary>Peek at the item popped from the stack.</summary> /// <remarks> /// If you want to get and pop the top item from the stack, you do `TrackPop(); TrackPeek();`. /// </remarks> private int TrackPeek() => runtrack![runtrackpos - 1]; /// <summary>Get the ith element down on the backtracking stack.</summary> private int TrackPeek(int i) => runtrack![runtrackpos - i - 1]; /// <summary>Push onto the grouping stack.</summary> private void StackPush(int i1) => runstack![--runstackpos] = i1; private void StackPush(int i1, int i2) { int[] localrunstack = runstack!; int localrunstackpos = runstackpos; localrunstack[--localrunstackpos] = i1; localrunstack[--localrunstackpos] = i2; runstackpos = localrunstackpos; } private void StackPop() => runstackpos++; // pop framesize items from the grouping stack private void StackPop(int framesize) => runstackpos += framesize; /// <summary> /// Technically we are actually peeking at items already popped. So if you want to /// get and pop the top item from the stack, you do `StackPop(); StackPeek();`. /// </summary> private int StackPeek() => runstack![runstackpos - 1]; /// <summary>Get the ith element down on the grouping stack.</summary> private int StackPeek(int i) => runstack![runstackpos - i - 1]; private int Operand(int i) => _code.Codes[_codepos + i + 1]; private int Leftchars() => runtextpos - runtextbeg; private int Rightchars() => runtextend - runtextpos; private int Bump() => _rightToLeft ? -1 : 1; private int Forwardchars() => _rightToLeft ? runtextpos - runtextbeg : runtextend - runtextpos; private char Forwardcharnext(ReadOnlySpan<char> inputSpan) { int i = _rightToLeft ? --runtextpos : runtextpos++; char ch = inputSpan[i]; return _caseInsensitive ? _textInfo.ToLower(ch) : ch; } private bool MatchString(string str, ReadOnlySpan<char> inputSpan) { int c = str.Length; int pos; if (!_rightToLeft) { if (runtextend - runtextpos < c) { return false; } pos = runtextpos + c; } else { if (runtextpos - runtextbeg < c) { return false; } pos = runtextpos; } if (!_caseInsensitive) { while (c != 0) { if (str[--c] != inputSpan[--pos]) { return false; } } } else { TextInfo ti = _textInfo; while (c != 0) { if (str[--c] != ti.ToLower(inputSpan[--pos])) { return false; } } } if (!_rightToLeft) { pos += str.Length; } runtextpos = pos; return true; } private bool MatchRef(int index, int length, ReadOnlySpan<char> inputSpan) { int pos; if (!_rightToLeft) { if (runtextend - runtextpos < length) { return false; } pos = runtextpos + length; } else { if (runtextpos - runtextbeg < length) { return false; } pos = runtextpos; } int cmpos = index + length; int c = length; if (!_caseInsensitive) { while (c-- != 0) { if (inputSpan[--cmpos] != inputSpan[--pos]) { return false; } } } else { TextInfo ti = _textInfo; while (c-- != 0) { if (ti.ToLower(inputSpan[--cmpos]) != ti.ToLower(inputSpan[--pos])) { return false; } } } if (!_rightToLeft) { pos += length; } runtextpos = pos; return true; } private void Backwardnext() => runtextpos += _rightToLeft ? 1 : -1; protected internal override void Scan(ReadOnlySpan<char> text) { Debug.Assert(runregex is not null); Debug.Assert(runtrack is not null); Debug.Assert(runstack is not null); Debug.Assert(runcrawl is not null); // Configure the additional value to "bump" the position along each time we loop around // to call TryFindNextStartingPosition again, as well as the stopping position for the loop. We generally // bump by 1 and stop at textend, but if we're examining right-to-left, we instead bump // by -1 and stop at textbeg. int bump = 1, stoppos = text.Length; if (runregex.RightToLeft) { bump = -1; stoppos = 0; } while (_code.FindOptimizations.TryFindNextStartingPosition(text, ref runtextpos, runtextbeg, runtextstart, runtextend)) { CheckTimeout(); if (TryMatchAtCurrentPosition(text) || runtextpos == stoppos) { return; } // Reset state for another iteration. runtrackpos = runtrack.Length; runstackpos = runstack.Length; runcrawlpos = runcrawl.Length; runtextpos += bump; } } private bool TryMatchAtCurrentPosition(ReadOnlySpan<char> inputSpan) { SetOperator((RegexOpcode)_code.Codes[0]); _codepos = 0; int advance = -1; while (true) { if (advance >= 0) { // Single common Advance call to reduce method size; and single method inline point. // Details at https://github.com/dotnet/corefx/pull/25096. Advance(advance); advance = -1; } #if DEBUG if (Regex.EnableDebugTracing) { DebugTraceCurrentState(); } #endif CheckTimeout(); switch (_operator) { case RegexOpcode.Stop: return runmatch!.FoundMatch; case RegexOpcode.Nothing: break; case RegexOpcode.Goto: Goto(Operand(0)); continue; case RegexOpcode.TestBackreference: if (!IsMatched(Operand(0))) { break; } advance = 1; continue; case RegexOpcode.Lazybranch: TrackPush(runtextpos); advance = 1; continue; case RegexOpcode.Lazybranch | RegexOpcode.Backtracking: TrackPop(); runtextpos = TrackPeek(); Goto(Operand(0)); continue; case RegexOpcode.Setmark: StackPush(runtextpos); TrackPush(); advance = 0; continue; case RegexOpcode.Nullmark: StackPush(-1); TrackPush(); advance = 0; continue; case RegexOpcode.Setmark | RegexOpcode.Backtracking: case RegexOpcode.Nullmark | RegexOpcode.Backtracking: StackPop(); break; case RegexOpcode.Getmark: StackPop(); TrackPush(StackPeek()); runtextpos = StackPeek(); advance = 0; continue; case RegexOpcode.Getmark | RegexOpcode.Backtracking: TrackPop(); StackPush(TrackPeek()); break; case RegexOpcode.Capturemark: if (Operand(1) != -1 && !IsMatched(Operand(1))) { break; } StackPop(); if (Operand(1) != -1) { TransferCapture(Operand(0), Operand(1), StackPeek(), runtextpos); } else { Capture(Operand(0), StackPeek(), runtextpos); } TrackPush(StackPeek()); advance = 2; continue; case RegexOpcode.Capturemark | RegexOpcode.Backtracking: TrackPop(); StackPush(TrackPeek()); Uncapture(); if (Operand(0) != -1 && Operand(1) != -1) { Uncapture(); } break; case RegexOpcode.Branchmark: StackPop(); if (runtextpos != StackPeek()) { // Nonempty match -> loop now TrackPush(StackPeek(), runtextpos); // Save old mark, textpos StackPush(runtextpos); // Make new mark Goto(Operand(0)); // Loop } else { // Empty match -> straight now TrackPush2(StackPeek()); // Save old mark advance = 1; // Straight } continue; case RegexOpcode.Branchmark | RegexOpcode.Backtracking: TrackPop(2); StackPop(); runtextpos = TrackPeek(1); // Recall position TrackPush2(TrackPeek()); // Save old mark advance = 1; // Straight continue; case RegexOpcode.Branchmark | RegexOpcode.BacktrackingSecond: TrackPop(); StackPush(TrackPeek()); // Recall old mark break; // Backtrack case RegexOpcode.Lazybranchmark: // We hit this the first time through a lazy loop and after each // successful match of the inner expression. It simply continues // on and doesn't loop. StackPop(); { int oldMarkPos = StackPeek(); if (runtextpos != oldMarkPos) { // Nonempty match -> try to loop again by going to 'back' state if (oldMarkPos != -1) { TrackPush(oldMarkPos, runtextpos); // Save old mark, textpos } else { TrackPush(runtextpos, runtextpos); } } else { // The inner expression found an empty match, so we'll go directly to 'back2' if we // backtrack. In this case, we need to push something on the stack, since back2 pops. // However, in the case of ()+? or similar, this empty match may be legitimate, so push the text // position associated with that empty match. StackPush(oldMarkPos); TrackPush2(StackPeek()); // Save old mark } } advance = 1; continue; case RegexOpcode.Lazybranchmark | RegexOpcode.Backtracking: { // After the first time, Lazybranchmark | RegexOpcode.Back occurs // with each iteration of the loop, and therefore with every attempted // match of the inner expression. We'll try to match the inner expression, // then go back to Lazybranchmark if successful. If the inner expression // fails, we go to Lazybranchmark | RegexOpcode.Back2 TrackPop(2); int pos = TrackPeek(1); TrackPush2(TrackPeek()); // Save old mark StackPush(pos); // Make new mark runtextpos = pos; // Recall position Goto(Operand(0)); // Loop } continue; case RegexOpcode.Lazybranchmark | RegexOpcode.BacktrackingSecond: // The lazy loop has failed. We'll do a true backtrack and // start over before the lazy loop. StackPop(); TrackPop(); StackPush(TrackPeek()); // Recall old mark break; case RegexOpcode.Setcount: StackPush(runtextpos, Operand(0)); TrackPush(); advance = 1; continue; case RegexOpcode.Nullcount: StackPush(-1, Operand(0)); TrackPush(); advance = 1; continue; case RegexOpcode.Setcount | RegexOpcode.Backtracking: case RegexOpcode.Nullcount | RegexOpcode.Backtracking: case RegexOpcode.Setjump | RegexOpcode.Backtracking: StackPop(2); break; case RegexOpcode.Branchcount: // StackPush: // 0: Mark // 1: Count StackPop(2); { int mark = StackPeek(); int count = StackPeek(1); int matched = runtextpos - mark; if (count >= Operand(1) || (matched == 0 && count >= 0)) { // Max loops or empty match -> straight now TrackPush2(mark, count); // Save old mark, count advance = 2; // Straight } else { // Nonempty match -> count+loop now TrackPush(mark); // remember mark StackPush(runtextpos, count + 1); // Make new mark, incr count Goto(Operand(0)); // Loop } } continue; case RegexOpcode.Branchcount | RegexOpcode.Backtracking: // TrackPush: // 0: Previous mark // StackPush: // 0: Mark (= current pos, discarded) // 1: Count TrackPop(); StackPop(2); if (StackPeek(1) > 0) { // Positive -> can go straight runtextpos = StackPeek(); // Zap to mark TrackPush2(TrackPeek(), StackPeek(1) - 1); // Save old mark, old count advance = 2; // Straight continue; } StackPush(TrackPeek(), StackPeek(1) - 1); // Recall old mark, old count break; case RegexOpcode.Branchcount | RegexOpcode.BacktrackingSecond: // TrackPush: // 0: Previous mark // 1: Previous count TrackPop(2); StackPush(TrackPeek(), TrackPeek(1)); // Recall old mark, old count break; // Backtrack case RegexOpcode.Lazybranchcount: // StackPush: // 0: Mark // 1: Count StackPop(2); { int mark = StackPeek(); int count = StackPeek(1); if (count < 0) { // Negative count -> loop now TrackPush2(mark); // Save old mark StackPush(runtextpos, count + 1); // Make new mark, incr count Goto(Operand(0)); // Loop } else { // Nonneg count -> straight now TrackPush(mark, count, runtextpos); // Save mark, count, position advance = 2; // Straight } } continue; case RegexOpcode.Lazybranchcount | RegexOpcode.Backtracking: // TrackPush: // 0: Mark // 1: Count // 2: Textpos TrackPop(3); { int mark = TrackPeek(); int textpos = TrackPeek(2); if (TrackPeek(1) < Operand(1) && textpos != mark) { // Under limit and not empty match -> loop runtextpos = textpos; // Recall position StackPush(textpos, TrackPeek(1) + 1); // Make new mark, incr count TrackPush2(mark); // Save old mark Goto(Operand(0)); // Loop continue; } else { // Max loops or empty match -> backtrack StackPush(TrackPeek(), TrackPeek(1)); // Recall old mark, count break; // backtrack } } case RegexOpcode.Lazybranchcount | RegexOpcode.BacktrackingSecond: // TrackPush: // 0: Previous mark // StackPush: // 0: Mark (== current pos, discarded) // 1: Count TrackPop(); StackPop(2); StackPush(TrackPeek(), StackPeek(1) - 1); // Recall old mark, count break; // Backtrack case RegexOpcode.Setjump: StackPush(Trackpos(), Crawlpos()); TrackPush(); advance = 0; continue; case RegexOpcode.Backjump: // StackPush: // 0: Saved trackpos // 1: Crawlpos StackPop(2); Trackto(StackPeek()); while (Crawlpos() != StackPeek(1)) { Uncapture(); } break; case RegexOpcode.Forejump: // StackPush: // 0: Saved trackpos // 1: Crawlpos StackPop(2); Trackto(StackPeek()); TrackPush(StackPeek(1)); advance = 0; continue; case RegexOpcode.Forejump | RegexOpcode.Backtracking: // TrackPush: // 0: Crawlpos TrackPop(); while (Crawlpos() != TrackPeek()) { Uncapture(); } break; case RegexOpcode.Bol: if (Leftchars() > 0 && inputSpan[runtextpos - 1] != '\n') { break; } advance = 0; continue; case RegexOpcode.Eol: if (Rightchars() > 0 && inputSpan[runtextpos] != '\n') { break; } advance = 0; continue; case RegexOpcode.Boundary: if (!IsBoundary(inputSpan, runtextpos)) { break; } advance = 0; continue; case RegexOpcode.NonBoundary: if (IsBoundary(inputSpan, runtextpos)) { break; } advance = 0; continue; case RegexOpcode.ECMABoundary: if (!IsECMABoundary(inputSpan, runtextpos)) { break; } advance = 0; continue; case RegexOpcode.NonECMABoundary: if (IsECMABoundary(inputSpan, runtextpos)) { break; } advance = 0; continue; case RegexOpcode.Beginning: if (Leftchars() > 0) { break; } advance = 0; continue; case RegexOpcode.Start: if (runtextpos != runtextstart) { break; } advance = 0; continue; case RegexOpcode.EndZ: if (Rightchars() > 1 || Rightchars() == 1 && inputSpan[runtextpos] != '\n') { break; } advance = 0; continue; case RegexOpcode.End: if (Rightchars() > 0) { break; } advance = 0; continue; case RegexOpcode.One: if (Forwardchars() < 1 || Forwardcharnext(inputSpan) != (char)Operand(0)) { break; } advance = 1; continue; case RegexOpcode.Notone: if (Forwardchars() < 1 || Forwardcharnext(inputSpan) == (char)Operand(0)) { break; } advance = 1; continue; case RegexOpcode.Set: if (Forwardchars() < 1) { break; } else { int operand = Operand(0); if (!RegexCharClass.CharInClass(Forwardcharnext(inputSpan), _code.Strings[operand], ref _code.StringsAsciiLookup[operand])) { break; } } advance = 1; continue; case RegexOpcode.Multi: if (!MatchString(_code.Strings[Operand(0)], inputSpan)) { break; } advance = 1; continue; case RegexOpcode.Backreference: { int capnum = Operand(0); if (IsMatched(capnum)) { if (!MatchRef(MatchIndex(capnum), MatchLength(capnum), inputSpan)) { break; } } else { if ((runregex!.roptions & RegexOptions.ECMAScript) == 0) { break; } } } advance = 1; continue; case RegexOpcode.Onerep: { int c = Operand(1); if (Forwardchars() < c) { break; } char ch = (char)Operand(0); while (c-- > 0) { if (Forwardcharnext(inputSpan) != ch) { goto BreakBackward; } } } advance = 2; continue; case RegexOpcode.Notonerep: { int c = Operand(1); if (Forwardchars() < c) { break; } char ch = (char)Operand(0); while (c-- > 0) { if (Forwardcharnext(inputSpan) == ch) { goto BreakBackward; } } } advance = 2; continue; case RegexOpcode.Setrep: { int c = Operand(1); if (Forwardchars() < c) { break; } int operand0 = Operand(0); string set = _code.Strings[operand0]; ref uint[]? setLookup = ref _code.StringsAsciiLookup[operand0]; while (c-- > 0) { // Check the timeout every 2048th iteration. if ((uint)c % LoopTimeoutCheckCount == 0) { CheckTimeout(); } if (!RegexCharClass.CharInClass(Forwardcharnext(inputSpan), set, ref setLookup)) { goto BreakBackward; } } } advance = 2; continue; case RegexOpcode.Oneloop: case RegexOpcode.Oneloopatomic: { int len = Math.Min(Operand(1), Forwardchars()); char ch = (char)Operand(0); int i; for (i = len; i > 0; i--) { if (Forwardcharnext(inputSpan) != ch) { Backwardnext(); break; } } if (len > i && _operator == RegexOpcode.Oneloop) { TrackPush(len - i - 1, runtextpos - Bump()); } } advance = 2; continue; case RegexOpcode.Notoneloop: case RegexOpcode.Notoneloopatomic: { int len = Math.Min(Operand(1), Forwardchars()); char ch = (char)Operand(0); int i; if (!_rightToLeft && !_caseInsensitive) { // We're left-to-right and case-sensitive, so we can employ the vectorized IndexOf // to search for the character. i = inputSpan.Slice(runtextpos, len).IndexOf(ch); if (i == -1) { runtextpos += len; i = 0; } else { runtextpos += i; i = len - i; } } else { for (i = len; i > 0; i--) { if (Forwardcharnext(inputSpan) == ch) { Backwardnext(); break; } } } if (len > i && _operator == RegexOpcode.Notoneloop) { TrackPush(len - i - 1, runtextpos - Bump()); } } advance = 2; continue; case RegexOpcode.Setloop: case RegexOpcode.Setloopatomic: { int len = Math.Min(Operand(1), Forwardchars()); int operand0 = Operand(0); string set = _code.Strings[operand0]; ref uint[]? setLookup = ref _code.StringsAsciiLookup[operand0]; int i; for (i = len; i > 0; i--) { // Check the timeout every 2048th iteration. if ((uint)i % LoopTimeoutCheckCount == 0) { CheckTimeout(); } if (!RegexCharClass.CharInClass(Forwardcharnext(inputSpan), set, ref setLookup)) { Backwardnext(); break; } } if (len > i && _operator == RegexOpcode.Setloop) { TrackPush(len - i - 1, runtextpos - Bump()); } } advance = 2; continue; case RegexOpcode.Oneloop | RegexOpcode.Backtracking: case RegexOpcode.Notoneloop | RegexOpcode.Backtracking: case RegexOpcode.Setloop | RegexOpcode.Backtracking: TrackPop(2); { int i = TrackPeek(); int pos = TrackPeek(1); runtextpos = pos; if (i > 0) { TrackPush(i - 1, pos - Bump()); } } advance = 2; continue; case RegexOpcode.Onelazy: case RegexOpcode.Notonelazy: case RegexOpcode.Setlazy: { int c = Math.Min(Operand(1), Forwardchars()); if (c > 0) { TrackPush(c - 1, runtextpos); } } advance = 2; continue; case RegexOpcode.Onelazy | RegexOpcode.Backtracking: TrackPop(2); { int pos = TrackPeek(1); runtextpos = pos; if (Forwardcharnext(inputSpan) != (char)Operand(0)) { break; } int i = TrackPeek(); if (i > 0) { TrackPush(i - 1, pos + Bump()); } } advance = 2; continue; case RegexOpcode.Notonelazy | RegexOpcode.Backtracking: TrackPop(2); { int pos = TrackPeek(1); runtextpos = pos; if (Forwardcharnext(inputSpan) == (char)Operand(0)) { break; } int i = TrackPeek(); if (i > 0) { TrackPush(i - 1, pos + Bump()); } } advance = 2; continue; case RegexOpcode.Setlazy | RegexOpcode.Backtracking: TrackPop(2); { int pos = TrackPeek(1); runtextpos = pos; int operand0 = Operand(0); if (!RegexCharClass.CharInClass(Forwardcharnext(inputSpan), _code.Strings[operand0], ref _code.StringsAsciiLookup[operand0])) { break; } int i = TrackPeek(); if (i > 0) { TrackPush(i - 1, pos + Bump()); } } advance = 2; continue; case RegexOpcode.UpdateBumpalong: // UpdateBumpalong should only exist in the code stream at such a point where the root // of the backtracking stack contains the runtextpos from the start of this Go call. Replace // that tracking value with the current runtextpos value if it's greater. { Debug.Assert(!_rightToLeft, "UpdateBumpalongs aren't added for RTL"); ref int trackingpos = ref runtrack![runtrack.Length - 1]; if (trackingpos < runtextpos) { trackingpos = runtextpos; } advance = 0; continue; } default: Debug.Fail($"Unimplemented state: {_operator:X8}"); break; } BreakBackward: Backtrack(); } } #if DEBUG [ExcludeFromCodeCoverage(Justification = "Debug only")] internal override void DebugTraceCurrentState() { base.DebugTraceCurrentState(); Debug.WriteLine($" {_code.DescribeInstruction(_codepos)} {((_operator & RegexOpcode.Backtracking) != 0 ? " Back" : "")} {((_operator & RegexOpcode.BacktrackingSecond) != 0 ? " Back2" : "")}"); Debug.WriteLine(""); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; namespace System.Text.RegularExpressions { /// <summary>A <see cref="RegexRunnerFactory"/> for creating <see cref="RegexInterpreter"/>s.</summary> internal sealed class RegexInterpreterFactory : RegexRunnerFactory { private readonly RegexInterpreterCode _code; public RegexInterpreterFactory(RegexTree tree, CultureInfo culture) => // Generate and store the RegexInterpretedCode for the RegexTree and the specified culture _code = RegexWriter.Write(tree, culture); protected internal override RegexRunner CreateInstance() => // Create a new interpreter instance. new RegexInterpreter(_code, RegexParser.GetTargetCulture(_code.Options)); } /// <summary>Executes a block of regular expression codes while consuming input.</summary> internal sealed class RegexInterpreter : RegexRunner { private const int LoopTimeoutCheckCount = 2048; // conservative value to provide reasonably-accurate timeout handling. private readonly RegexInterpreterCode _code; private readonly TextInfo _textInfo; private RegexOpcode _operator; private int _codepos; private bool _rightToLeft; private bool _caseInsensitive; public RegexInterpreter(RegexInterpreterCode code, CultureInfo culture) { Debug.Assert(code != null, "code must not be null."); Debug.Assert(culture != null, "culture must not be null."); _code = code; _textInfo = culture.TextInfo; } protected override void InitTrackCount() => runtrackcount = _code.TrackCount; private void Advance(int i) { _codepos += i + 1; SetOperator((RegexOpcode)_code.Codes[_codepos]); } private void Goto(int newpos) { // When branching backward, ensure storage. if (newpos < _codepos) { EnsureStorage(); } _codepos = newpos; SetOperator((RegexOpcode)_code.Codes[newpos]); } private void Trackto(int newpos) => runtrackpos = runtrack!.Length - newpos; private int Trackpos() => runtrack!.Length - runtrackpos; /// <summary>Push onto the backtracking stack.</summary> private void TrackPush() => runtrack![--runtrackpos] = _codepos; private void TrackPush(int i1) { int[] localruntrack = runtrack!; int localruntrackpos = runtrackpos; localruntrack[--localruntrackpos] = i1; localruntrack[--localruntrackpos] = _codepos; runtrackpos = localruntrackpos; } private void TrackPush(int i1, int i2) { int[] localruntrack = runtrack!; int localruntrackpos = runtrackpos; localruntrack[--localruntrackpos] = i1; localruntrack[--localruntrackpos] = i2; localruntrack[--localruntrackpos] = _codepos; runtrackpos = localruntrackpos; } private void TrackPush(int i1, int i2, int i3) { int[] localruntrack = runtrack!; int localruntrackpos = runtrackpos; localruntrack[--localruntrackpos] = i1; localruntrack[--localruntrackpos] = i2; localruntrack[--localruntrackpos] = i3; localruntrack[--localruntrackpos] = _codepos; runtrackpos = localruntrackpos; } private void TrackPush2(int i1) { int[] localruntrack = runtrack!; int localruntrackpos = runtrackpos; localruntrack[--localruntrackpos] = i1; localruntrack[--localruntrackpos] = -_codepos; runtrackpos = localruntrackpos; } private void TrackPush2(int i1, int i2) { int[] localruntrack = runtrack!; int localruntrackpos = runtrackpos; localruntrack[--localruntrackpos] = i1; localruntrack[--localruntrackpos] = i2; localruntrack[--localruntrackpos] = -_codepos; runtrackpos = localruntrackpos; } private void Backtrack() { int newpos = runtrack![runtrackpos]; runtrackpos++; #if DEBUG Debug.WriteLineIf(Regex.EnableDebugTracing, $" Backtracking{(newpos < 0 ? " (back2)" : "")} to code position {Math.Abs(newpos)}"); #endif int back = (int)RegexOpcode.Backtracking; if (newpos < 0) { newpos = -newpos; back = (int)RegexOpcode.BacktrackingSecond; } SetOperator((RegexOpcode)(_code.Codes[newpos] | back)); // When branching backward, ensure storage. if (newpos < _codepos) { EnsureStorage(); } _codepos = newpos; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SetOperator(RegexOpcode op) { _operator = op & ~(RegexOpcode.RightToLeft | RegexOpcode.CaseInsensitive); _caseInsensitive = (op & RegexOpcode.CaseInsensitive) != 0; _rightToLeft = (op & RegexOpcode.RightToLeft) != 0; } private void TrackPop() => runtrackpos++; /// <summary>Pop framesize items from the backtracking stack.</summary> private void TrackPop(int framesize) => runtrackpos += framesize; /// <summary>Peek at the item popped from the stack.</summary> /// <remarks> /// If you want to get and pop the top item from the stack, you do `TrackPop(); TrackPeek();`. /// </remarks> private int TrackPeek() => runtrack![runtrackpos - 1]; /// <summary>Get the ith element down on the backtracking stack.</summary> private int TrackPeek(int i) => runtrack![runtrackpos - i - 1]; /// <summary>Push onto the grouping stack.</summary> private void StackPush(int i1) => runstack![--runstackpos] = i1; private void StackPush(int i1, int i2) { int[] localrunstack = runstack!; int localrunstackpos = runstackpos; localrunstack[--localrunstackpos] = i1; localrunstack[--localrunstackpos] = i2; runstackpos = localrunstackpos; } private void StackPop() => runstackpos++; // pop framesize items from the grouping stack private void StackPop(int framesize) => runstackpos += framesize; /// <summary> /// Technically we are actually peeking at items already popped. So if you want to /// get and pop the top item from the stack, you do `StackPop(); StackPeek();`. /// </summary> private int StackPeek() => runstack![runstackpos - 1]; /// <summary>Get the ith element down on the grouping stack.</summary> private int StackPeek(int i) => runstack![runstackpos - i - 1]; private int Operand(int i) => _code.Codes[_codepos + i + 1]; private int Bump() => _rightToLeft ? -1 : 1; private int Forwardchars() => _rightToLeft ? runtextpos : runtextend - runtextpos; private char Forwardcharnext(ReadOnlySpan<char> inputSpan) { int i = _rightToLeft ? --runtextpos : runtextpos++; char ch = inputSpan[i]; return _caseInsensitive ? _textInfo.ToLower(ch) : ch; } private bool MatchString(string str, ReadOnlySpan<char> inputSpan) { int c = str.Length; int pos; if (!_rightToLeft) { if (inputSpan.Length - runtextpos < c) { return false; } pos = runtextpos + c; } else { if (runtextpos < c) { return false; } pos = runtextpos; } if (!_caseInsensitive) { while (c != 0) { if (str[--c] != inputSpan[--pos]) { return false; } } } else { TextInfo ti = _textInfo; while (c != 0) { if (str[--c] != ti.ToLower(inputSpan[--pos])) { return false; } } } if (!_rightToLeft) { pos += str.Length; } runtextpos = pos; return true; } private bool MatchRef(int index, int length, ReadOnlySpan<char> inputSpan) { int pos; if (!_rightToLeft) { if (inputSpan.Length - runtextpos < length) { return false; } pos = runtextpos + length; } else { if (runtextpos < length) { return false; } pos = runtextpos; } int cmpos = index + length; int c = length; if (!_caseInsensitive) { while (c-- != 0) { if (inputSpan[--cmpos] != inputSpan[--pos]) { return false; } } } else { TextInfo ti = _textInfo; while (c-- != 0) { if (ti.ToLower(inputSpan[--cmpos]) != ti.ToLower(inputSpan[--pos])) { return false; } } } if (!_rightToLeft) { pos += length; } runtextpos = pos; return true; } private void Backwardnext() => runtextpos += _rightToLeft ? 1 : -1; protected internal override void Scan(ReadOnlySpan<char> text) { Debug.Assert(runregex is not null); Debug.Assert(runtrack is not null); Debug.Assert(runstack is not null); Debug.Assert(runcrawl is not null); // Configure the additional value to "bump" the position along each time we loop around // to call TryFindNextStartingPosition again, as well as the stopping position for the loop. We generally // bump by 1 and stop at textend, but if we're examining right-to-left, we instead bump // by -1 and stop at textbeg. int bump = 1, stoppos = text.Length; if (runregex.RightToLeft) { bump = -1; stoppos = 0; } while (_code.FindOptimizations.TryFindNextStartingPosition(text, ref runtextpos, runtextstart)) { CheckTimeout(); if (TryMatchAtCurrentPosition(text) || runtextpos == stoppos) { return; } // Reset state for another iteration. runtrackpos = runtrack.Length; runstackpos = runstack.Length; runcrawlpos = runcrawl.Length; runtextpos += bump; } } private bool TryMatchAtCurrentPosition(ReadOnlySpan<char> inputSpan) { SetOperator((RegexOpcode)_code.Codes[0]); _codepos = 0; int advance = -1; while (true) { if (advance >= 0) { // Single common Advance call to reduce method size; and single method inline point. // Details at https://github.com/dotnet/corefx/pull/25096. Advance(advance); advance = -1; } #if DEBUG if (Regex.EnableDebugTracing) { DebugTraceCurrentState(); } #endif CheckTimeout(); switch (_operator) { case RegexOpcode.Stop: return runmatch!.FoundMatch; case RegexOpcode.Nothing: break; case RegexOpcode.Goto: Goto(Operand(0)); continue; case RegexOpcode.TestBackreference: if (!IsMatched(Operand(0))) { break; } advance = 1; continue; case RegexOpcode.Lazybranch: TrackPush(runtextpos); advance = 1; continue; case RegexOpcode.Lazybranch | RegexOpcode.Backtracking: TrackPop(); runtextpos = TrackPeek(); Goto(Operand(0)); continue; case RegexOpcode.Setmark: StackPush(runtextpos); TrackPush(); advance = 0; continue; case RegexOpcode.Nullmark: StackPush(-1); TrackPush(); advance = 0; continue; case RegexOpcode.Setmark | RegexOpcode.Backtracking: case RegexOpcode.Nullmark | RegexOpcode.Backtracking: StackPop(); break; case RegexOpcode.Getmark: StackPop(); TrackPush(StackPeek()); runtextpos = StackPeek(); advance = 0; continue; case RegexOpcode.Getmark | RegexOpcode.Backtracking: TrackPop(); StackPush(TrackPeek()); break; case RegexOpcode.Capturemark: if (Operand(1) != -1 && !IsMatched(Operand(1))) { break; } StackPop(); if (Operand(1) != -1) { TransferCapture(Operand(0), Operand(1), StackPeek(), runtextpos); } else { Capture(Operand(0), StackPeek(), runtextpos); } TrackPush(StackPeek()); advance = 2; continue; case RegexOpcode.Capturemark | RegexOpcode.Backtracking: TrackPop(); StackPush(TrackPeek()); Uncapture(); if (Operand(0) != -1 && Operand(1) != -1) { Uncapture(); } break; case RegexOpcode.Branchmark: StackPop(); if (runtextpos != StackPeek()) { // Nonempty match -> loop now TrackPush(StackPeek(), runtextpos); // Save old mark, textpos StackPush(runtextpos); // Make new mark Goto(Operand(0)); // Loop } else { // Empty match -> straight now TrackPush2(StackPeek()); // Save old mark advance = 1; // Straight } continue; case RegexOpcode.Branchmark | RegexOpcode.Backtracking: TrackPop(2); StackPop(); runtextpos = TrackPeek(1); // Recall position TrackPush2(TrackPeek()); // Save old mark advance = 1; // Straight continue; case RegexOpcode.Branchmark | RegexOpcode.BacktrackingSecond: TrackPop(); StackPush(TrackPeek()); // Recall old mark break; // Backtrack case RegexOpcode.Lazybranchmark: // We hit this the first time through a lazy loop and after each // successful match of the inner expression. It simply continues // on and doesn't loop. StackPop(); { int oldMarkPos = StackPeek(); if (runtextpos != oldMarkPos) { // Nonempty match -> try to loop again by going to 'back' state if (oldMarkPos != -1) { TrackPush(oldMarkPos, runtextpos); // Save old mark, textpos } else { TrackPush(runtextpos, runtextpos); } } else { // The inner expression found an empty match, so we'll go directly to 'back2' if we // backtrack. In this case, we need to push something on the stack, since back2 pops. // However, in the case of ()+? or similar, this empty match may be legitimate, so push the text // position associated with that empty match. StackPush(oldMarkPos); TrackPush2(StackPeek()); // Save old mark } } advance = 1; continue; case RegexOpcode.Lazybranchmark | RegexOpcode.Backtracking: { // After the first time, Lazybranchmark | RegexOpcode.Back occurs // with each iteration of the loop, and therefore with every attempted // match of the inner expression. We'll try to match the inner expression, // then go back to Lazybranchmark if successful. If the inner expression // fails, we go to Lazybranchmark | RegexOpcode.Back2 TrackPop(2); int pos = TrackPeek(1); TrackPush2(TrackPeek()); // Save old mark StackPush(pos); // Make new mark runtextpos = pos; // Recall position Goto(Operand(0)); // Loop } continue; case RegexOpcode.Lazybranchmark | RegexOpcode.BacktrackingSecond: // The lazy loop has failed. We'll do a true backtrack and // start over before the lazy loop. StackPop(); TrackPop(); StackPush(TrackPeek()); // Recall old mark break; case RegexOpcode.Setcount: StackPush(runtextpos, Operand(0)); TrackPush(); advance = 1; continue; case RegexOpcode.Nullcount: StackPush(-1, Operand(0)); TrackPush(); advance = 1; continue; case RegexOpcode.Setcount | RegexOpcode.Backtracking: case RegexOpcode.Nullcount | RegexOpcode.Backtracking: case RegexOpcode.Setjump | RegexOpcode.Backtracking: StackPop(2); break; case RegexOpcode.Branchcount: // StackPush: // 0: Mark // 1: Count StackPop(2); { int mark = StackPeek(); int count = StackPeek(1); int matched = runtextpos - mark; if (count >= Operand(1) || (matched == 0 && count >= 0)) { // Max loops or empty match -> straight now TrackPush2(mark, count); // Save old mark, count advance = 2; // Straight } else { // Nonempty match -> count+loop now TrackPush(mark); // remember mark StackPush(runtextpos, count + 1); // Make new mark, incr count Goto(Operand(0)); // Loop } } continue; case RegexOpcode.Branchcount | RegexOpcode.Backtracking: // TrackPush: // 0: Previous mark // StackPush: // 0: Mark (= current pos, discarded) // 1: Count TrackPop(); StackPop(2); if (StackPeek(1) > 0) { // Positive -> can go straight runtextpos = StackPeek(); // Zap to mark TrackPush2(TrackPeek(), StackPeek(1) - 1); // Save old mark, old count advance = 2; // Straight continue; } StackPush(TrackPeek(), StackPeek(1) - 1); // Recall old mark, old count break; case RegexOpcode.Branchcount | RegexOpcode.BacktrackingSecond: // TrackPush: // 0: Previous mark // 1: Previous count TrackPop(2); StackPush(TrackPeek(), TrackPeek(1)); // Recall old mark, old count break; // Backtrack case RegexOpcode.Lazybranchcount: // StackPush: // 0: Mark // 1: Count StackPop(2); { int mark = StackPeek(); int count = StackPeek(1); if (count < 0) { // Negative count -> loop now TrackPush2(mark); // Save old mark StackPush(runtextpos, count + 1); // Make new mark, incr count Goto(Operand(0)); // Loop } else { // Nonneg count -> straight now TrackPush(mark, count, runtextpos); // Save mark, count, position advance = 2; // Straight } } continue; case RegexOpcode.Lazybranchcount | RegexOpcode.Backtracking: // TrackPush: // 0: Mark // 1: Count // 2: Textpos TrackPop(3); { int mark = TrackPeek(); int textpos = TrackPeek(2); if (TrackPeek(1) < Operand(1) && textpos != mark) { // Under limit and not empty match -> loop runtextpos = textpos; // Recall position StackPush(textpos, TrackPeek(1) + 1); // Make new mark, incr count TrackPush2(mark); // Save old mark Goto(Operand(0)); // Loop continue; } else { // Max loops or empty match -> backtrack StackPush(TrackPeek(), TrackPeek(1)); // Recall old mark, count break; // backtrack } } case RegexOpcode.Lazybranchcount | RegexOpcode.BacktrackingSecond: // TrackPush: // 0: Previous mark // StackPush: // 0: Mark (== current pos, discarded) // 1: Count TrackPop(); StackPop(2); StackPush(TrackPeek(), StackPeek(1) - 1); // Recall old mark, count break; // Backtrack case RegexOpcode.Setjump: StackPush(Trackpos(), Crawlpos()); TrackPush(); advance = 0; continue; case RegexOpcode.Backjump: // StackPush: // 0: Saved trackpos // 1: Crawlpos StackPop(2); Trackto(StackPeek()); while (Crawlpos() != StackPeek(1)) { Uncapture(); } break; case RegexOpcode.Forejump: // StackPush: // 0: Saved trackpos // 1: Crawlpos StackPop(2); Trackto(StackPeek()); TrackPush(StackPeek(1)); advance = 0; continue; case RegexOpcode.Forejump | RegexOpcode.Backtracking: // TrackPush: // 0: Crawlpos TrackPop(); while (Crawlpos() != TrackPeek()) { Uncapture(); } break; case RegexOpcode.Bol: { int m1 = runtextpos - 1; if ((uint)m1 < (uint)inputSpan.Length && inputSpan[m1] != '\n') { break; } advance = 0; continue; } case RegexOpcode.Eol: { int runtextpos = this.runtextpos; if ((uint)runtextpos < (uint)inputSpan.Length && inputSpan[runtextpos] != '\n') { break; } advance = 0; continue; } case RegexOpcode.Boundary: if (!IsBoundary(inputSpan, runtextpos)) { break; } advance = 0; continue; case RegexOpcode.NonBoundary: if (IsBoundary(inputSpan, runtextpos)) { break; } advance = 0; continue; case RegexOpcode.ECMABoundary: if (!IsECMABoundary(inputSpan, runtextpos)) { break; } advance = 0; continue; case RegexOpcode.NonECMABoundary: if (IsECMABoundary(inputSpan, runtextpos)) { break; } advance = 0; continue; case RegexOpcode.Beginning: if (runtextpos > 0) { break; } advance = 0; continue; case RegexOpcode.Start: if (runtextpos != runtextstart) { break; } advance = 0; continue; case RegexOpcode.EndZ: { int runtextpos = this.runtextpos; if (runtextpos < inputSpan.Length - 1 || ((uint)runtextpos < (uint)inputSpan.Length && inputSpan[runtextpos] != '\n')) { break; } advance = 0; continue; } case RegexOpcode.End: if (runtextpos < inputSpan.Length) { break; } advance = 0; continue; case RegexOpcode.One: if (Forwardchars() < 1 || Forwardcharnext(inputSpan) != (char)Operand(0)) { break; } advance = 1; continue; case RegexOpcode.Notone: if (Forwardchars() < 1 || Forwardcharnext(inputSpan) == (char)Operand(0)) { break; } advance = 1; continue; case RegexOpcode.Set: if (Forwardchars() < 1) { break; } else { int operand = Operand(0); if (!RegexCharClass.CharInClass(Forwardcharnext(inputSpan), _code.Strings[operand], ref _code.StringsAsciiLookup[operand])) { break; } } advance = 1; continue; case RegexOpcode.Multi: if (!MatchString(_code.Strings[Operand(0)], inputSpan)) { break; } advance = 1; continue; case RegexOpcode.Backreference: { int capnum = Operand(0); if (IsMatched(capnum)) { if (!MatchRef(MatchIndex(capnum), MatchLength(capnum), inputSpan)) { break; } } else { if ((runregex!.roptions & RegexOptions.ECMAScript) == 0) { break; } } } advance = 1; continue; case RegexOpcode.Onerep: { int c = Operand(1); if (Forwardchars() < c) { break; } char ch = (char)Operand(0); while (c-- > 0) { if (Forwardcharnext(inputSpan) != ch) { goto BreakBackward; } } } advance = 2; continue; case RegexOpcode.Notonerep: { int c = Operand(1); if (Forwardchars() < c) { break; } char ch = (char)Operand(0); while (c-- > 0) { if (Forwardcharnext(inputSpan) == ch) { goto BreakBackward; } } } advance = 2; continue; case RegexOpcode.Setrep: { int c = Operand(1); if (Forwardchars() < c) { break; } int operand0 = Operand(0); string set = _code.Strings[operand0]; ref uint[]? setLookup = ref _code.StringsAsciiLookup[operand0]; while (c-- > 0) { // Check the timeout every 2048th iteration. if ((uint)c % LoopTimeoutCheckCount == 0) { CheckTimeout(); } if (!RegexCharClass.CharInClass(Forwardcharnext(inputSpan), set, ref setLookup)) { goto BreakBackward; } } } advance = 2; continue; case RegexOpcode.Oneloop: case RegexOpcode.Oneloopatomic: { int len = Math.Min(Operand(1), Forwardchars()); char ch = (char)Operand(0); int i; for (i = len; i > 0; i--) { if (Forwardcharnext(inputSpan) != ch) { Backwardnext(); break; } } if (len > i && _operator == RegexOpcode.Oneloop) { TrackPush(len - i - 1, runtextpos - Bump()); } } advance = 2; continue; case RegexOpcode.Notoneloop: case RegexOpcode.Notoneloopatomic: { int len = Math.Min(Operand(1), Forwardchars()); char ch = (char)Operand(0); int i; if (!_rightToLeft && !_caseInsensitive) { // We're left-to-right and case-sensitive, so we can employ the vectorized IndexOf // to search for the character. i = inputSpan.Slice(runtextpos, len).IndexOf(ch); if (i == -1) { runtextpos += len; i = 0; } else { runtextpos += i; i = len - i; } } else { for (i = len; i > 0; i--) { if (Forwardcharnext(inputSpan) == ch) { Backwardnext(); break; } } } if (len > i && _operator == RegexOpcode.Notoneloop) { TrackPush(len - i - 1, runtextpos - Bump()); } } advance = 2; continue; case RegexOpcode.Setloop: case RegexOpcode.Setloopatomic: { int len = Math.Min(Operand(1), Forwardchars()); int operand0 = Operand(0); string set = _code.Strings[operand0]; ref uint[]? setLookup = ref _code.StringsAsciiLookup[operand0]; int i; for (i = len; i > 0; i--) { // Check the timeout every 2048th iteration. if ((uint)i % LoopTimeoutCheckCount == 0) { CheckTimeout(); } if (!RegexCharClass.CharInClass(Forwardcharnext(inputSpan), set, ref setLookup)) { Backwardnext(); break; } } if (len > i && _operator == RegexOpcode.Setloop) { TrackPush(len - i - 1, runtextpos - Bump()); } } advance = 2; continue; case RegexOpcode.Oneloop | RegexOpcode.Backtracking: case RegexOpcode.Notoneloop | RegexOpcode.Backtracking: case RegexOpcode.Setloop | RegexOpcode.Backtracking: TrackPop(2); { int i = TrackPeek(); int pos = TrackPeek(1); runtextpos = pos; if (i > 0) { TrackPush(i - 1, pos - Bump()); } } advance = 2; continue; case RegexOpcode.Onelazy: case RegexOpcode.Notonelazy: case RegexOpcode.Setlazy: { int c = Math.Min(Operand(1), Forwardchars()); if (c > 0) { TrackPush(c - 1, runtextpos); } } advance = 2; continue; case RegexOpcode.Onelazy | RegexOpcode.Backtracking: TrackPop(2); { int pos = TrackPeek(1); runtextpos = pos; if (Forwardcharnext(inputSpan) != (char)Operand(0)) { break; } int i = TrackPeek(); if (i > 0) { TrackPush(i - 1, pos + Bump()); } } advance = 2; continue; case RegexOpcode.Notonelazy | RegexOpcode.Backtracking: TrackPop(2); { int pos = TrackPeek(1); runtextpos = pos; if (Forwardcharnext(inputSpan) == (char)Operand(0)) { break; } int i = TrackPeek(); if (i > 0) { TrackPush(i - 1, pos + Bump()); } } advance = 2; continue; case RegexOpcode.Setlazy | RegexOpcode.Backtracking: TrackPop(2); { int pos = TrackPeek(1); runtextpos = pos; int operand0 = Operand(0); if (!RegexCharClass.CharInClass(Forwardcharnext(inputSpan), _code.Strings[operand0], ref _code.StringsAsciiLookup[operand0])) { break; } int i = TrackPeek(); if (i > 0) { TrackPush(i - 1, pos + Bump()); } } advance = 2; continue; case RegexOpcode.UpdateBumpalong: // UpdateBumpalong should only exist in the code stream at such a point where the root // of the backtracking stack contains the runtextpos from the start of this Go call. Replace // that tracking value with the current runtextpos value if it's greater. { Debug.Assert(!_rightToLeft, "UpdateBumpalongs aren't added for RTL"); ref int trackingpos = ref runtrack![runtrack.Length - 1]; if (trackingpos < runtextpos) { trackingpos = runtextpos; } advance = 0; continue; } default: Debug.Fail($"Unimplemented state: {_operator:X8}"); break; } BreakBackward: Backtrack(); } } #if DEBUG [ExcludeFromCodeCoverage(Justification = "Debug only")] internal override void DebugTraceCurrentState() { base.DebugTraceCurrentState(); Debug.WriteLine($" {_code.DescribeInstruction(_codepos)} {((_operator & RegexOpcode.Backtracking) != 0 ? " Back" : "")} {((_operator & RegexOpcode.BacktrackingSecond) != 0 ? " Back2" : "")}"); Debug.WriteLine(""); } #endif } }
1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents a regex matching engine that performs regex matching using symbolic derivatives.</summary> internal abstract class SymbolicRegexMatcher { #if DEBUG /// <summary>Unwind the regex of the matcher and save the resulting state graph in DGML</summary> /// <param name="bound">roughly the maximum number of states, 0 means no bound</param> /// <param name="hideStateInfo">if true then hide state info</param> /// <param name="addDotStar">if true then pretend that there is a .* at the beginning</param> /// <param name="inReverse">if true then unwind the regex backwards (addDotStar is then ignored)</param> /// <param name="onlyDFAinfo">if true then compute and save only genral DFA info</param> /// <param name="writer">dgml output is written here</param> /// <param name="maxLabelLength">maximum length of labels in nodes anything over that length is indicated with .. </param> /// <param name="asNFA">if true creates NFA instead of DFA</param> public abstract void SaveDGML(TextWriter writer, int bound, bool hideStateInfo, bool addDotStar, bool inReverse, bool onlyDFAinfo, int maxLabelLength, bool asNFA); /// <summary> /// Generates up to k random strings matched by the regex /// </summary> /// <param name="k">upper bound on the number of generated strings</param> /// <param name="randomseed">random seed for the generator, 0 means no random seed</param> /// <param name="negative">if true then generate inputs that do not match</param> /// <returns></returns> public abstract IEnumerable<string> GenerateRandomMembers(int k, int randomseed, bool negative); #endif } /// <summary>Represents a regex matching engine that performs regex matching using symbolic derivatives.</summary> /// <typeparam name="TSetType">Character set type.</typeparam> internal sealed class SymbolicRegexMatcher<TSetType> : SymbolicRegexMatcher where TSetType : notnull { /// <summary>Maximum number of built states before switching over to NFA mode.</summary> /// <remarks> /// By default, all matching starts out using DFAs, where every state transitions to one and only one /// state for any minterm (each character maps to one minterm). Some regular expressions, however, can result /// in really, really large DFA state graphs, much too big to actually store. Instead of failing when we /// encounter such state graphs, at some point we instead switch from processing as a DFA to processing as /// an NFA. As an NFA, we instead track all of the states we're in at any given point, and transitioning /// from one "state" to the next really means for every constituent state that composes our current "state", /// we find all possible states that transitioning out of each of them could result in, and the union of /// all of those is our new "state". This constant represents the size of the graph after which we start /// processing as an NFA instead of as a DFA. This processing doesn't change immediately, however. All /// processing starts out in DFA mode, even if we've previously triggered NFA mode for the same regex. /// We switch over into NFA mode the first time a given traversal (match operation) results in us needing /// to create a new node and the graph is already or newly beyond this threshold. /// </remarks> internal const int NfaThreshold = 10_000; /// <summary>Sentinel value used internally by the matcher to indicate no match exists.</summary> private const int NoMatchExists = -2; /// <summary>Builder used to create <see cref="SymbolicRegexNode{S}"/>s while matching.</summary> /// <remarks> /// The builder is used to build up the DFA state space lazily, which means we need to be able to /// produce new <see cref="SymbolicRegexNode{S}"/>s as we match. Once in NFA mode, we also use /// the builder to produce new NFA states. The builder maintains a cache of all DFA and NFA states. /// </remarks> internal readonly SymbolicRegexBuilder<TSetType> _builder; /// <summary>Maps every character to its corresponding minterm ID.</summary> private readonly MintermClassifier _mintermClassifier; /// <summary><see cref="_pattern"/> prefixed with [0-0xFFFF]*</summary> /// <remarks> /// The matching engine first uses <see cref="_dotStarredPattern"/> to find whether there is a match /// and where that match might end. Prepending the .* prefix onto the original pattern provides the DFA /// with the ability to continue to process input characters even if those characters aren't part of /// the match. If Regex.IsMatch is used, nothing further is needed beyond this prefixed pattern. If, however, /// other matching operations are performed that require knowing the exact start and end of the match, /// the engine then needs to process the pattern in reverse to find where the match actually started; /// for that, it uses the <see cref="_reversePattern"/> and walks backwards through the input characters /// from where <see cref="_dotStarredPattern"/> left off. At this point we know that there was a match, /// where it started, and where it could have ended, but that ending point could be influenced by the /// selection of the starting point. So, to find the actual ending point, the original <see cref="_pattern"/> /// is then used from that starting point to walk forward through the input characters again to find the /// actual end point used for the match. /// </remarks> internal readonly SymbolicRegexNode<TSetType> _dotStarredPattern; /// <summary>The original regex pattern.</summary> internal readonly SymbolicRegexNode<TSetType> _pattern; /// <summary>The reverse of <see cref="_pattern"/>.</summary> /// <remarks> /// Determining that there is a match and where the match ends requires only <see cref="_pattern"/>. /// But from there determining where the match began requires reversing the pattern and running /// the matcher again, starting from the ending position. This <see cref="_reversePattern"/> caches /// that reversed pattern used for extracting match start. /// </remarks> internal readonly SymbolicRegexNode<TSetType> _reversePattern; /// <summary>true iff timeout checking is enabled.</summary> private readonly bool _checkTimeout; /// <summary>Timeout in milliseconds. This is only used if <see cref="_checkTimeout"/> is true.</summary> private readonly int _timeout; /// <summary>Data and routines for skipping ahead to the next place a match could potentially start.</summary> private readonly RegexFindOptimizations? _findOpts; /// <summary>The initial states for the original pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _initialStates; /// <summary>The initial states for the dot-star pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _dotstarredInitialStates; /// <summary>The initial states for the reverse pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _reverseInitialStates; /// <summary>Lookup table to quickly determine the character kind for ASCII characters.</summary> /// <remarks>Non-null iff the pattern contains anchors; otherwise, it's unused.</remarks> private readonly uint[]? _asciiCharKinds; /// <summary>Number of capture groups.</summary> private readonly int _capsize; /// <summary>Fixed-length of any possible match.</summary> /// <remarks>This will be null if matches may be of varying lengths or if a fixed-length couldn't otherwise be computed.</remarks> private readonly int? _fixedMatchLength; /// <summary>Gets whether the regular expression contains captures (beyond the implicit root-level capture).</summary> /// <remarks>This determines whether the matcher uses the special capturing NFA simulation mode.</remarks> internal bool HasSubcaptures => _capsize > 1; /// <summary>Get the minterm of <paramref name="c"/>.</summary> /// <param name="c">character code</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] private TSetType GetMinterm(int c) { Debug.Assert(_builder._minterms is not null); return _builder._minterms[_mintermClassifier.GetMintermID(c)]; } /// <summary>Constructs matcher for given symbolic regex.</summary> internal SymbolicRegexMatcher(SymbolicRegexNode<TSetType> sr, RegexTree regexTree, BDD[] minterms, TimeSpan matchTimeout) { Debug.Assert(sr._builder._solver is BitVector64Algebra or BitVectorAlgebra or CharSetSolver, $"Unsupported algebra: {sr._builder._solver}"); _pattern = sr; _builder = sr._builder; _checkTimeout = Regex.InfiniteMatchTimeout != matchTimeout; _timeout = (int)(matchTimeout.TotalMilliseconds + 0.5); // Round up, so it will be at least 1ms _mintermClassifier = _builder._solver switch { BitVector64Algebra bv64 => bv64._classifier, BitVectorAlgebra bv => bv._classifier, _ => new MintermClassifier((CharSetSolver)(object)_builder._solver, minterms), }; _capsize = regexTree.CaptureCount; if (regexTree.FindOptimizations.MinRequiredLength == regexTree.FindOptimizations.MaxPossibleLength) { _fixedMatchLength = regexTree.FindOptimizations.MinRequiredLength; } if (regexTree.FindOptimizations.FindMode != FindNextStartingPositionMode.NoSearch && regexTree.FindOptimizations.LeadingAnchor == 0) // If there are any anchors, we're better off letting the DFA quickly do its job of determining whether there's a match. { _findOpts = regexTree.FindOptimizations; } // Determine the number of initial states. If there's no anchor, only the default previous // character kind 0 is ever going to be used for all initial states. int statesCount = _pattern._info.ContainsSomeAnchor ? CharKind.CharKindCount : 1; // Create the initial states for the original pattern. var initialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < initialStates.Length; i++) { initialStates[i] = _builder.CreateState(_pattern, i, capturing: HasSubcaptures); } _initialStates = initialStates; // Create the dot-star pattern (a concatenation of any* with the original pattern) // and all of its initial states. SymbolicRegexNode<TSetType> unorderedPattern = _pattern.IgnoreOrOrderAndLazyness(); _dotStarredPattern = _builder.CreateConcat(_builder._anyStar, unorderedPattern); var dotstarredInitialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < dotstarredInitialStates.Length; i++) { // Used to detect if initial state was reentered, // but observe that the behavior from the state may ultimately depend on the previous // input char e.g. possibly causing nullability of \b or \B or of a start-of-line anchor, // in that sense there can be several "versions" (not more than StateCount) of the initial state. DfaMatchingState<TSetType> state = _builder.CreateState(_dotStarredPattern, i, capturing: false); state.IsInitialState = true; dotstarredInitialStates[i] = state; } _dotstarredInitialStates = dotstarredInitialStates; // Create the reverse pattern (the original pattern in reverse order) and all of its // initial states. _reversePattern = unorderedPattern.Reverse(); var reverseInitialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < reverseInitialStates.Length; i++) { reverseInitialStates[i] = _builder.CreateState(_reversePattern, i, capturing: false); } _reverseInitialStates = reverseInitialStates; // Initialize our fast-lookup for determining the character kind of ASCII characters. // This is only required when the pattern contains anchors, as otherwise there's only // ever a single kind used. if (_pattern._info.ContainsSomeAnchor) { var asciiCharKinds = new uint[128]; for (int i = 0; i < asciiCharKinds.Length; i++) { TSetType predicate2; uint charKind; if (i == '\n') { predicate2 = _builder._newLinePredicate; charKind = CharKind.Newline; } else { predicate2 = _builder._wordLetterPredicateForAnchors; charKind = CharKind.WordLetter; } asciiCharKinds[i] = _builder._solver.And(GetMinterm(i), predicate2).Equals(_builder._solver.False) ? 0 : charKind; } _asciiCharKinds = asciiCharKinds; } } /// <summary> /// Create a PerThreadData with the appropriate parts initialized for this matcher's pattern. /// </summary> internal PerThreadData CreatePerThreadData() => new PerThreadData(_builder, _capsize); /// <summary>Compute the target state for the source state and input[i] character and transition to it.</summary> /// <param name="builder">The associated builder.</param> /// <param name="input">The input text.</param> /// <param name="i">The index into <paramref name="input"/> at which the target character lives.</param> /// <param name="state">The current state being transitioned from. Upon return it's the new state if the transition succeeded.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryTakeTransition<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, int i, ref CurrentState state) where TStateHandler : struct, IStateHandler { int c = input[i]; int mintermId = c == '\n' && i == input.Length - 1 && TStateHandler.StartsWithLineAnchor(ref state) ? builder._minterms!.Length : // mintermId = minterms.Length represents \Z (last \n) _mintermClassifier.GetMintermID(c); return TStateHandler.TakeTransition(builder, ref state, mintermId); } private List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)> CreateNewCapturingTransitions(DfaMatchingState<TSetType> state, TSetType minterm, int offset) { Debug.Assert(_builder._capturingDelta is not null); lock (this) { // Get the next state if it exists. The caller should have already tried and found it null (not yet created), // but in the interim another thread could have created it. List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)>? p = _builder._capturingDelta[offset]; if (p is null) { // Build the new state and store it into the array. p = state.NfaEagerNextWithEffects(minterm); Volatile.Write(ref _builder._capturingDelta[offset], p); } return p; } } private void DoCheckTimeout(int timeoutOccursAt) { // This logic is identical to RegexRunner.DoCheckTimeout, with the exception of check skipping. RegexRunner calls // DoCheckTimeout potentially on every iteration of a loop, whereas this calls it only once per transition. int currentMillis = Environment.TickCount; if (currentMillis >= timeoutOccursAt && (0 <= timeoutOccursAt || 0 >= currentMillis)) { throw new RegexMatchTimeoutException(string.Empty, string.Empty, TimeSpan.FromMilliseconds(_timeout)); } } /// <summary>Find a match.</summary> /// <param name="isMatch">Whether to return once we know there's a match without determining where exactly it matched.</param> /// <param name="input">The input span</param> /// <param name="startat">The position to start search in the input span.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> public SymbolicMatch FindMatch(bool isMatch, ReadOnlySpan<char> input, int startat, PerThreadData perThreadData) { Debug.Assert(startat >= 0 && startat <= input.Length, $"{nameof(startat)} == {startat}, {nameof(input.Length)} == {input.Length}"); Debug.Assert(perThreadData is not null); // If we need to perform timeout checks, store the absolute timeout value. int timeoutOccursAt = 0; if (_checkTimeout) { // Using Environment.TickCount for efficiency instead of Stopwatch -- as in the non-DFA case. timeoutOccursAt = Environment.TickCount + (int)(_timeout + 0.5); } // If we're starting at the end of the input, we don't need to do any work other than // determine whether an empty match is valid, i.e. whether the pattern is "nullable" // given the kinds of characters at and just before the end. if (startat == input.Length) { // TODO https://github.com/dotnet/runtime/issues/65606: Handle capture groups. uint prevKind = GetCharKind(input, startat - 1); uint nextKind = GetCharKind(input, startat); return _pattern.IsNullableFor(CharKind.Context(prevKind, nextKind)) ? new SymbolicMatch(startat, 0) : SymbolicMatch.NoMatch; } // Phase 1: // Determine whether there is a match by finding the first final state position. This only tells // us whether there is a match but needn't give us the longest possible match. This may return -1 as // a legitimate value when the initial state is nullable and startat == 0. It returns NoMatchExists (-2) // when there is no match. As an example, consider the pattern a{5,10}b* run against an input // of aaaaaaaaaaaaaaabbbc: phase 1 will find the position of the first b: aaaaaaaaaaaaaaab. int i = FindFinalStatePosition(input, startat, timeoutOccursAt, out int matchStartLowBoundary, out int matchStartLengthMarker, perThreadData); // If there wasn't a match, we're done. if (i == NoMatchExists) { return SymbolicMatch.NoMatch; } // A match exists. If we don't need further details, because IsMatch was used (and thus we don't // need the exact bounds of the match, captures, etc.), we're done. if (isMatch) { return SymbolicMatch.QuickMatch; } // Phase 2: // Match backwards through the input matching against the reverse of the pattern, looking for the earliest // start position. That tells us the actual starting position of the match. We can skip this phase if we // recorded a fixed-length marker for the portion of the pattern that matched, as we can then jump that // exact number of positions backwards. Continuing the previous example, phase 2 will walk backwards from // that first b until it finds the 6th a: aaaaaaaaaab. int matchStart; if (matchStartLengthMarker >= 0) { matchStart = i - matchStartLengthMarker + 1; } else { Debug.Assert(i >= startat - 1); matchStart = i < startat ? startat : FindStartPosition(input, i, matchStartLowBoundary, perThreadData); } // Phase 3: // Match again, this time from the computed start position, to find the latest end position. That start // and end then represent the bounds of the match. If the pattern has subcaptures (captures other than // the top-level capture for the whole match), we need to do more work to compute their exact bounds, so we // take a faster path if captures aren't required. Further, if captures aren't needed, and if any possible // match of the whole pattern is a fixed length, we can skip this phase as well, just using that fixed-length // to compute the ending position based on the starting position. Continuing the previous example, phase 3 // will walk forwards from the 6th a until it finds the end of the match: aaaaaaaaaabbb. if (!HasSubcaptures) { if (_fixedMatchLength.HasValue) { return new SymbolicMatch(matchStart, _fixedMatchLength.GetValueOrDefault()); } int matchEnd = FindEndPosition(input, matchStart, perThreadData); return new SymbolicMatch(matchStart, matchEnd + 1 - matchStart); } else { int matchEnd = FindEndPositionCapturing(input, matchStart, out Registers endRegisters, perThreadData); return new SymbolicMatch(matchStart, matchEnd + 1 - matchStart, endRegisters.CaptureStarts, endRegisters.CaptureEnds); } } /// <summary>Phase 3 of matching. From a found starting position, find the ending position of the match using the original pattern.</summary> /// <remarks> /// The ending position is known to exist; this function just needs to determine exactly what it is. /// We need to find the longest possible match and thus the latest valid ending position. /// </remarks> /// <param name="input">The input text.</param> /// <param name="i">The starting position of the match.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The found ending position of the match.</returns> private int FindEndPosition(ReadOnlySpan<char> input, int i, PerThreadData perThreadData) { // Get the starting state based on the current context. DfaMatchingState<TSetType> dfaStartState = _initialStates[GetCharKind(input, i - 1)]; // If the starting state is nullable (accepts the empty string), then it's a valid // match and we need to record the position as a possible end, but keep going looking // for a better one. int end = input.Length; // invalid sentinel value if (dfaStartState.IsNullable(GetCharKind(input, i))) { // Empty match exists because the initial state is accepting. end = i - 1; } if ((uint)i < (uint)input.Length) { // Iterate from the starting state until we've found the best ending state. SymbolicRegexBuilder<TSetType> builder = dfaStartState.Node._builder; var currentState = new CurrentState(dfaStartState); while (true) { // Run the DFA or NFA traversal backwards from the current point using the current state. bool done = currentState.NfaState is not null ? FindEndPositionDeltas<NfaStateHandler>(builder, input, ref i, ref currentState, ref end) : FindEndPositionDeltas<DfaStateHandler>(builder, input, ref i, ref currentState, ref end); // If we successfully found the ending position, we're done. if (done || (uint)i >= (uint)input.Length) { break; } // We exited out of the inner processing loop, but we didn't hit a dead end or run out // of input, and that should only happen if we failed to transition from one state to // the next, which should only happen if we were in DFA mode and we tried to create // a new state and exceeded the graph size. Upgrade to NFA mode and continue; Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } } // Return the found ending position. Debug.Assert(end < input.Length, "Expected to find an ending position but didn't"); return end; } /// <summary> /// Workhorse inner loop for <see cref="FindEndPosition"/>. Consumes the <paramref name="input"/> character by character, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> private bool FindEndPositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, ref CurrentState currentState, ref int endingIndex) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Repeatedly read the next character from the input and use it to transition the current state to the next. // We're looking for the furthest final state we can find. while ((uint)pos < (uint)input.Length && TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos + 1))) { // If the new state accepts the empty string, we found an ending state. Record the position. endingIndex = pos; } else if (TStateHandler.IsDeadend(ref state)) { // If the new state is a dead end, the match ended the last time endingIndex was updated. currentState = state; i = pos; return true; } // We successfully transitioned to the next state and consumed the current character, // so move along to the next. pos++; } // We either ran out of input, in which case we successfully recorded an ending index, // or we failed to transition to the next state due to the graph becoming too large. currentState = state; i = pos; return false; } /// <summary>Find match end position using the original pattern, end position is known to exist. This version also produces captures.</summary> /// <param name="input">input span</param> /// <param name="i">inclusive start position</param> /// <param name="resultRegisters">out parameter for the final register values, which indicate capture starts and ends</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>the match end position</returns> private int FindEndPositionCapturing(ReadOnlySpan<char> input, int i, out Registers resultRegisters, PerThreadData perThreadData) { int i_end = input.Length; Registers endRegisters = default; DfaMatchingState<TSetType>? endState = null; // Pick the correct start state based on previous character kind. DfaMatchingState<TSetType> initialState = _initialStates[GetCharKind(input, i - 1)]; Registers initialRegisters = perThreadData.InitialRegisters; // Initialize registers with -1, which means "not seen yet" Array.Fill(initialRegisters.CaptureStarts, -1); Array.Fill(initialRegisters.CaptureEnds, -1); if (initialState.IsNullable(GetCharKind(input, i))) { // Empty match exists because the initial state is accepting. i_end = i - 1; endRegisters.Assign(initialRegisters); endState = initialState; } // Use two maps from state IDs to register values for the current and next set of states. // Note that these maps use insertion order, which is used to maintain priorities between states in a way // that matches the order the backtracking engines visit paths. Debug.Assert(perThreadData.Current is not null && perThreadData.Next is not null); SparseIntMap<Registers> current = perThreadData.Current, next = perThreadData.Next; current.Clear(); next.Clear(); current.Add(initialState.Id, initialRegisters); SymbolicRegexBuilder<TSetType> builder = _builder; while ((uint)i < (uint)input.Length) { Debug.Assert(next.Count == 0); int c = input[i]; int normalMintermId = _mintermClassifier.GetMintermID(c); foreach ((int sourceId, Registers sourceRegisters) in current.Values) { Debug.Assert(builder._capturingStateArray is not null); DfaMatchingState<TSetType> sourceState = builder._capturingStateArray[sourceId]; // Find the minterm, handling the special case for the last \n int mintermId = c == '\n' && i == input.Length - 1 && sourceState.StartsWithLineAnchor ? builder._minterms!.Length : normalMintermId; // mintermId = minterms.Length represents \Z (last \n) TSetType minterm = builder.GetMinterm(mintermId); // Get or create the transitions int offset = (sourceId << builder._mintermsLog) | mintermId; Debug.Assert(builder._capturingDelta is not null); List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)>? transitions = builder._capturingDelta[offset] ?? CreateNewCapturingTransitions(sourceState, minterm, offset); // Take the transitions in their prioritized order for (int j = 0; j < transitions.Count; ++j) { (DfaMatchingState<TSetType> targetState, List<DerivativeEffect> effects) = transitions[j]; if (targetState.IsDeadend) continue; // Try to add the state and handle the case where it didn't exist before. If the state already // exists, then the transition can be safely ignored, as the existing state was generated by a // higher priority transition. if (next.Add(targetState.Id, out int index)) { // Avoid copying the registers on the last transition from this state, reusing the registers instead Registers newRegisters = j != transitions.Count - 1 ? sourceRegisters.Clone() : sourceRegisters; newRegisters.ApplyEffects(effects, i); next.Update(index, targetState.Id, newRegisters); if (targetState.IsNullable(GetCharKind(input, i + 1))) { // Accepting state has been reached. Record the position. i_end = i; endRegisters.Assign(newRegisters); endState = targetState; // No lower priority transitions from this or other source states are taken because the // backtracking engines would return the match ending here. goto BreakNullable; } } } } BreakNullable: if (next.Count == 0) { // If all states died out some nullable state must have been seen before break; } // Swap the state sets and prepare for the next character SparseIntMap<Registers> tmp = current; current = next; next = tmp; next.Clear(); i++; } Debug.Assert(i_end != input.Length && endState is not null); // Apply effects for finishing at the stored end state endState.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i_end + 1), CharKind.Context(endState.PrevCharKind, GetCharKind(input, i_end + 1))); resultRegisters = endRegisters; return i_end; } /// <summary> /// Phase 2 of matching. From a found ending position, walk in reverse through the input using the reverse pattern to find the /// start position of match. /// </summary> /// <remarks> /// The start position is known to exist; this function just needs to determine exactly what it is. /// We need to find the earliest (lowest index) starting position that's not earlier than <paramref name="matchStartBoundary"/>. /// </remarks> /// <param name="input">The input text.</param> /// <param name="i">The ending position to walk backwards from. <paramref name="i"/> points at the last character of the match.</param> /// <param name="matchStartBoundary">The initial starting location discovered in phase 1, a point we must not walk earlier than.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The found starting position for the match.</returns> private int FindStartPosition(ReadOnlySpan<char> input, int i, int matchStartBoundary, PerThreadData perThreadData) { Debug.Assert(i >= 0, $"{nameof(i)} == {i}"); Debug.Assert(matchStartBoundary >= 0 && matchStartBoundary < input.Length, $"{nameof(matchStartBoundary)} == {matchStartBoundary}"); Debug.Assert(i >= matchStartBoundary, $"Expected {i} >= {matchStartBoundary}."); // Get the starting state for the reverse pattern. This depends on previous character (which, because we're // going backwards, is character number i + 1). var currentState = new CurrentState(_reverseInitialStates[GetCharKind(input, i + 1)]); // If the initial state is nullable, meaning it accepts the empty string, then we've already discovered // a valid starting position, and we just need to keep looking for an earlier one in case there is one. int lastStart = -1; // invalid sentinel value if (currentState.DfaState!.IsNullable(GetCharKind(input, i))) { lastStart = i + 1; } // Walk backwards to the furthest accepting state of the reverse pattern but no earlier than matchStartBoundary. SymbolicRegexBuilder<TSetType> builder = currentState.DfaState.Node._builder; while (true) { // Run the DFA or NFA traversal backwards from the current point using the current state. bool done = currentState.NfaState is not null ? FindStartPositionDeltas<NfaStateHandler>(builder, input, ref i, matchStartBoundary, ref currentState, ref lastStart) : FindStartPositionDeltas<DfaStateHandler>(builder, input, ref i, matchStartBoundary, ref currentState, ref lastStart); // If we found the starting position, we're done. if (done) { break; } // We didn't find the starting position but we did exit out of the backwards traversal. That should only happen // if we were unable to transition, which should only happen if we were in DFA mode and exceeded our graph size. // Upgrade to NFA mode and continue. Debug.Assert(i >= matchStartBoundary); Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } Debug.Assert(lastStart != -1, "We expected to find a starting position but didn't."); return lastStart; } /// <summary> /// Workhorse inner loop for <see cref="FindStartPosition"/>. Consumes the <paramref name="input"/> character by character in reverse, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> private bool FindStartPositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, int startThreshold, ref CurrentState currentState, ref int lastStart) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Loop backwards through each character in the input, transitioning from state to state for each. while (TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { // We successfully transitioned. If the new state is a dead end, we're done, as we must have already seen // and recorded a larger lastStart value that was the earliest valid starting position. if (TStateHandler.IsDeadend(ref state)) { Debug.Assert(lastStart != -1); currentState = state; i = pos; return true; } // If the new state accepts the empty string, we found a valid starting position. Record it and keep going, // since we're looking for the earliest one to occur within bounds. if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos - 1))) { lastStart = pos; } // Since we successfully transitioned, update our current index to match the fact that we consumed the previous character in the input. pos--; // If doing so now puts us below the start threshold, bail; we should have already found a valid starting location. if (pos < startThreshold) { Debug.Assert(lastStart != -1); currentState = state; i = pos; return true; } } // Unable to transition further. currentState = state; i = pos; return false; } /// <summary>Performs the initial Phase 1 match to find the first final state encountered.</summary> /// <param name="input">The input text.</param> /// <param name="i">The starting position in <paramref name="input"/>.</param> /// <param name="timeoutOccursAt">The time at which timeout occurs, if timeouts are being checked.</param> /// <param name="initialStateIndex">The last position the initial state of <see cref="_dotStarredPattern"/> was visited.</param> /// <param name="matchLength">Length of the match if there's a match; otherwise, -1.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The index into input that matches the final state, or NoMatchExists if no match exists. It returns -1 when i=0 and the initial state is nullable.</returns> private int FindFinalStatePosition(ReadOnlySpan<char> input, int i, int timeoutOccursAt, out int initialStateIndex, out int matchLength, PerThreadData perThreadData) { matchLength = -1; initialStateIndex = i; // Start with the start state of the dot-star pattern, which in general depends on the previous character kind in the input in order to handle anchors. // If the starting state is a dead end, then no match exists. var currentState = new CurrentState(_dotstarredInitialStates[GetCharKind(input, i - 1)]); if (currentState.DfaState!.IsNothing) { // This can happen, for example, when the original regex starts with a beginning anchor but the previous char kind is not Beginning. return NoMatchExists; } // If the starting state accepts the empty string in this context (factoring in anchors), we're done. if (currentState.DfaState.IsNullable(GetCharKind(input, i))) { // The initial state is nullable in this context so at least an empty match exists. // The last position of the match is i - 1 because the match is empty. // This value is -1 if i == 0. return i - 1; } // Otherwise, start searching from the current position until the end of the input. if ((uint)i < (uint)input.Length) { SymbolicRegexBuilder<TSetType> builder = currentState.DfaState.Node._builder; while (true) { // If we're at an initial state, try to search ahead for the next possible match location // using any find optimizations that may have previously been computed. if (currentState.DfaState is { IsInitialState: true }) { // i is the most recent position in the input when the dot-star pattern is in the initial state initialStateIndex = i; if (_findOpts is RegexFindOptimizations findOpts) { // Find the first position i that matches with some likely character. if (!findOpts.TryFindNextStartingPosition(input, ref i, 0, 0, input.Length)) { // no match was found return NoMatchExists; } initialStateIndex = i; // Update the starting state based on where TryFindNextStartingPosition moved us to. // As with the initial starting state, if it's a dead end, no match exists. currentState = new CurrentState(_dotstarredInitialStates[GetCharKind(input, i - 1)]); if (currentState.DfaState!.IsNothing) { return NoMatchExists; } } } // Now run the DFA or NFA traversal from the current point using the current state. int finalStatePosition; int findResult = currentState.NfaState is not null ? FindFinalStatePositionDeltas<NfaStateHandler>(builder, input, ref i, ref currentState, ref matchLength, out finalStatePosition) : FindFinalStatePositionDeltas<DfaStateHandler>(builder, input, ref i, ref currentState, ref matchLength, out finalStatePosition); // If we reached a final or deadend state, we're done. if (findResult > 0) { return finalStatePosition; } // We're not at an end state, so we either ran out of input (in which case no match exists), hit an initial state (in which case // we want to loop around to apply our initial state processing logic and optimizations), or failed to transition (which should // only happen if we were in DFA mode and need to switch over to NFA mode). If we exited because we hit an initial state, // find result will be 0, otherwise negative. if (findResult < 0) { if ((uint)i >= (uint)input.Length) { // We ran out of input. No match. break; } // We failed to transition. Upgrade to DFA mode. Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } // Check for a timeout before continuing. if (_checkTimeout) { DoCheckTimeout(timeoutOccursAt); } } } // No match was found. return NoMatchExists; } /// <summary> /// Workhorse inner loop for <see cref="FindFinalStatePosition"/>. Consumes the <paramref name="input"/> character by character, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> /// <remarks> /// The <typeparamref name="TStateHandler"/> supplies the actual transitioning logic, controlling whether processing is /// performed in DFA mode or in NFA mode. However, it expects <paramref name="currentState"/> to be configured to match, /// so for example if <typeparamref name="TStateHandler"/> is a <see cref="DfaStateHandler"/>, it expects the <paramref name="currentState"/>'s /// <see cref="CurrentState.DfaState"/> to be non-null and its <see cref="CurrentState.NfaState"/> to be null; vice versa for /// <see cref="NfaStateHandler"/>. /// </remarks> /// <returns> /// A positive value if iteration completed because it reached a nullable or deadend state. /// 0 if iteration completed because we reached an initial state. /// A negative value if iteration completed because we ran out of input or we failed to transition. /// </returns> private int FindFinalStatePositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, ref CurrentState currentState, ref int matchLength, out int finalStatePosition) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Loop through each character in the input, transitioning from state to state for each. while ((uint)pos < (uint)input.Length && TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { // We successfully transitioned for the character at index i. If the new state is nullable for // the next character, meaning it accepts the empty string, we found a final state and are done! if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos + 1))) { // Check whether there's a fixed-length marker for the current state. If there is, we can // use that length to optimize subsequent matching phases. matchLength = TStateHandler.FixedLength(ref state); currentState = state; i = pos; finalStatePosition = pos; return 1; } // If the new state is a dead end, such that we didn't match and we can't transition anywhere // else, then no match exists. if (TStateHandler.IsDeadend(ref state)) { currentState = state; i = pos; finalStatePosition = NoMatchExists; return 1; } // We successfully transitioned, so update our current input index to match. pos++; // Now that currentState and our position are coherent, check if currentState represents an initial state. // If it does, we exit out in order to allow our find optimizations to kick in to hopefully more quickly // find the next possible starting location. if (TStateHandler.IsInitialState(ref state)) { currentState = state; i = pos; finalStatePosition = 0; return 0; } } currentState = state; i = pos; finalStatePosition = 0; return -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private uint GetCharKind(ReadOnlySpan<char> input, int i) { return !_pattern._info.ContainsSomeAnchor ? CharKind.General : // The previous character kind is irrelevant when anchors are not used. GetCharKindWithAnchor(input, i); uint GetCharKindWithAnchor(ReadOnlySpan<char> input, int i) { Debug.Assert(_asciiCharKinds is not null); if ((uint)i >= (uint)input.Length) { return CharKind.BeginningEnd; } char nextChar = input[i]; if (nextChar == '\n') { return _builder._newLinePredicate.Equals(_builder._solver.False) ? 0 : // ignore \n i == 0 || i == input.Length - 1 ? CharKind.NewLineS : // very first or very last \n. Detection of very first \n is needed for rev(\Z). CharKind.Newline; } uint[] asciiCharKinds = _asciiCharKinds; return nextChar < (uint)asciiCharKinds.Length ? asciiCharKinds[nextChar] : _builder._solver.And(GetMinterm(nextChar), _builder._wordLetterPredicateForAnchors).Equals(_builder._solver.False) ? 0 : //apply the wordletter predicate to compute the kind of the next character CharKind.WordLetter; } } /// <summary>Stores additional data for tracking capture start and end positions.</summary> /// <remarks>The NFA simulation based third phase has one of these for each current state in the current set of live states.</remarks> internal struct Registers { public Registers(int[] captureStarts, int[] captureEnds) { CaptureStarts = captureStarts; CaptureEnds = captureEnds; } public int[] CaptureStarts { get; set; } public int[] CaptureEnds { get; set; } /// <summary> /// Applies a list of effects in order to these registers at the provided input position. The order of effects /// should not matter though, as multiple effects to the same capture start or end do not arise. /// </summary> /// <param name="effects">list of effects to be applied</param> /// <param name="pos">the current input position to record</param> public void ApplyEffects(List<DerivativeEffect> effects, int pos) { foreach (DerivativeEffect effect in effects) { ApplyEffect(effect, pos); } } /// <summary> /// Apply a single effect to these registers at the provided input position. /// </summary> /// <param name="effect">the effecto to be applied</param> /// <param name="pos">the current input position to record</param> public void ApplyEffect(DerivativeEffect effect, int pos) { switch (effect.Kind) { case DerivativeEffectKind.CaptureStart: CaptureStarts[effect.CaptureNumber] = pos; break; case DerivativeEffectKind.CaptureEnd: CaptureEnds[effect.CaptureNumber] = pos; break; } } /// <summary> /// Make a copy of this set of registers. /// </summary> /// <returns>Registers pointing to copies of this set of registers</returns> public Registers Clone() => new Registers((int[])CaptureStarts.Clone(), (int[])CaptureEnds.Clone()); /// <summary> /// Copy register values from another set of registers, possibly allocating new arrays if they were not yet allocated. /// </summary> /// <param name="other">the registers to copy from</param> public void Assign(Registers other) { if (CaptureStarts is not null && CaptureEnds is not null) { Debug.Assert(CaptureStarts.Length == other.CaptureStarts.Length); Debug.Assert(CaptureEnds.Length == other.CaptureEnds.Length); Array.Copy(other.CaptureStarts, CaptureStarts, CaptureStarts.Length); Array.Copy(other.CaptureEnds, CaptureEnds, CaptureEnds.Length); } else { CaptureStarts = (int[])other.CaptureStarts.Clone(); CaptureEnds = (int[])other.CaptureEnds.Clone(); } } } /// <summary> /// Per thread data to be held by the regex runner and passed into every call to FindMatch. This is used to /// avoid repeated memory allocation. /// </summary> internal sealed class PerThreadData { public readonly NfaMatchingState NfaState; /// <summary>Maps used for the capturing third phase.</summary> public readonly SparseIntMap<Registers>? Current, Next; /// <summary>Registers used for the capturing third phase.</summary> public readonly Registers InitialRegisters; public PerThreadData(SymbolicRegexBuilder<TSetType> builder, int capsize) { NfaState = new NfaMatchingState(builder); // Only create data used for capturing mode if there are subcaptures if (capsize > 1) { Current = new(); Next = new(); InitialRegisters = new Registers(new int[capsize], new int[capsize]); } } } /// <summary>Stores the state that represents a current state in NFA mode.</summary> /// <remarks>The entire state is composed of a list of individual states.</remarks> internal sealed class NfaMatchingState { /// <summary>The associated builder used to lazily add new DFA or NFA nodes to the graph.</summary> public readonly SymbolicRegexBuilder<TSetType> Builder; /// <summary>Ordered set used to store the current NFA states.</summary> /// <remarks>The value is unused. The type is used purely for its keys.</remarks> public SparseIntMap<int> NfaStateSet = new(); /// <summary>Scratch set to swap with <see cref="NfaStateSet"/> on each transition.</summary> /// <remarks> /// On each transition, <see cref="NfaStateSetScratch"/> is cleared and filled with the next /// states computed from the current states in <see cref="NfaStateSet"/>, and then the sets /// are swapped so the scratch becomes the current and the current becomes the scratch. /// </remarks> public SparseIntMap<int> NfaStateSetScratch = new(); /// <summary>Create the instance.</summary> /// <remarks>New instances should only be created once per runner.</remarks> public NfaMatchingState(SymbolicRegexBuilder<TSetType> builder) => Builder = builder; /// <summary>Resets this NFA state to represent the supplied DFA state.</summary> /// <param name="dfaMatchingState">The DFA state to use to initialize the NFA state.</param> public void InitializeFrom(DfaMatchingState<TSetType> dfaMatchingState) { NfaStateSet.Clear(); // If the DFA state is a union of multiple DFA states, loop through all of them // adding an NFA state for each. if (dfaMatchingState.Node.Kind is SymbolicRegexNodeKind.Or) { Debug.Assert(dfaMatchingState.Node._alts is not null); foreach (SymbolicRegexNode<TSetType> node in dfaMatchingState.Node._alts) { // Create (possibly new) NFA states for all the members. // Add their IDs to the current set of NFA states and into the list. int nfaState = Builder.CreateNfaState(node, dfaMatchingState.PrevCharKind); NfaStateSet.Add(nfaState, out _); } } else { // Otherwise, just add an NFA state for the singular DFA state. SymbolicRegexNode<TSetType> node = dfaMatchingState.Node; int nfaState = Builder.CreateNfaState(node, dfaMatchingState.PrevCharKind); NfaStateSet.Add(nfaState, out _); } } } /// <summary>Represents a current state in a DFA or NFA graph walk while processing a regular expression.</summary> /// <remarks>This is a discriminated union between a DFA state and an NFA state. One and only one will be non-null.</remarks> private struct CurrentState { /// <summary>Initializes the state as a DFA state.</summary> public CurrentState(DfaMatchingState<TSetType> dfaState) { DfaState = dfaState; NfaState = null; } /// <summary>Initializes the state as an NFA state.</summary> public CurrentState(NfaMatchingState nfaState) { DfaState = null; NfaState = nfaState; } /// <summary>The DFA state.</summary> public DfaMatchingState<TSetType>? DfaState; /// <summary>The NFA state.</summary> public NfaMatchingState? NfaState; } /// <summary>Represents a set of routines for operating over a <see cref="CurrentState"/>.</summary> private interface IStateHandler { #pragma warning disable CA2252 // This API requires opting into preview features public static abstract bool StartsWithLineAnchor(ref CurrentState state); public static abstract bool IsNullable(ref CurrentState state, uint nextCharKind); public static abstract bool IsDeadend(ref CurrentState state); public static abstract int FixedLength(ref CurrentState state); public static abstract bool IsInitialState(ref CurrentState state); public static abstract bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId); #pragma warning restore CA2252 // This API requires opting into preview features } /// <summary>An <see cref="IStateHandler"/> for operating over <see cref="CurrentState"/> instances configured as DFA states.</summary> private readonly struct DfaStateHandler : IStateHandler { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWithLineAnchor(ref CurrentState state) => state.DfaState!.StartsWithLineAnchor; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullable(ref CurrentState state, uint nextCharKind) => state.DfaState!.IsNullable(nextCharKind); /// <summary>Gets whether this is a dead-end state, meaning there are no transitions possible out of the state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDeadend(ref CurrentState state) => state.DfaState!.IsDeadend; /// <summary>Gets the length of any fixed-length marker that exists for this state, or -1 if there is none.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FixedLength(ref CurrentState state) => state.DfaState!.FixedLength; /// <summary>Gets whether this is an initial state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInitialState(ref CurrentState state) => state.DfaState!.IsInitialState; /// <summary>Take the transition to the next DFA state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId) { Debug.Assert(state.DfaState is not null, $"Expected non-null {nameof(state.DfaState)}."); Debug.Assert(state.NfaState is null, $"Expected null {nameof(state.NfaState)}."); Debug.Assert(builder._delta is not null); // Get the current state. DfaMatchingState<TSetType> dfaMatchingState = state.DfaState!; // Use the mintermId for the character being read to look up which state to transition to. // If that state has already been materialized, move to it, and we're done. If that state // hasn't been materialized, try to create it; if we can, move to it, and we're done. int dfaOffset = (dfaMatchingState.Id << builder._mintermsLog) | mintermId; DfaMatchingState<TSetType>? nextState = builder._delta[dfaOffset]; if (nextState is not null || builder.TryCreateNewTransition(dfaMatchingState, mintermId, dfaOffset, checkThreshold: true, out nextState)) { // There was an existing state for this transition or we were able to create one. Move to it and // return that we're still operating as a DFA and can keep going. state.DfaState = nextState; return true; } return false; } } /// <summary>An <see cref="IStateHandler"/> for operating over <see cref="CurrentState"/> instances configured as NFA states.</summary> private readonly struct NfaStateHandler : IStateHandler { /// <summary>Check if any underlying core state starts with a line anchor.</summary> public static bool StartsWithLineAnchor(ref CurrentState state) { SymbolicRegexBuilder<TSetType> builder = state.NfaState!.Builder; foreach (ref KeyValuePair<int, int> nfaState in CollectionsMarshal.AsSpan(state.NfaState!.NfaStateSet.Values)) { if (builder.GetCoreState(nfaState.Key).StartsWithLineAnchor) { return true; } } return false; } /// <summary>Check if any underlying core state is nullable.</summary> public static bool IsNullable(ref CurrentState state, uint nextCharKind) { SymbolicRegexBuilder<TSetType> builder = state.NfaState!.Builder; foreach (ref KeyValuePair<int, int> nfaState in CollectionsMarshal.AsSpan(state.NfaState!.NfaStateSet.Values)) { if (builder.GetCoreState(nfaState.Key).IsNullable(nextCharKind)) { return true; } } return false; } /// <summary>Gets whether this is a dead-end state, meaning there are no transitions possible out of the state.</summary> /// <remarks>In NFA mode, an empty set of states means that it is a dead end.</remarks> public static bool IsDeadend(ref CurrentState state) => state.NfaState!.NfaStateSet.Count == 0; /// <summary>Gets the length of any fixed-length marker that exists for this state, or -1 if there is none.</summary> /// <summary>In NFA mode, there are no fixed-length markers.</summary> public static int FixedLength(ref CurrentState state) => -1; /// <summary>Gets whether this is an initial state.</summary> /// <summary>In NFA mode, no set of states qualifies as an initial state.</summary> public static bool IsInitialState(ref CurrentState state) => false; /// <summary>Take the transition to the next NFA state.</summary> public static bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId) { Debug.Assert(state.DfaState is null, $"Expected null {nameof(state.DfaState)}."); Debug.Assert(state.NfaState is not null, $"Expected non-null {nameof(state.NfaState)}."); NfaMatchingState nfaState = state.NfaState!; // Grab the sets, swapping the current active states set with the scratch set. SparseIntMap<int> nextStates = nfaState.NfaStateSetScratch; SparseIntMap<int> sourceStates = nfaState.NfaStateSet; nfaState.NfaStateSet = nextStates; nfaState.NfaStateSetScratch = sourceStates; // Compute the set of all unique next states from the current source states and the mintermId. nextStates.Clear(); if (sourceStates.Count == 1) { // We have a single source state. We know its next states are already deduped, // so we can just add them directly to the destination states list. foreach (int nextState in GetNextStates(sourceStates.Values[0].Key, mintermId, builder)) { nextStates.Add(nextState, out _); } } else { // We have multiple source states, so we need to potentially dedup across each of // their next states. For each source state, get its next states, adding each into // our set (which exists purely for deduping purposes), and if we successfully added // to the set, then add the known-unique state to the destination list. foreach (ref KeyValuePair<int, int> sourceState in CollectionsMarshal.AsSpan(sourceStates.Values)) { foreach (int nextState in GetNextStates(sourceState.Key, mintermId, builder)) { nextStates.Add(nextState, out _); } } } return true; [MethodImpl(MethodImplOptions.AggressiveInlining)] static int[] GetNextStates(int sourceState, int mintermId, SymbolicRegexBuilder<TSetType> builder) { // Calculate the offset into the NFA transition table. int nfaOffset = (sourceState << builder._mintermsLog) | mintermId; // Get the next NFA state. return builder._nfaDelta[nfaOffset] ?? builder.CreateNewNfaTransition(sourceState, mintermId, nfaOffset); } } } #if DEBUG public override void SaveDGML(TextWriter writer, int bound, bool hideStateInfo, bool addDotStar, bool inReverse, bool onlyDFAinfo, int maxLabelLength, bool asNFA) { var graph = new DGML.RegexAutomaton<TSetType>(this, bound, addDotStar, inReverse, asNFA); var dgml = new DGML.DgmlWriter(writer, hideStateInfo, maxLabelLength, onlyDFAinfo); dgml.Write(graph); } public override IEnumerable<string> GenerateRandomMembers(int k, int randomseed, bool negative) => new SymbolicRegexSampler<TSetType>(_pattern, randomseed, negative).GenerateRandomMembers(k); #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents a regex matching engine that performs regex matching using symbolic derivatives.</summary> internal abstract class SymbolicRegexMatcher { #if DEBUG /// <summary>Unwind the regex of the matcher and save the resulting state graph in DGML</summary> /// <param name="bound">roughly the maximum number of states, 0 means no bound</param> /// <param name="hideStateInfo">if true then hide state info</param> /// <param name="addDotStar">if true then pretend that there is a .* at the beginning</param> /// <param name="inReverse">if true then unwind the regex backwards (addDotStar is then ignored)</param> /// <param name="onlyDFAinfo">if true then compute and save only genral DFA info</param> /// <param name="writer">dgml output is written here</param> /// <param name="maxLabelLength">maximum length of labels in nodes anything over that length is indicated with .. </param> /// <param name="asNFA">if true creates NFA instead of DFA</param> public abstract void SaveDGML(TextWriter writer, int bound, bool hideStateInfo, bool addDotStar, bool inReverse, bool onlyDFAinfo, int maxLabelLength, bool asNFA); /// <summary> /// Generates up to k random strings matched by the regex /// </summary> /// <param name="k">upper bound on the number of generated strings</param> /// <param name="randomseed">random seed for the generator, 0 means no random seed</param> /// <param name="negative">if true then generate inputs that do not match</param> /// <returns></returns> public abstract IEnumerable<string> GenerateRandomMembers(int k, int randomseed, bool negative); #endif } /// <summary>Represents a regex matching engine that performs regex matching using symbolic derivatives.</summary> /// <typeparam name="TSetType">Character set type.</typeparam> internal sealed class SymbolicRegexMatcher<TSetType> : SymbolicRegexMatcher where TSetType : notnull { /// <summary>Maximum number of built states before switching over to NFA mode.</summary> /// <remarks> /// By default, all matching starts out using DFAs, where every state transitions to one and only one /// state for any minterm (each character maps to one minterm). Some regular expressions, however, can result /// in really, really large DFA state graphs, much too big to actually store. Instead of failing when we /// encounter such state graphs, at some point we instead switch from processing as a DFA to processing as /// an NFA. As an NFA, we instead track all of the states we're in at any given point, and transitioning /// from one "state" to the next really means for every constituent state that composes our current "state", /// we find all possible states that transitioning out of each of them could result in, and the union of /// all of those is our new "state". This constant represents the size of the graph after which we start /// processing as an NFA instead of as a DFA. This processing doesn't change immediately, however. All /// processing starts out in DFA mode, even if we've previously triggered NFA mode for the same regex. /// We switch over into NFA mode the first time a given traversal (match operation) results in us needing /// to create a new node and the graph is already or newly beyond this threshold. /// </remarks> internal const int NfaThreshold = 10_000; /// <summary>Sentinel value used internally by the matcher to indicate no match exists.</summary> private const int NoMatchExists = -2; /// <summary>Builder used to create <see cref="SymbolicRegexNode{S}"/>s while matching.</summary> /// <remarks> /// The builder is used to build up the DFA state space lazily, which means we need to be able to /// produce new <see cref="SymbolicRegexNode{S}"/>s as we match. Once in NFA mode, we also use /// the builder to produce new NFA states. The builder maintains a cache of all DFA and NFA states. /// </remarks> internal readonly SymbolicRegexBuilder<TSetType> _builder; /// <summary>Maps every character to its corresponding minterm ID.</summary> private readonly MintermClassifier _mintermClassifier; /// <summary><see cref="_pattern"/> prefixed with [0-0xFFFF]*</summary> /// <remarks> /// The matching engine first uses <see cref="_dotStarredPattern"/> to find whether there is a match /// and where that match might end. Prepending the .* prefix onto the original pattern provides the DFA /// with the ability to continue to process input characters even if those characters aren't part of /// the match. If Regex.IsMatch is used, nothing further is needed beyond this prefixed pattern. If, however, /// other matching operations are performed that require knowing the exact start and end of the match, /// the engine then needs to process the pattern in reverse to find where the match actually started; /// for that, it uses the <see cref="_reversePattern"/> and walks backwards through the input characters /// from where <see cref="_dotStarredPattern"/> left off. At this point we know that there was a match, /// where it started, and where it could have ended, but that ending point could be influenced by the /// selection of the starting point. So, to find the actual ending point, the original <see cref="_pattern"/> /// is then used from that starting point to walk forward through the input characters again to find the /// actual end point used for the match. /// </remarks> internal readonly SymbolicRegexNode<TSetType> _dotStarredPattern; /// <summary>The original regex pattern.</summary> internal readonly SymbolicRegexNode<TSetType> _pattern; /// <summary>The reverse of <see cref="_pattern"/>.</summary> /// <remarks> /// Determining that there is a match and where the match ends requires only <see cref="_pattern"/>. /// But from there determining where the match began requires reversing the pattern and running /// the matcher again, starting from the ending position. This <see cref="_reversePattern"/> caches /// that reversed pattern used for extracting match start. /// </remarks> internal readonly SymbolicRegexNode<TSetType> _reversePattern; /// <summary>true iff timeout checking is enabled.</summary> private readonly bool _checkTimeout; /// <summary>Timeout in milliseconds. This is only used if <see cref="_checkTimeout"/> is true.</summary> private readonly int _timeout; /// <summary>Data and routines for skipping ahead to the next place a match could potentially start.</summary> private readonly RegexFindOptimizations? _findOpts; /// <summary>The initial states for the original pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _initialStates; /// <summary>The initial states for the dot-star pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _dotstarredInitialStates; /// <summary>The initial states for the reverse pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _reverseInitialStates; /// <summary>Lookup table to quickly determine the character kind for ASCII characters.</summary> /// <remarks>Non-null iff the pattern contains anchors; otherwise, it's unused.</remarks> private readonly uint[]? _asciiCharKinds; /// <summary>Number of capture groups.</summary> private readonly int _capsize; /// <summary>Fixed-length of any possible match.</summary> /// <remarks>This will be null if matches may be of varying lengths or if a fixed-length couldn't otherwise be computed.</remarks> private readonly int? _fixedMatchLength; /// <summary>Gets whether the regular expression contains captures (beyond the implicit root-level capture).</summary> /// <remarks>This determines whether the matcher uses the special capturing NFA simulation mode.</remarks> internal bool HasSubcaptures => _capsize > 1; /// <summary>Get the minterm of <paramref name="c"/>.</summary> /// <param name="c">character code</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] private TSetType GetMinterm(int c) { Debug.Assert(_builder._minterms is not null); return _builder._minterms[_mintermClassifier.GetMintermID(c)]; } /// <summary>Constructs matcher for given symbolic regex.</summary> internal SymbolicRegexMatcher(SymbolicRegexNode<TSetType> sr, RegexTree regexTree, BDD[] minterms, TimeSpan matchTimeout) { Debug.Assert(sr._builder._solver is BitVector64Algebra or BitVectorAlgebra or CharSetSolver, $"Unsupported algebra: {sr._builder._solver}"); _pattern = sr; _builder = sr._builder; _checkTimeout = Regex.InfiniteMatchTimeout != matchTimeout; _timeout = (int)(matchTimeout.TotalMilliseconds + 0.5); // Round up, so it will be at least 1ms _mintermClassifier = _builder._solver switch { BitVector64Algebra bv64 => bv64._classifier, BitVectorAlgebra bv => bv._classifier, _ => new MintermClassifier((CharSetSolver)(object)_builder._solver, minterms), }; _capsize = regexTree.CaptureCount; if (regexTree.FindOptimizations.MinRequiredLength == regexTree.FindOptimizations.MaxPossibleLength) { _fixedMatchLength = regexTree.FindOptimizations.MinRequiredLength; } if (regexTree.FindOptimizations.FindMode != FindNextStartingPositionMode.NoSearch && regexTree.FindOptimizations.LeadingAnchor == 0) // If there are any anchors, we're better off letting the DFA quickly do its job of determining whether there's a match. { _findOpts = regexTree.FindOptimizations; } // Determine the number of initial states. If there's no anchor, only the default previous // character kind 0 is ever going to be used for all initial states. int statesCount = _pattern._info.ContainsSomeAnchor ? CharKind.CharKindCount : 1; // Create the initial states for the original pattern. var initialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < initialStates.Length; i++) { initialStates[i] = _builder.CreateState(_pattern, i, capturing: HasSubcaptures); } _initialStates = initialStates; // Create the dot-star pattern (a concatenation of any* with the original pattern) // and all of its initial states. SymbolicRegexNode<TSetType> unorderedPattern = _pattern.IgnoreOrOrderAndLazyness(); _dotStarredPattern = _builder.CreateConcat(_builder._anyStar, unorderedPattern); var dotstarredInitialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < dotstarredInitialStates.Length; i++) { // Used to detect if initial state was reentered, // but observe that the behavior from the state may ultimately depend on the previous // input char e.g. possibly causing nullability of \b or \B or of a start-of-line anchor, // in that sense there can be several "versions" (not more than StateCount) of the initial state. DfaMatchingState<TSetType> state = _builder.CreateState(_dotStarredPattern, i, capturing: false); state.IsInitialState = true; dotstarredInitialStates[i] = state; } _dotstarredInitialStates = dotstarredInitialStates; // Create the reverse pattern (the original pattern in reverse order) and all of its // initial states. _reversePattern = unorderedPattern.Reverse(); var reverseInitialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < reverseInitialStates.Length; i++) { reverseInitialStates[i] = _builder.CreateState(_reversePattern, i, capturing: false); } _reverseInitialStates = reverseInitialStates; // Initialize our fast-lookup for determining the character kind of ASCII characters. // This is only required when the pattern contains anchors, as otherwise there's only // ever a single kind used. if (_pattern._info.ContainsSomeAnchor) { var asciiCharKinds = new uint[128]; for (int i = 0; i < asciiCharKinds.Length; i++) { TSetType predicate2; uint charKind; if (i == '\n') { predicate2 = _builder._newLinePredicate; charKind = CharKind.Newline; } else { predicate2 = _builder._wordLetterPredicateForAnchors; charKind = CharKind.WordLetter; } asciiCharKinds[i] = _builder._solver.And(GetMinterm(i), predicate2).Equals(_builder._solver.False) ? 0 : charKind; } _asciiCharKinds = asciiCharKinds; } } /// <summary> /// Create a PerThreadData with the appropriate parts initialized for this matcher's pattern. /// </summary> internal PerThreadData CreatePerThreadData() => new PerThreadData(_builder, _capsize); /// <summary>Compute the target state for the source state and input[i] character and transition to it.</summary> /// <param name="builder">The associated builder.</param> /// <param name="input">The input text.</param> /// <param name="i">The index into <paramref name="input"/> at which the target character lives.</param> /// <param name="state">The current state being transitioned from. Upon return it's the new state if the transition succeeded.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryTakeTransition<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, int i, ref CurrentState state) where TStateHandler : struct, IStateHandler { int c = input[i]; int mintermId = c == '\n' && i == input.Length - 1 && TStateHandler.StartsWithLineAnchor(ref state) ? builder._minterms!.Length : // mintermId = minterms.Length represents \Z (last \n) _mintermClassifier.GetMintermID(c); return TStateHandler.TakeTransition(builder, ref state, mintermId); } private List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)> CreateNewCapturingTransitions(DfaMatchingState<TSetType> state, TSetType minterm, int offset) { Debug.Assert(_builder._capturingDelta is not null); lock (this) { // Get the next state if it exists. The caller should have already tried and found it null (not yet created), // but in the interim another thread could have created it. List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)>? p = _builder._capturingDelta[offset]; if (p is null) { // Build the new state and store it into the array. p = state.NfaEagerNextWithEffects(minterm); Volatile.Write(ref _builder._capturingDelta[offset], p); } return p; } } private void DoCheckTimeout(int timeoutOccursAt) { // This logic is identical to RegexRunner.DoCheckTimeout, with the exception of check skipping. RegexRunner calls // DoCheckTimeout potentially on every iteration of a loop, whereas this calls it only once per transition. int currentMillis = Environment.TickCount; if (currentMillis >= timeoutOccursAt && (0 <= timeoutOccursAt || 0 >= currentMillis)) { throw new RegexMatchTimeoutException(string.Empty, string.Empty, TimeSpan.FromMilliseconds(_timeout)); } } /// <summary>Find a match.</summary> /// <param name="isMatch">Whether to return once we know there's a match without determining where exactly it matched.</param> /// <param name="input">The input span</param> /// <param name="startat">The position to start search in the input span.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> public SymbolicMatch FindMatch(bool isMatch, ReadOnlySpan<char> input, int startat, PerThreadData perThreadData) { Debug.Assert(startat >= 0 && startat <= input.Length, $"{nameof(startat)} == {startat}, {nameof(input.Length)} == {input.Length}"); Debug.Assert(perThreadData is not null); // If we need to perform timeout checks, store the absolute timeout value. int timeoutOccursAt = 0; if (_checkTimeout) { // Using Environment.TickCount for efficiency instead of Stopwatch -- as in the non-DFA case. timeoutOccursAt = Environment.TickCount + (int)(_timeout + 0.5); } // If we're starting at the end of the input, we don't need to do any work other than // determine whether an empty match is valid, i.e. whether the pattern is "nullable" // given the kinds of characters at and just before the end. if (startat == input.Length) { // TODO https://github.com/dotnet/runtime/issues/65606: Handle capture groups. uint prevKind = GetCharKind(input, startat - 1); uint nextKind = GetCharKind(input, startat); return _pattern.IsNullableFor(CharKind.Context(prevKind, nextKind)) ? new SymbolicMatch(startat, 0) : SymbolicMatch.NoMatch; } // Phase 1: // Determine whether there is a match by finding the first final state position. This only tells // us whether there is a match but needn't give us the longest possible match. This may return -1 as // a legitimate value when the initial state is nullable and startat == 0. It returns NoMatchExists (-2) // when there is no match. As an example, consider the pattern a{5,10}b* run against an input // of aaaaaaaaaaaaaaabbbc: phase 1 will find the position of the first b: aaaaaaaaaaaaaaab. int i = FindFinalStatePosition(input, startat, timeoutOccursAt, out int matchStartLowBoundary, out int matchStartLengthMarker, perThreadData); // If there wasn't a match, we're done. if (i == NoMatchExists) { return SymbolicMatch.NoMatch; } // A match exists. If we don't need further details, because IsMatch was used (and thus we don't // need the exact bounds of the match, captures, etc.), we're done. if (isMatch) { return SymbolicMatch.QuickMatch; } // Phase 2: // Match backwards through the input matching against the reverse of the pattern, looking for the earliest // start position. That tells us the actual starting position of the match. We can skip this phase if we // recorded a fixed-length marker for the portion of the pattern that matched, as we can then jump that // exact number of positions backwards. Continuing the previous example, phase 2 will walk backwards from // that first b until it finds the 6th a: aaaaaaaaaab. int matchStart; if (matchStartLengthMarker >= 0) { matchStart = i - matchStartLengthMarker + 1; } else { Debug.Assert(i >= startat - 1); matchStart = i < startat ? startat : FindStartPosition(input, i, matchStartLowBoundary, perThreadData); } // Phase 3: // Match again, this time from the computed start position, to find the latest end position. That start // and end then represent the bounds of the match. If the pattern has subcaptures (captures other than // the top-level capture for the whole match), we need to do more work to compute their exact bounds, so we // take a faster path if captures aren't required. Further, if captures aren't needed, and if any possible // match of the whole pattern is a fixed length, we can skip this phase as well, just using that fixed-length // to compute the ending position based on the starting position. Continuing the previous example, phase 3 // will walk forwards from the 6th a until it finds the end of the match: aaaaaaaaaabbb. if (!HasSubcaptures) { if (_fixedMatchLength.HasValue) { return new SymbolicMatch(matchStart, _fixedMatchLength.GetValueOrDefault()); } int matchEnd = FindEndPosition(input, matchStart, perThreadData); return new SymbolicMatch(matchStart, matchEnd + 1 - matchStart); } else { int matchEnd = FindEndPositionCapturing(input, matchStart, out Registers endRegisters, perThreadData); return new SymbolicMatch(matchStart, matchEnd + 1 - matchStart, endRegisters.CaptureStarts, endRegisters.CaptureEnds); } } /// <summary>Phase 3 of matching. From a found starting position, find the ending position of the match using the original pattern.</summary> /// <remarks> /// The ending position is known to exist; this function just needs to determine exactly what it is. /// We need to find the longest possible match and thus the latest valid ending position. /// </remarks> /// <param name="input">The input text.</param> /// <param name="i">The starting position of the match.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The found ending position of the match.</returns> private int FindEndPosition(ReadOnlySpan<char> input, int i, PerThreadData perThreadData) { // Get the starting state based on the current context. DfaMatchingState<TSetType> dfaStartState = _initialStates[GetCharKind(input, i - 1)]; // If the starting state is nullable (accepts the empty string), then it's a valid // match and we need to record the position as a possible end, but keep going looking // for a better one. int end = input.Length; // invalid sentinel value if (dfaStartState.IsNullable(GetCharKind(input, i))) { // Empty match exists because the initial state is accepting. end = i - 1; } if ((uint)i < (uint)input.Length) { // Iterate from the starting state until we've found the best ending state. SymbolicRegexBuilder<TSetType> builder = dfaStartState.Node._builder; var currentState = new CurrentState(dfaStartState); while (true) { // Run the DFA or NFA traversal backwards from the current point using the current state. bool done = currentState.NfaState is not null ? FindEndPositionDeltas<NfaStateHandler>(builder, input, ref i, ref currentState, ref end) : FindEndPositionDeltas<DfaStateHandler>(builder, input, ref i, ref currentState, ref end); // If we successfully found the ending position, we're done. if (done || (uint)i >= (uint)input.Length) { break; } // We exited out of the inner processing loop, but we didn't hit a dead end or run out // of input, and that should only happen if we failed to transition from one state to // the next, which should only happen if we were in DFA mode and we tried to create // a new state and exceeded the graph size. Upgrade to NFA mode and continue; Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } } // Return the found ending position. Debug.Assert(end < input.Length, "Expected to find an ending position but didn't"); return end; } /// <summary> /// Workhorse inner loop for <see cref="FindEndPosition"/>. Consumes the <paramref name="input"/> character by character, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> private bool FindEndPositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, ref CurrentState currentState, ref int endingIndex) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Repeatedly read the next character from the input and use it to transition the current state to the next. // We're looking for the furthest final state we can find. while ((uint)pos < (uint)input.Length && TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos + 1))) { // If the new state accepts the empty string, we found an ending state. Record the position. endingIndex = pos; } else if (TStateHandler.IsDeadend(ref state)) { // If the new state is a dead end, the match ended the last time endingIndex was updated. currentState = state; i = pos; return true; } // We successfully transitioned to the next state and consumed the current character, // so move along to the next. pos++; } // We either ran out of input, in which case we successfully recorded an ending index, // or we failed to transition to the next state due to the graph becoming too large. currentState = state; i = pos; return false; } /// <summary>Find match end position using the original pattern, end position is known to exist. This version also produces captures.</summary> /// <param name="input">input span</param> /// <param name="i">inclusive start position</param> /// <param name="resultRegisters">out parameter for the final register values, which indicate capture starts and ends</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>the match end position</returns> private int FindEndPositionCapturing(ReadOnlySpan<char> input, int i, out Registers resultRegisters, PerThreadData perThreadData) { int i_end = input.Length; Registers endRegisters = default; DfaMatchingState<TSetType>? endState = null; // Pick the correct start state based on previous character kind. DfaMatchingState<TSetType> initialState = _initialStates[GetCharKind(input, i - 1)]; Registers initialRegisters = perThreadData.InitialRegisters; // Initialize registers with -1, which means "not seen yet" Array.Fill(initialRegisters.CaptureStarts, -1); Array.Fill(initialRegisters.CaptureEnds, -1); if (initialState.IsNullable(GetCharKind(input, i))) { // Empty match exists because the initial state is accepting. i_end = i - 1; endRegisters.Assign(initialRegisters); endState = initialState; } // Use two maps from state IDs to register values for the current and next set of states. // Note that these maps use insertion order, which is used to maintain priorities between states in a way // that matches the order the backtracking engines visit paths. Debug.Assert(perThreadData.Current is not null && perThreadData.Next is not null); SparseIntMap<Registers> current = perThreadData.Current, next = perThreadData.Next; current.Clear(); next.Clear(); current.Add(initialState.Id, initialRegisters); SymbolicRegexBuilder<TSetType> builder = _builder; while ((uint)i < (uint)input.Length) { Debug.Assert(next.Count == 0); int c = input[i]; int normalMintermId = _mintermClassifier.GetMintermID(c); foreach ((int sourceId, Registers sourceRegisters) in current.Values) { Debug.Assert(builder._capturingStateArray is not null); DfaMatchingState<TSetType> sourceState = builder._capturingStateArray[sourceId]; // Find the minterm, handling the special case for the last \n int mintermId = c == '\n' && i == input.Length - 1 && sourceState.StartsWithLineAnchor ? builder._minterms!.Length : normalMintermId; // mintermId = minterms.Length represents \Z (last \n) TSetType minterm = builder.GetMinterm(mintermId); // Get or create the transitions int offset = (sourceId << builder._mintermsLog) | mintermId; Debug.Assert(builder._capturingDelta is not null); List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)>? transitions = builder._capturingDelta[offset] ?? CreateNewCapturingTransitions(sourceState, minterm, offset); // Take the transitions in their prioritized order for (int j = 0; j < transitions.Count; ++j) { (DfaMatchingState<TSetType> targetState, List<DerivativeEffect> effects) = transitions[j]; if (targetState.IsDeadend) continue; // Try to add the state and handle the case where it didn't exist before. If the state already // exists, then the transition can be safely ignored, as the existing state was generated by a // higher priority transition. if (next.Add(targetState.Id, out int index)) { // Avoid copying the registers on the last transition from this state, reusing the registers instead Registers newRegisters = j != transitions.Count - 1 ? sourceRegisters.Clone() : sourceRegisters; newRegisters.ApplyEffects(effects, i); next.Update(index, targetState.Id, newRegisters); if (targetState.IsNullable(GetCharKind(input, i + 1))) { // Accepting state has been reached. Record the position. i_end = i; endRegisters.Assign(newRegisters); endState = targetState; // No lower priority transitions from this or other source states are taken because the // backtracking engines would return the match ending here. goto BreakNullable; } } } } BreakNullable: if (next.Count == 0) { // If all states died out some nullable state must have been seen before break; } // Swap the state sets and prepare for the next character SparseIntMap<Registers> tmp = current; current = next; next = tmp; next.Clear(); i++; } Debug.Assert(i_end != input.Length && endState is not null); // Apply effects for finishing at the stored end state endState.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i_end + 1), CharKind.Context(endState.PrevCharKind, GetCharKind(input, i_end + 1))); resultRegisters = endRegisters; return i_end; } /// <summary> /// Phase 2 of matching. From a found ending position, walk in reverse through the input using the reverse pattern to find the /// start position of match. /// </summary> /// <remarks> /// The start position is known to exist; this function just needs to determine exactly what it is. /// We need to find the earliest (lowest index) starting position that's not earlier than <paramref name="matchStartBoundary"/>. /// </remarks> /// <param name="input">The input text.</param> /// <param name="i">The ending position to walk backwards from. <paramref name="i"/> points at the last character of the match.</param> /// <param name="matchStartBoundary">The initial starting location discovered in phase 1, a point we must not walk earlier than.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The found starting position for the match.</returns> private int FindStartPosition(ReadOnlySpan<char> input, int i, int matchStartBoundary, PerThreadData perThreadData) { Debug.Assert(i >= 0, $"{nameof(i)} == {i}"); Debug.Assert(matchStartBoundary >= 0 && matchStartBoundary < input.Length, $"{nameof(matchStartBoundary)} == {matchStartBoundary}"); Debug.Assert(i >= matchStartBoundary, $"Expected {i} >= {matchStartBoundary}."); // Get the starting state for the reverse pattern. This depends on previous character (which, because we're // going backwards, is character number i + 1). var currentState = new CurrentState(_reverseInitialStates[GetCharKind(input, i + 1)]); // If the initial state is nullable, meaning it accepts the empty string, then we've already discovered // a valid starting position, and we just need to keep looking for an earlier one in case there is one. int lastStart = -1; // invalid sentinel value if (currentState.DfaState!.IsNullable(GetCharKind(input, i))) { lastStart = i + 1; } // Walk backwards to the furthest accepting state of the reverse pattern but no earlier than matchStartBoundary. SymbolicRegexBuilder<TSetType> builder = currentState.DfaState.Node._builder; while (true) { // Run the DFA or NFA traversal backwards from the current point using the current state. bool done = currentState.NfaState is not null ? FindStartPositionDeltas<NfaStateHandler>(builder, input, ref i, matchStartBoundary, ref currentState, ref lastStart) : FindStartPositionDeltas<DfaStateHandler>(builder, input, ref i, matchStartBoundary, ref currentState, ref lastStart); // If we found the starting position, we're done. if (done) { break; } // We didn't find the starting position but we did exit out of the backwards traversal. That should only happen // if we were unable to transition, which should only happen if we were in DFA mode and exceeded our graph size. // Upgrade to NFA mode and continue. Debug.Assert(i >= matchStartBoundary); Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } Debug.Assert(lastStart != -1, "We expected to find a starting position but didn't."); return lastStart; } /// <summary> /// Workhorse inner loop for <see cref="FindStartPosition"/>. Consumes the <paramref name="input"/> character by character in reverse, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> private bool FindStartPositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, int startThreshold, ref CurrentState currentState, ref int lastStart) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Loop backwards through each character in the input, transitioning from state to state for each. while (TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { // We successfully transitioned. If the new state is a dead end, we're done, as we must have already seen // and recorded a larger lastStart value that was the earliest valid starting position. if (TStateHandler.IsDeadend(ref state)) { Debug.Assert(lastStart != -1); currentState = state; i = pos; return true; } // If the new state accepts the empty string, we found a valid starting position. Record it and keep going, // since we're looking for the earliest one to occur within bounds. if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos - 1))) { lastStart = pos; } // Since we successfully transitioned, update our current index to match the fact that we consumed the previous character in the input. pos--; // If doing so now puts us below the start threshold, bail; we should have already found a valid starting location. if (pos < startThreshold) { Debug.Assert(lastStart != -1); currentState = state; i = pos; return true; } } // Unable to transition further. currentState = state; i = pos; return false; } /// <summary>Performs the initial Phase 1 match to find the first final state encountered.</summary> /// <param name="input">The input text.</param> /// <param name="i">The starting position in <paramref name="input"/>.</param> /// <param name="timeoutOccursAt">The time at which timeout occurs, if timeouts are being checked.</param> /// <param name="initialStateIndex">The last position the initial state of <see cref="_dotStarredPattern"/> was visited.</param> /// <param name="matchLength">Length of the match if there's a match; otherwise, -1.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The index into input that matches the final state, or NoMatchExists if no match exists. It returns -1 when i=0 and the initial state is nullable.</returns> private int FindFinalStatePosition(ReadOnlySpan<char> input, int i, int timeoutOccursAt, out int initialStateIndex, out int matchLength, PerThreadData perThreadData) { matchLength = -1; initialStateIndex = i; // Start with the start state of the dot-star pattern, which in general depends on the previous character kind in the input in order to handle anchors. // If the starting state is a dead end, then no match exists. var currentState = new CurrentState(_dotstarredInitialStates[GetCharKind(input, i - 1)]); if (currentState.DfaState!.IsNothing) { // This can happen, for example, when the original regex starts with a beginning anchor but the previous char kind is not Beginning. return NoMatchExists; } // If the starting state accepts the empty string in this context (factoring in anchors), we're done. if (currentState.DfaState.IsNullable(GetCharKind(input, i))) { // The initial state is nullable in this context so at least an empty match exists. // The last position of the match is i - 1 because the match is empty. // This value is -1 if i == 0. return i - 1; } // Otherwise, start searching from the current position until the end of the input. if ((uint)i < (uint)input.Length) { SymbolicRegexBuilder<TSetType> builder = currentState.DfaState.Node._builder; while (true) { // If we're at an initial state, try to search ahead for the next possible match location // using any find optimizations that may have previously been computed. if (currentState.DfaState is { IsInitialState: true }) { // i is the most recent position in the input when the dot-star pattern is in the initial state initialStateIndex = i; if (_findOpts is RegexFindOptimizations findOpts) { // Find the first position i that matches with some likely character. if (!findOpts.TryFindNextStartingPosition(input, ref i, 0)) { // no match was found return NoMatchExists; } initialStateIndex = i; // Update the starting state based on where TryFindNextStartingPosition moved us to. // As with the initial starting state, if it's a dead end, no match exists. currentState = new CurrentState(_dotstarredInitialStates[GetCharKind(input, i - 1)]); if (currentState.DfaState!.IsNothing) { return NoMatchExists; } } } // Now run the DFA or NFA traversal from the current point using the current state. int finalStatePosition; int findResult = currentState.NfaState is not null ? FindFinalStatePositionDeltas<NfaStateHandler>(builder, input, ref i, ref currentState, ref matchLength, out finalStatePosition) : FindFinalStatePositionDeltas<DfaStateHandler>(builder, input, ref i, ref currentState, ref matchLength, out finalStatePosition); // If we reached a final or deadend state, we're done. if (findResult > 0) { return finalStatePosition; } // We're not at an end state, so we either ran out of input (in which case no match exists), hit an initial state (in which case // we want to loop around to apply our initial state processing logic and optimizations), or failed to transition (which should // only happen if we were in DFA mode and need to switch over to NFA mode). If we exited because we hit an initial state, // find result will be 0, otherwise negative. if (findResult < 0) { if ((uint)i >= (uint)input.Length) { // We ran out of input. No match. break; } // We failed to transition. Upgrade to DFA mode. Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } // Check for a timeout before continuing. if (_checkTimeout) { DoCheckTimeout(timeoutOccursAt); } } } // No match was found. return NoMatchExists; } /// <summary> /// Workhorse inner loop for <see cref="FindFinalStatePosition"/>. Consumes the <paramref name="input"/> character by character, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> /// <remarks> /// The <typeparamref name="TStateHandler"/> supplies the actual transitioning logic, controlling whether processing is /// performed in DFA mode or in NFA mode. However, it expects <paramref name="currentState"/> to be configured to match, /// so for example if <typeparamref name="TStateHandler"/> is a <see cref="DfaStateHandler"/>, it expects the <paramref name="currentState"/>'s /// <see cref="CurrentState.DfaState"/> to be non-null and its <see cref="CurrentState.NfaState"/> to be null; vice versa for /// <see cref="NfaStateHandler"/>. /// </remarks> /// <returns> /// A positive value if iteration completed because it reached a nullable or deadend state. /// 0 if iteration completed because we reached an initial state. /// A negative value if iteration completed because we ran out of input or we failed to transition. /// </returns> private int FindFinalStatePositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, ref CurrentState currentState, ref int matchLength, out int finalStatePosition) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Loop through each character in the input, transitioning from state to state for each. while ((uint)pos < (uint)input.Length && TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { // We successfully transitioned for the character at index i. If the new state is nullable for // the next character, meaning it accepts the empty string, we found a final state and are done! if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos + 1))) { // Check whether there's a fixed-length marker for the current state. If there is, we can // use that length to optimize subsequent matching phases. matchLength = TStateHandler.FixedLength(ref state); currentState = state; i = pos; finalStatePosition = pos; return 1; } // If the new state is a dead end, such that we didn't match and we can't transition anywhere // else, then no match exists. if (TStateHandler.IsDeadend(ref state)) { currentState = state; i = pos; finalStatePosition = NoMatchExists; return 1; } // We successfully transitioned, so update our current input index to match. pos++; // Now that currentState and our position are coherent, check if currentState represents an initial state. // If it does, we exit out in order to allow our find optimizations to kick in to hopefully more quickly // find the next possible starting location. if (TStateHandler.IsInitialState(ref state)) { currentState = state; i = pos; finalStatePosition = 0; return 0; } } currentState = state; i = pos; finalStatePosition = 0; return -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private uint GetCharKind(ReadOnlySpan<char> input, int i) { return !_pattern._info.ContainsSomeAnchor ? CharKind.General : // The previous character kind is irrelevant when anchors are not used. GetCharKindWithAnchor(input, i); uint GetCharKindWithAnchor(ReadOnlySpan<char> input, int i) { Debug.Assert(_asciiCharKinds is not null); if ((uint)i >= (uint)input.Length) { return CharKind.BeginningEnd; } char nextChar = input[i]; if (nextChar == '\n') { return _builder._newLinePredicate.Equals(_builder._solver.False) ? 0 : // ignore \n i == 0 || i == input.Length - 1 ? CharKind.NewLineS : // very first or very last \n. Detection of very first \n is needed for rev(\Z). CharKind.Newline; } uint[] asciiCharKinds = _asciiCharKinds; return nextChar < (uint)asciiCharKinds.Length ? asciiCharKinds[nextChar] : _builder._solver.And(GetMinterm(nextChar), _builder._wordLetterPredicateForAnchors).Equals(_builder._solver.False) ? 0 : //apply the wordletter predicate to compute the kind of the next character CharKind.WordLetter; } } /// <summary>Stores additional data for tracking capture start and end positions.</summary> /// <remarks>The NFA simulation based third phase has one of these for each current state in the current set of live states.</remarks> internal struct Registers { public Registers(int[] captureStarts, int[] captureEnds) { CaptureStarts = captureStarts; CaptureEnds = captureEnds; } public int[] CaptureStarts { get; set; } public int[] CaptureEnds { get; set; } /// <summary> /// Applies a list of effects in order to these registers at the provided input position. The order of effects /// should not matter though, as multiple effects to the same capture start or end do not arise. /// </summary> /// <param name="effects">list of effects to be applied</param> /// <param name="pos">the current input position to record</param> public void ApplyEffects(List<DerivativeEffect> effects, int pos) { foreach (DerivativeEffect effect in effects) { ApplyEffect(effect, pos); } } /// <summary> /// Apply a single effect to these registers at the provided input position. /// </summary> /// <param name="effect">the effecto to be applied</param> /// <param name="pos">the current input position to record</param> public void ApplyEffect(DerivativeEffect effect, int pos) { switch (effect.Kind) { case DerivativeEffectKind.CaptureStart: CaptureStarts[effect.CaptureNumber] = pos; break; case DerivativeEffectKind.CaptureEnd: CaptureEnds[effect.CaptureNumber] = pos; break; } } /// <summary> /// Make a copy of this set of registers. /// </summary> /// <returns>Registers pointing to copies of this set of registers</returns> public Registers Clone() => new Registers((int[])CaptureStarts.Clone(), (int[])CaptureEnds.Clone()); /// <summary> /// Copy register values from another set of registers, possibly allocating new arrays if they were not yet allocated. /// </summary> /// <param name="other">the registers to copy from</param> public void Assign(Registers other) { if (CaptureStarts is not null && CaptureEnds is not null) { Debug.Assert(CaptureStarts.Length == other.CaptureStarts.Length); Debug.Assert(CaptureEnds.Length == other.CaptureEnds.Length); Array.Copy(other.CaptureStarts, CaptureStarts, CaptureStarts.Length); Array.Copy(other.CaptureEnds, CaptureEnds, CaptureEnds.Length); } else { CaptureStarts = (int[])other.CaptureStarts.Clone(); CaptureEnds = (int[])other.CaptureEnds.Clone(); } } } /// <summary> /// Per thread data to be held by the regex runner and passed into every call to FindMatch. This is used to /// avoid repeated memory allocation. /// </summary> internal sealed class PerThreadData { public readonly NfaMatchingState NfaState; /// <summary>Maps used for the capturing third phase.</summary> public readonly SparseIntMap<Registers>? Current, Next; /// <summary>Registers used for the capturing third phase.</summary> public readonly Registers InitialRegisters; public PerThreadData(SymbolicRegexBuilder<TSetType> builder, int capsize) { NfaState = new NfaMatchingState(builder); // Only create data used for capturing mode if there are subcaptures if (capsize > 1) { Current = new(); Next = new(); InitialRegisters = new Registers(new int[capsize], new int[capsize]); } } } /// <summary>Stores the state that represents a current state in NFA mode.</summary> /// <remarks>The entire state is composed of a list of individual states.</remarks> internal sealed class NfaMatchingState { /// <summary>The associated builder used to lazily add new DFA or NFA nodes to the graph.</summary> public readonly SymbolicRegexBuilder<TSetType> Builder; /// <summary>Ordered set used to store the current NFA states.</summary> /// <remarks>The value is unused. The type is used purely for its keys.</remarks> public SparseIntMap<int> NfaStateSet = new(); /// <summary>Scratch set to swap with <see cref="NfaStateSet"/> on each transition.</summary> /// <remarks> /// On each transition, <see cref="NfaStateSetScratch"/> is cleared and filled with the next /// states computed from the current states in <see cref="NfaStateSet"/>, and then the sets /// are swapped so the scratch becomes the current and the current becomes the scratch. /// </remarks> public SparseIntMap<int> NfaStateSetScratch = new(); /// <summary>Create the instance.</summary> /// <remarks>New instances should only be created once per runner.</remarks> public NfaMatchingState(SymbolicRegexBuilder<TSetType> builder) => Builder = builder; /// <summary>Resets this NFA state to represent the supplied DFA state.</summary> /// <param name="dfaMatchingState">The DFA state to use to initialize the NFA state.</param> public void InitializeFrom(DfaMatchingState<TSetType> dfaMatchingState) { NfaStateSet.Clear(); // If the DFA state is a union of multiple DFA states, loop through all of them // adding an NFA state for each. if (dfaMatchingState.Node.Kind is SymbolicRegexNodeKind.Or) { Debug.Assert(dfaMatchingState.Node._alts is not null); foreach (SymbolicRegexNode<TSetType> node in dfaMatchingState.Node._alts) { // Create (possibly new) NFA states for all the members. // Add their IDs to the current set of NFA states and into the list. int nfaState = Builder.CreateNfaState(node, dfaMatchingState.PrevCharKind); NfaStateSet.Add(nfaState, out _); } } else { // Otherwise, just add an NFA state for the singular DFA state. SymbolicRegexNode<TSetType> node = dfaMatchingState.Node; int nfaState = Builder.CreateNfaState(node, dfaMatchingState.PrevCharKind); NfaStateSet.Add(nfaState, out _); } } } /// <summary>Represents a current state in a DFA or NFA graph walk while processing a regular expression.</summary> /// <remarks>This is a discriminated union between a DFA state and an NFA state. One and only one will be non-null.</remarks> private struct CurrentState { /// <summary>Initializes the state as a DFA state.</summary> public CurrentState(DfaMatchingState<TSetType> dfaState) { DfaState = dfaState; NfaState = null; } /// <summary>Initializes the state as an NFA state.</summary> public CurrentState(NfaMatchingState nfaState) { DfaState = null; NfaState = nfaState; } /// <summary>The DFA state.</summary> public DfaMatchingState<TSetType>? DfaState; /// <summary>The NFA state.</summary> public NfaMatchingState? NfaState; } /// <summary>Represents a set of routines for operating over a <see cref="CurrentState"/>.</summary> private interface IStateHandler { #pragma warning disable CA2252 // This API requires opting into preview features public static abstract bool StartsWithLineAnchor(ref CurrentState state); public static abstract bool IsNullable(ref CurrentState state, uint nextCharKind); public static abstract bool IsDeadend(ref CurrentState state); public static abstract int FixedLength(ref CurrentState state); public static abstract bool IsInitialState(ref CurrentState state); public static abstract bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId); #pragma warning restore CA2252 // This API requires opting into preview features } /// <summary>An <see cref="IStateHandler"/> for operating over <see cref="CurrentState"/> instances configured as DFA states.</summary> private readonly struct DfaStateHandler : IStateHandler { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWithLineAnchor(ref CurrentState state) => state.DfaState!.StartsWithLineAnchor; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullable(ref CurrentState state, uint nextCharKind) => state.DfaState!.IsNullable(nextCharKind); /// <summary>Gets whether this is a dead-end state, meaning there are no transitions possible out of the state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDeadend(ref CurrentState state) => state.DfaState!.IsDeadend; /// <summary>Gets the length of any fixed-length marker that exists for this state, or -1 if there is none.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FixedLength(ref CurrentState state) => state.DfaState!.FixedLength; /// <summary>Gets whether this is an initial state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInitialState(ref CurrentState state) => state.DfaState!.IsInitialState; /// <summary>Take the transition to the next DFA state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId) { Debug.Assert(state.DfaState is not null, $"Expected non-null {nameof(state.DfaState)}."); Debug.Assert(state.NfaState is null, $"Expected null {nameof(state.NfaState)}."); Debug.Assert(builder._delta is not null); // Get the current state. DfaMatchingState<TSetType> dfaMatchingState = state.DfaState!; // Use the mintermId for the character being read to look up which state to transition to. // If that state has already been materialized, move to it, and we're done. If that state // hasn't been materialized, try to create it; if we can, move to it, and we're done. int dfaOffset = (dfaMatchingState.Id << builder._mintermsLog) | mintermId; DfaMatchingState<TSetType>? nextState = builder._delta[dfaOffset]; if (nextState is not null || builder.TryCreateNewTransition(dfaMatchingState, mintermId, dfaOffset, checkThreshold: true, out nextState)) { // There was an existing state for this transition or we were able to create one. Move to it and // return that we're still operating as a DFA and can keep going. state.DfaState = nextState; return true; } return false; } } /// <summary>An <see cref="IStateHandler"/> for operating over <see cref="CurrentState"/> instances configured as NFA states.</summary> private readonly struct NfaStateHandler : IStateHandler { /// <summary>Check if any underlying core state starts with a line anchor.</summary> public static bool StartsWithLineAnchor(ref CurrentState state) { SymbolicRegexBuilder<TSetType> builder = state.NfaState!.Builder; foreach (ref KeyValuePair<int, int> nfaState in CollectionsMarshal.AsSpan(state.NfaState!.NfaStateSet.Values)) { if (builder.GetCoreState(nfaState.Key).StartsWithLineAnchor) { return true; } } return false; } /// <summary>Check if any underlying core state is nullable.</summary> public static bool IsNullable(ref CurrentState state, uint nextCharKind) { SymbolicRegexBuilder<TSetType> builder = state.NfaState!.Builder; foreach (ref KeyValuePair<int, int> nfaState in CollectionsMarshal.AsSpan(state.NfaState!.NfaStateSet.Values)) { if (builder.GetCoreState(nfaState.Key).IsNullable(nextCharKind)) { return true; } } return false; } /// <summary>Gets whether this is a dead-end state, meaning there are no transitions possible out of the state.</summary> /// <remarks>In NFA mode, an empty set of states means that it is a dead end.</remarks> public static bool IsDeadend(ref CurrentState state) => state.NfaState!.NfaStateSet.Count == 0; /// <summary>Gets the length of any fixed-length marker that exists for this state, or -1 if there is none.</summary> /// <summary>In NFA mode, there are no fixed-length markers.</summary> public static int FixedLength(ref CurrentState state) => -1; /// <summary>Gets whether this is an initial state.</summary> /// <summary>In NFA mode, no set of states qualifies as an initial state.</summary> public static bool IsInitialState(ref CurrentState state) => false; /// <summary>Take the transition to the next NFA state.</summary> public static bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId) { Debug.Assert(state.DfaState is null, $"Expected null {nameof(state.DfaState)}."); Debug.Assert(state.NfaState is not null, $"Expected non-null {nameof(state.NfaState)}."); NfaMatchingState nfaState = state.NfaState!; // Grab the sets, swapping the current active states set with the scratch set. SparseIntMap<int> nextStates = nfaState.NfaStateSetScratch; SparseIntMap<int> sourceStates = nfaState.NfaStateSet; nfaState.NfaStateSet = nextStates; nfaState.NfaStateSetScratch = sourceStates; // Compute the set of all unique next states from the current source states and the mintermId. nextStates.Clear(); if (sourceStates.Count == 1) { // We have a single source state. We know its next states are already deduped, // so we can just add them directly to the destination states list. foreach (int nextState in GetNextStates(sourceStates.Values[0].Key, mintermId, builder)) { nextStates.Add(nextState, out _); } } else { // We have multiple source states, so we need to potentially dedup across each of // their next states. For each source state, get its next states, adding each into // our set (which exists purely for deduping purposes), and if we successfully added // to the set, then add the known-unique state to the destination list. foreach (ref KeyValuePair<int, int> sourceState in CollectionsMarshal.AsSpan(sourceStates.Values)) { foreach (int nextState in GetNextStates(sourceState.Key, mintermId, builder)) { nextStates.Add(nextState, out _); } } } return true; [MethodImpl(MethodImplOptions.AggressiveInlining)] static int[] GetNextStates(int sourceState, int mintermId, SymbolicRegexBuilder<TSetType> builder) { // Calculate the offset into the NFA transition table. int nfaOffset = (sourceState << builder._mintermsLog) | mintermId; // Get the next NFA state. return builder._nfaDelta[nfaOffset] ?? builder.CreateNewNfaTransition(sourceState, mintermId, nfaOffset); } } } #if DEBUG public override void SaveDGML(TextWriter writer, int bound, bool hideStateInfo, bool addDotStar, bool inReverse, bool onlyDFAinfo, int maxLabelLength, bool asNFA) { var graph = new DGML.RegexAutomaton<TSetType>(this, bound, addDotStar, inReverse, asNFA); var dgml = new DGML.DgmlWriter(writer, hideStateInfo, maxLabelLength, onlyDFAinfo); dgml.Write(graph); } public override IEnumerable<string> GenerateRandomMembers(int k, int randomseed, bool negative) => new SymbolicRegexSampler<TSetType>(_pattern, randomseed, negative).GenerateRandomMembers(k); #endif } }
1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/GetAndWithElement.Double.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementDouble1() { var test = new VectorGetAndWithElement__GetAndWithElementDouble1(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementDouble1 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Double[] values = new Double[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetDouble(); } Vector256<Double> value = Vector256.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { Double result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Double.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Double insertedValue = TestLibrary.Generator.GetDouble(); try { Vector256<Double> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Double.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Double[] values = new Double[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetDouble(); } Vector256<Double> value = Vector256.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Double)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Double.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Double insertedValue = TestLibrary.Generator.GetDouble(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<Double>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Double.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Double result, Double[] values, [CallerMemberName] string method = "") { if (result != values[1]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<Double.GetElement(1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<Double> result, Double[] values, Double insertedValue, [CallerMemberName] string method = "") { Double[] resultElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Double[] result, Double[] values, Double insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 1) && (result[i] != values[i])) { succeeded = false; break; } } if (result[1] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Double.WithElement(1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementDouble1() { var test = new VectorGetAndWithElement__GetAndWithElementDouble1(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementDouble1 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Double[] values = new Double[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetDouble(); } Vector256<Double> value = Vector256.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { Double result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Double.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Double insertedValue = TestLibrary.Generator.GetDouble(); try { Vector256<Double> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Double.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Double[] values = new Double[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetDouble(); } Vector256<Double> value = Vector256.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Double)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Double.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Double insertedValue = TestLibrary.Generator.GetDouble(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<Double>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Double.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Double result, Double[] values, [CallerMemberName] string method = "") { if (result != values[1]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<Double.GetElement(1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<Double> result, Double[] values, Double insertedValue, [CallerMemberName] string method = "") { Double[] resultElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Double[] result, Double[] values, Double insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 1) && (result[i] != values[i])) { succeeded = false; break; } } if (result[1] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Double.WithElement(1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/JIT/Methodical/eh/generics/trycatchnestedtype.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; public class GenException<T> : Exception { } public interface IGen { bool ExceptionTest(); } public class Gen<T> : IGen { public bool ExceptionTest() { try { Console.WriteLine("in try"); throw new GenException<T>(); } catch (GenException<T> exp) { Console.WriteLine("in catch: " + exp.Message); return true; } } } public class Test_trycatchnestedtype { private static TestUtil.TestLog testLog; static Test_trycatchnestedtype() { // Create test writer object to hold expected output StringWriter expectedOut = new StringWriter(); // Write expected output to string writer object Exception[] expList = new Exception[] { new GenException<Exception>(), new GenException<GenException<Exception>>(), new GenException<GenException<GenException<Exception>>>(), new GenException<GenException<GenException<GenException<Exception>>>>(), new GenException<GenException<GenException<GenException<GenException<Exception>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>>() }; for (int i = 0; i < expList.Length; i++) { expectedOut.WriteLine("in try"); expectedOut.WriteLine("in catch: " + expList[i].Message); expectedOut.WriteLine("{0}", true); } // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } public static int Main() { //Start recording testLog.StartRecording(); // create test list IGen[] genList = new IGen[] { new Gen<Exception>(), new Gen<GenException<Exception>>(), new Gen<GenException<GenException<Exception>>>(), new Gen<GenException<GenException<GenException<Exception>>>>(), new Gen<GenException<GenException<GenException<GenException<Exception>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>>() }; // run test for (int i = 0; i < genList.Length; i++) { Console.WriteLine(genList[i].ExceptionTest()); } // stop recoding testLog.StopRecording(); return testLog.VerifyOutput(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; public class GenException<T> : Exception { } public interface IGen { bool ExceptionTest(); } public class Gen<T> : IGen { public bool ExceptionTest() { try { Console.WriteLine("in try"); throw new GenException<T>(); } catch (GenException<T> exp) { Console.WriteLine("in catch: " + exp.Message); return true; } } } public class Test_trycatchnestedtype { private static TestUtil.TestLog testLog; static Test_trycatchnestedtype() { // Create test writer object to hold expected output StringWriter expectedOut = new StringWriter(); // Write expected output to string writer object Exception[] expList = new Exception[] { new GenException<Exception>(), new GenException<GenException<Exception>>(), new GenException<GenException<GenException<Exception>>>(), new GenException<GenException<GenException<GenException<Exception>>>>(), new GenException<GenException<GenException<GenException<GenException<Exception>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>(), new GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>>() }; for (int i = 0; i < expList.Length; i++) { expectedOut.WriteLine("in try"); expectedOut.WriteLine("in catch: " + expList[i].Message); expectedOut.WriteLine("{0}", true); } // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } public static int Main() { //Start recording testLog.StartRecording(); // create test list IGen[] genList = new IGen[] { new Gen<Exception>(), new Gen<GenException<Exception>>(), new Gen<GenException<GenException<Exception>>>(), new Gen<GenException<GenException<GenException<Exception>>>>(), new Gen<GenException<GenException<GenException<GenException<Exception>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>(), new Gen<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<GenException<Exception>>>>>>>>>>() }; // run test for (int i = 0; i < genList.Length; i++) { Console.WriteLine(genList[i].ExceptionTest()); } // stop recoding testLog.StopRecording(); return testLog.VerifyOutput(); } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/RightShiftInstruction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract class RightShiftInstruction : Instruction { private static Instruction? s_SByte, s_Int16, s_Int32, s_Int64, s_Byte, s_UInt16, s_UInt32, s_UInt64; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "RightShift"; private RightShiftInstruction() { } private sealed class RightShiftSByte : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((sbyte)((sbyte)value >> (int)shift)); } return 1; } } private sealed class RightShiftInt16 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((short)((short)value >> (int)shift)); } return 1; } } private sealed class RightShiftInt32 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((int)value >> (int)shift); } return 1; } } private sealed class RightShiftInt64 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((long)value >> (int)shift); } return 1; } } private sealed class RightShiftByte : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((byte)((byte)value >> (int)shift)); } return 1; } } private sealed class RightShiftUInt16 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((ushort)((ushort)value >> (int)shift)); } return 1; } } private sealed class RightShiftUInt32 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((uint)value >> (int)shift); } return 1; } } private sealed class RightShiftUInt64 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((ulong)value >> (int)shift); } return 1; } } public static Instruction Create(Type type) { return type.GetNonNullableType().GetTypeCode() switch { TypeCode.SByte => s_SByte ?? (s_SByte = new RightShiftSByte()), TypeCode.Int16 => s_Int16 ?? (s_Int16 = new RightShiftInt16()), TypeCode.Int32 => s_Int32 ?? (s_Int32 = new RightShiftInt32()), TypeCode.Int64 => s_Int64 ?? (s_Int64 = new RightShiftInt64()), TypeCode.Byte => s_Byte ?? (s_Byte = new RightShiftByte()), TypeCode.UInt16 => s_UInt16 ?? (s_UInt16 = new RightShiftUInt16()), TypeCode.UInt32 => s_UInt32 ?? (s_UInt32 = new RightShiftUInt32()), TypeCode.UInt64 => s_UInt64 ?? (s_UInt64 = new RightShiftUInt64()), _ => throw ContractUtils.Unreachable, }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract class RightShiftInstruction : Instruction { private static Instruction? s_SByte, s_Int16, s_Int32, s_Int64, s_Byte, s_UInt16, s_UInt32, s_UInt64; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "RightShift"; private RightShiftInstruction() { } private sealed class RightShiftSByte : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((sbyte)((sbyte)value >> (int)shift)); } return 1; } } private sealed class RightShiftInt16 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((short)((short)value >> (int)shift)); } return 1; } } private sealed class RightShiftInt32 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((int)value >> (int)shift); } return 1; } } private sealed class RightShiftInt64 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((long)value >> (int)shift); } return 1; } } private sealed class RightShiftByte : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((byte)((byte)value >> (int)shift)); } return 1; } } private sealed class RightShiftUInt16 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((ushort)((ushort)value >> (int)shift)); } return 1; } } private sealed class RightShiftUInt32 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((uint)value >> (int)shift); } return 1; } } private sealed class RightShiftUInt64 : RightShiftInstruction { public override int Run(InterpretedFrame frame) { object? shift = frame.Pop(); object? value = frame.Pop(); if (value == null || shift == null) { frame.Push(null); } else { frame.Push((ulong)value >> (int)shift); } return 1; } } public static Instruction Create(Type type) { return type.GetNonNullableType().GetTypeCode() switch { TypeCode.SByte => s_SByte ?? (s_SByte = new RightShiftSByte()), TypeCode.Int16 => s_Int16 ?? (s_Int16 = new RightShiftInt16()), TypeCode.Int32 => s_Int32 ?? (s_Int32 = new RightShiftInt32()), TypeCode.Int64 => s_Int64 ?? (s_Int64 = new RightShiftInt64()), TypeCode.Byte => s_Byte ?? (s_Byte = new RightShiftByte()), TypeCode.UInt16 => s_UInt16 ?? (s_UInt16 = new RightShiftUInt16()), TypeCode.UInt32 => s_UInt32 ?? (s_UInt32 = new RightShiftUInt32()), TypeCode.UInt64 => s_UInt64 ?? (s_UInt64 = new RightShiftUInt64()), _ => throw ContractUtils.Unreachable, }; } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/installer/tests/HostActivation.Tests/NativeHosting/HostContext.PropertyCompatibilityTestData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Xunit; using Xunit.Abstractions; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeHosting { public partial class HostContext : IClassFixture<HostContext.SharedTestState> { public class PropertyTestData : IXunitSerializable { public string Name; public string NewValue; public string ExistingValue; void IXunitSerializable.Deserialize(IXunitSerializationInfo info) { Name = info.GetValue<string>("Name"); NewValue = info.GetValue<string>("NewValue"); ExistingValue = info.GetValue<string>("ExistingValue"); } void IXunitSerializable.Serialize(IXunitSerializationInfo info) { info.AddValue("Name", Name); info.AddValue("NewValue", NewValue); info.AddValue("ExistingValue", ExistingValue); } public override string ToString() { return $"Name: {Name}, NewValue: {NewValue}, ExistingValue: {ExistingValue}"; } } private static List<PropertyTestData[]> GetPropertiesTestData( string propertyName1, string propertyValue1, string propertyName2, string propertyValue2) { var list = new List<PropertyTestData[]>() { // No additional properties new PropertyTestData[] { }, // Match new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1, ExistingValue = propertyValue1 } }, // Substring new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1.Remove(propertyValue1.Length - 1), ExistingValue = propertyValue1 } }, // Different in case only new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1.ToLower(), ExistingValue = propertyValue1 } }, // Different value new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = "NEW_PROPERTY_VALUE", ExistingValue = propertyValue1 } }, // Different value (empty) new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = string.Empty, ExistingValue = propertyValue1 } }, // New property new PropertyTestData[] { new PropertyTestData { Name = "NEW_PROPERTY_NAME", NewValue = "NEW_PROPERTY_VALUE", ExistingValue = null } }, // Match, new property new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1, ExistingValue = propertyValue1 }, new PropertyTestData { Name = "NEW_PROPERTY_NAME", NewValue = "NEW_PROPERTY_VALUE", ExistingValue = null } }, // One match, one different new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1, ExistingValue = propertyValue1 }, new PropertyTestData { Name = propertyName2, NewValue = "NEW_PROPERTY_VALUE", ExistingValue = propertyValue2 } }, // Both different new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = "NEW_PROPERTY_VALUE", ExistingValue = propertyValue1 }, new PropertyTestData { Name = propertyName2, NewValue = "NEW_PROPERTY_VALUE", ExistingValue = propertyValue2 } }, }; if (propertyValue2 != null) { list.Add( // Both match new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1, ExistingValue = propertyValue1 }, new PropertyTestData { Name = propertyName2, NewValue = propertyValue2, ExistingValue = propertyValue2 } }); list.Add( // Both match, new property new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1, ExistingValue = propertyValue1 }, new PropertyTestData { Name = propertyName2, NewValue = propertyValue2, ExistingValue = propertyValue2 }, new PropertyTestData { Name = "NEW_PROPERTY_NAME", NewValue = "NEW_PROPERTY_VALUE", ExistingValue = null } }); } return list; } public static IEnumerable<object[]> GetPropertyCompatibilityTestData(string scenario, bool hasSecondProperty) { List<PropertyTestData[]> properties; switch (scenario) { case Scenario.ConfigMultiple: properties = GetPropertiesTestData( SharedTestState.ConfigPropertyName, SharedTestState.ConfigPropertyValue, SharedTestState.ConfigMultiPropertyName, hasSecondProperty ? SharedTestState.ConfigMultiPropertyValue : null); break; case Scenario.Mixed: case Scenario.NonContextMixedAppHost: case Scenario.NonContextMixedDotnet: properties = GetPropertiesTestData( SharedTestState.AppPropertyName, SharedTestState.AppPropertyValue, SharedTestState.AppMultiPropertyName, hasSecondProperty ? SharedTestState.AppMultiPropertyValue : null); break; default: throw new Exception($"Unexpected scenario: {scenario}"); } var list = new List<object[]> (); foreach (var p in properties) { list.Add(new object[] { scenario, hasSecondProperty, p }); } return list; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Xunit; using Xunit.Abstractions; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeHosting { public partial class HostContext : IClassFixture<HostContext.SharedTestState> { public class PropertyTestData : IXunitSerializable { public string Name; public string NewValue; public string ExistingValue; void IXunitSerializable.Deserialize(IXunitSerializationInfo info) { Name = info.GetValue<string>("Name"); NewValue = info.GetValue<string>("NewValue"); ExistingValue = info.GetValue<string>("ExistingValue"); } void IXunitSerializable.Serialize(IXunitSerializationInfo info) { info.AddValue("Name", Name); info.AddValue("NewValue", NewValue); info.AddValue("ExistingValue", ExistingValue); } public override string ToString() { return $"Name: {Name}, NewValue: {NewValue}, ExistingValue: {ExistingValue}"; } } private static List<PropertyTestData[]> GetPropertiesTestData( string propertyName1, string propertyValue1, string propertyName2, string propertyValue2) { var list = new List<PropertyTestData[]>() { // No additional properties new PropertyTestData[] { }, // Match new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1, ExistingValue = propertyValue1 } }, // Substring new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1.Remove(propertyValue1.Length - 1), ExistingValue = propertyValue1 } }, // Different in case only new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1.ToLower(), ExistingValue = propertyValue1 } }, // Different value new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = "NEW_PROPERTY_VALUE", ExistingValue = propertyValue1 } }, // Different value (empty) new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = string.Empty, ExistingValue = propertyValue1 } }, // New property new PropertyTestData[] { new PropertyTestData { Name = "NEW_PROPERTY_NAME", NewValue = "NEW_PROPERTY_VALUE", ExistingValue = null } }, // Match, new property new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1, ExistingValue = propertyValue1 }, new PropertyTestData { Name = "NEW_PROPERTY_NAME", NewValue = "NEW_PROPERTY_VALUE", ExistingValue = null } }, // One match, one different new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1, ExistingValue = propertyValue1 }, new PropertyTestData { Name = propertyName2, NewValue = "NEW_PROPERTY_VALUE", ExistingValue = propertyValue2 } }, // Both different new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = "NEW_PROPERTY_VALUE", ExistingValue = propertyValue1 }, new PropertyTestData { Name = propertyName2, NewValue = "NEW_PROPERTY_VALUE", ExistingValue = propertyValue2 } }, }; if (propertyValue2 != null) { list.Add( // Both match new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1, ExistingValue = propertyValue1 }, new PropertyTestData { Name = propertyName2, NewValue = propertyValue2, ExistingValue = propertyValue2 } }); list.Add( // Both match, new property new PropertyTestData[] { new PropertyTestData { Name = propertyName1, NewValue = propertyValue1, ExistingValue = propertyValue1 }, new PropertyTestData { Name = propertyName2, NewValue = propertyValue2, ExistingValue = propertyValue2 }, new PropertyTestData { Name = "NEW_PROPERTY_NAME", NewValue = "NEW_PROPERTY_VALUE", ExistingValue = null } }); } return list; } public static IEnumerable<object[]> GetPropertyCompatibilityTestData(string scenario, bool hasSecondProperty) { List<PropertyTestData[]> properties; switch (scenario) { case Scenario.ConfigMultiple: properties = GetPropertiesTestData( SharedTestState.ConfigPropertyName, SharedTestState.ConfigPropertyValue, SharedTestState.ConfigMultiPropertyName, hasSecondProperty ? SharedTestState.ConfigMultiPropertyValue : null); break; case Scenario.Mixed: case Scenario.NonContextMixedAppHost: case Scenario.NonContextMixedDotnet: properties = GetPropertiesTestData( SharedTestState.AppPropertyName, SharedTestState.AppPropertyValue, SharedTestState.AppMultiPropertyName, hasSecondProperty ? SharedTestState.AppMultiPropertyValue : null); break; default: throw new Exception($"Unexpected scenario: {scenario}"); } var list = new List<object[]> (); foreach (var p in properties) { list.Add(new object[] { scenario, hasSecondProperty, p }); } return list; } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/JIT/CodeGenBringUpTests/Call1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; using System.Runtime.CompilerServices; public class BringUpTest_Call1 { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void M() { Console.WriteLine("Hello"); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Call1() { M(); } public static int Main() { Call1(); return 100; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; using System.Runtime.CompilerServices; public class BringUpTest_Call1 { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void M() { Console.WriteLine("Hello"); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Call1() { M(); } public static int Main() { Call1(); return 100; } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.ValueTypedMember.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { private class ValueTypeToInterfaceConverter : JsonConverter<IMemberInterface> { public int ReadCallCount { get; private set; } public int WriteCallCount { get; private set; } public override bool HandleNull => true; public override bool CanConvert(Type typeToConvert) { return typeof(IMemberInterface).IsAssignableFrom(typeToConvert); } public override IMemberInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { ReadCallCount++; string value = reader.GetString(); if (value == null) { return null; } if (value.IndexOf("ValueTyped", StringComparison.Ordinal) >= 0) { return new ValueTypedMember(value); } if (value.IndexOf("RefTyped", StringComparison.Ordinal) >= 0) { return new RefTypedMember(value); } if (value.IndexOf("OtherVT", StringComparison.Ordinal) >= 0) { return new OtherVTMember(value); } if (value.IndexOf("OtherRT", StringComparison.Ordinal) >= 0) { return new OtherRTMember(value); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, IMemberInterface value, JsonSerializerOptions options) { WriteCallCount++; JsonSerializer.Serialize<string>(writer, value == null ? null : value.Value, options); } } private class ValueTypeToObjectConverter : JsonConverter<object> { public int ReadCallCount { get; private set; } public int WriteCallCount { get; private set; } public override bool HandleNull => true; public override bool CanConvert(Type typeToConvert) { return typeof(IMemberInterface).IsAssignableFrom(typeToConvert); } public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { ReadCallCount++; string value = reader.GetString(); if (value == null) { return null; } if (value.IndexOf("ValueTyped", StringComparison.Ordinal) >= 0) { return new ValueTypedMember(value); } if (value.IndexOf("RefTyped", StringComparison.Ordinal) >= 0) { return new RefTypedMember(value); } if (value.IndexOf("OtherVT", StringComparison.Ordinal) >= 0) { return new OtherVTMember(value); } if (value.IndexOf("OtherRT", StringComparison.Ordinal) >= 0) { return new OtherRTMember(value); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) { WriteCallCount++; JsonSerializer.Serialize<string>(writer, value == null ? null : ((IMemberInterface)value).Value, options); } } [Fact] public static void AssignmentToValueTypedMemberInterface() { var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Invalid null ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":null}", options)); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":null}", options)); } [Fact] public static void AssignmentToValueTypedMemberObject() { var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Invalid null ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":null}", options)); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":null}", options)); } [Fact] public static void AssignmentToNullableValueTypedMemberInterface() { var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); TestClassWithNullableValueTypedMember obj; Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Valid null obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":null,""MyValueTypedField"":null}", options); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); } [Fact] public static void AssignmentToNullableValueTypedMemberObject() { var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); TestClassWithNullableValueTypedMember obj; Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Valid null obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":null,""MyValueTypedField"":null}", options); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); } [Fact] public static void ValueTypedMemberToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void ValueTypedMemberToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberWithNullsToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":null,""MyRefTypedProperty"":null,""MyValueTypedField"":null,""MyRefTypedField"":null}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); Assert.Equal(4, converter.ReadCallCount); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); Assert.Null(obj.MyRefTypedProperty); Assert.Null(obj.MyRefTypedField); } } [Fact] public static void NullableValueTypedMemberWithNullsToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":null,""MyRefTypedProperty"":null,""MyValueTypedField"":null,""MyRefTypedField"":null}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); Assert.Equal(4, converter.ReadCallCount); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); Assert.Null(obj.MyRefTypedProperty); Assert.Null(obj.MyRefTypedField); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { private class ValueTypeToInterfaceConverter : JsonConverter<IMemberInterface> { public int ReadCallCount { get; private set; } public int WriteCallCount { get; private set; } public override bool HandleNull => true; public override bool CanConvert(Type typeToConvert) { return typeof(IMemberInterface).IsAssignableFrom(typeToConvert); } public override IMemberInterface Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { ReadCallCount++; string value = reader.GetString(); if (value == null) { return null; } if (value.IndexOf("ValueTyped", StringComparison.Ordinal) >= 0) { return new ValueTypedMember(value); } if (value.IndexOf("RefTyped", StringComparison.Ordinal) >= 0) { return new RefTypedMember(value); } if (value.IndexOf("OtherVT", StringComparison.Ordinal) >= 0) { return new OtherVTMember(value); } if (value.IndexOf("OtherRT", StringComparison.Ordinal) >= 0) { return new OtherRTMember(value); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, IMemberInterface value, JsonSerializerOptions options) { WriteCallCount++; JsonSerializer.Serialize<string>(writer, value == null ? null : value.Value, options); } } private class ValueTypeToObjectConverter : JsonConverter<object> { public int ReadCallCount { get; private set; } public int WriteCallCount { get; private set; } public override bool HandleNull => true; public override bool CanConvert(Type typeToConvert) { return typeof(IMemberInterface).IsAssignableFrom(typeToConvert); } public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { ReadCallCount++; string value = reader.GetString(); if (value == null) { return null; } if (value.IndexOf("ValueTyped", StringComparison.Ordinal) >= 0) { return new ValueTypedMember(value); } if (value.IndexOf("RefTyped", StringComparison.Ordinal) >= 0) { return new RefTypedMember(value); } if (value.IndexOf("OtherVT", StringComparison.Ordinal) >= 0) { return new OtherVTMember(value); } if (value.IndexOf("OtherRT", StringComparison.Ordinal) >= 0) { return new OtherRTMember(value); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) { WriteCallCount++; JsonSerializer.Serialize<string>(writer, value == null ? null : ((IMemberInterface)value).Value, options); } } [Fact] public static void AssignmentToValueTypedMemberInterface() { var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Invalid null ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":null}", options)); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":null}", options)); } [Fact] public static void AssignmentToValueTypedMemberObject() { var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Invalid null ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":null}", options)); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<TestClassWithValueTypedMember>(@"{""MyValueTypedField"":null}", options)); } [Fact] public static void AssignmentToNullableValueTypedMemberInterface() { var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); TestClassWithNullableValueTypedMember obj; Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Valid null obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":null,""MyValueTypedField"":null}", options); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); } [Fact] public static void AssignmentToNullableValueTypedMemberObject() { var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); TestClassWithNullableValueTypedMember obj; Exception ex; // Invalid cast OtherVTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options)); // Invalid cast OtherRTMember ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options)); ex = Assert.Throws<InvalidCastException>(() => JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options)); // Valid null obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(@"{""MyValueTypedProperty"":null,""MyValueTypedField"":null}", options); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); } [Fact] public static void ValueTypedMemberToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void ValueTypedMemberToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } } [Fact] public static void NullableValueTypedMemberWithNullsToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":null,""MyRefTypedProperty"":null,""MyValueTypedField"":null,""MyRefTypedField"":null}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); Assert.Equal(4, converter.ReadCallCount); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); Assert.Null(obj.MyRefTypedProperty); Assert.Null(obj.MyRefTypedField); } } [Fact] public static void NullableValueTypedMemberWithNullsToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":null,""MyRefTypedProperty"":null,""MyValueTypedField"":null,""MyRefTypedField"":null}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize<TestClassWithNullableValueTypedMember>(json, options); Assert.Equal(4, converter.ReadCallCount); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); Assert.Null(obj.MyRefTypedProperty); Assert.Null(obj.MyRefTypedField); } } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/IsReadOnlyAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This attribute should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.All, Inherited = false)] public sealed class IsReadOnlyAttribute : Attribute { public IsReadOnlyAttribute() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This attribute should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.All, Inherited = false)] public sealed class IsReadOnlyAttribute : Attribute { public IsReadOnlyAttribute() { } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/JIT/Methodical/NaN/arithm64.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace JitTest { using System; class Test { static void RunTests(double nan, double plusinf, double minusinf) { if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); } static int Main() { RunTests(Double.NaN, Double.PositiveInfinity, Double.NegativeInfinity); Console.WriteLine("=== PASSED ==="); return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace JitTest { using System; class Test { static void RunTests(double nan, double plusinf, double minusinf) { if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); if (!Double.IsNaN(nan + nan)) throw new Exception("! Double.IsNaN(nan + nan)"); if (!Double.IsNaN(nan + plusinf)) throw new Exception("! Double.IsNaN(nan + plusinf)"); if (!Double.IsNaN(nan + minusinf)) throw new Exception("! Double.IsNaN(nan + minusinf)"); if (!Double.IsNaN(plusinf + nan)) throw new Exception("! Double.IsNaN(plusinf + nan)"); if (!Double.IsPositiveInfinity(plusinf + plusinf)) throw new Exception("! Double.IsPositiveInfinity(plusinf + plusinf)"); if (!Double.IsNaN(plusinf + minusinf)) throw new Exception("! Double.IsNaN(plusinf + minusinf)"); if (!Double.IsNaN(minusinf + nan)) throw new Exception("! Double.IsNaN(minusinf + nan)"); if (!Double.IsNaN(minusinf + plusinf)) throw new Exception("! Double.IsNaN(minusinf + plusinf)"); if (!Double.IsNegativeInfinity(minusinf + minusinf)) throw new Exception("! Double.IsNegativeInfinity(minusinf + minusinf)"); } static int Main() { RunTests(Double.NaN, Double.PositiveInfinity, Double.NegativeInfinity); Console.WriteLine("=== PASSED ==="); return 100; } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Linq.Expressions/tests/BinaryOperators/Arithmetic/BinaryNullableModuloTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableModuloTests { #region Test methods [Fact] public static void CheckNullableByteModuloTest() { byte?[] array = { 0, 1, byte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableSByteModuloTest() { sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteModulo(array[i], array[j]); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortModuloTest(bool useInterpreter) { ushort?[] array = { 0, 1, ushort.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableShortModuloTest(bool useInterpreter) { short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntModuloTest(bool useInterpreter) { uint?[] array = { 0, 1, uint.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableIntModuloTest(bool useInterpreter) { int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableULongModuloTest(bool useInterpreter) { ulong?[] array = { 0, 1, ulong.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableLongModuloTest(bool useInterpreter) { long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableFloatModuloTest(bool useInterpreter) { float?[] array = { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDoubleModuloTest(bool useInterpreter) { double?[] array = { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDecimalModuloTest(bool useInterpreter) { decimal?[] array = { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalModulo(array[i], array[j], useInterpreter); } } } [Fact] public static void CheckNullableCharModuloTest() { char?[] array = { '\0', '\b', 'A', '\uffff', null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharModulo(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyNullableByteModulo(byte? a, byte? b) { Expression aExp = Expression.Constant(a, typeof(byte?)); Expression bExp = Expression.Constant(b, typeof(byte?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } private static void VerifyNullableSByteModulo(sbyte? a, sbyte? b) { Expression aExp = Expression.Constant(a, typeof(sbyte?)); Expression bExp = Expression.Constant(b, typeof(sbyte?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } private static void VerifyNullableUShortModulo(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Modulo( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableShortModulo(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Modulo( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableUIntModulo(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Modulo( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableIntModulo(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Modulo( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == int.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableULongModulo(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Modulo( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableLongModulo(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Modulo( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == long.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableFloatModulo(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Modulo( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyNullableDoubleModulo(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Modulo( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyNullableDecimalModulo(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Modulo( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableCharModulo(char? a, char? b) { Expression aExp = Expression.Constant(a, typeof(char?)); Expression bExp = Expression.Constant(b, typeof(char?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableModuloTests { #region Test methods [Fact] public static void CheckNullableByteModuloTest() { byte?[] array = { 0, 1, byte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableSByteModuloTest() { sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteModulo(array[i], array[j]); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortModuloTest(bool useInterpreter) { ushort?[] array = { 0, 1, ushort.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableShortModuloTest(bool useInterpreter) { short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntModuloTest(bool useInterpreter) { uint?[] array = { 0, 1, uint.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableIntModuloTest(bool useInterpreter) { int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableULongModuloTest(bool useInterpreter) { ulong?[] array = { 0, 1, ulong.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongModulo(array[i], array[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckNullableLongModuloTest(bool useInterpreter) { long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableFloatModuloTest(bool useInterpreter) { float?[] array = { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDoubleModuloTest(bool useInterpreter) { double?[] array = { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDecimalModuloTest(bool useInterpreter) { decimal?[] array = { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalModulo(array[i], array[j], useInterpreter); } } } [Fact] public static void CheckNullableCharModuloTest() { char?[] array = { '\0', '\b', 'A', '\uffff', null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharModulo(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyNullableByteModulo(byte? a, byte? b) { Expression aExp = Expression.Constant(a, typeof(byte?)); Expression bExp = Expression.Constant(b, typeof(byte?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } private static void VerifyNullableSByteModulo(sbyte? a, sbyte? b) { Expression aExp = Expression.Constant(a, typeof(sbyte?)); Expression bExp = Expression.Constant(b, typeof(sbyte?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } private static void VerifyNullableUShortModulo(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Modulo( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableShortModulo(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Modulo( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableUIntModulo(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Modulo( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableIntModulo(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Modulo( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == int.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableULongModulo(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Modulo( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableLongModulo(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Modulo( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == long.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableFloatModulo(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Modulo( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyNullableDoubleModulo(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Modulo( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyNullableDecimalModulo(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Modulo( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyNullableCharModulo(char? a, char? b) { Expression aExp = Expression.Constant(a, typeof(char?)); Expression bExp = Expression.Constant(b, typeof(char?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } #endregion } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.OSX.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.NetworkInformation { public partial class Ping { private static bool SendIpHeader => true; private static bool NeedsConnect => false; private static bool SupportsDualMode => false; private PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) => SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options); private async Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) { Task<PingReply> t = SendIcmpEchoRequestOverRawSocketAsync(address, buffer, timeout, options); PingReply reply = await t.ConfigureAwait(false); if (_canceled) { throw new OperationCanceledException(); } return reply; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.NetworkInformation { public partial class Ping { private static bool SendIpHeader => true; private static bool NeedsConnect => false; private static bool SupportsDualMode => false; private PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) => SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options); private async Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) { Task<PingReply> t = SendIcmpEchoRequestOverRawSocketAsync(address, buffer, timeout, options); PingReply reply = await t.ConfigureAwait(false); if (_canceled) { throw new OperationCanceledException(); } return reply; } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Runtime/tests/System/ValueTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Tests { public static class ValueTypeTests { [Fact] public static void ToStringTest() { object obj = new S(); Assert.Equal(obj.ToString(), obj.GetType().ToString()); Assert.Equal("System.Tests.ValueTypeTests+S", obj.ToString()); } [Fact] public static void StructWithDoubleFieldNotTightlyPackedZeroCompareTest() { StructWithDoubleFieldNotTightlyPacked obj1 = new StructWithDoubleFieldNotTightlyPacked(); obj1.value1 = 1; obj1.value2 = 0.0; StructWithDoubleFieldNotTightlyPacked obj2 = new StructWithDoubleFieldNotTightlyPacked(); obj2.value1 = 1; obj2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithDoubleFieldTightlyPackedZeroCompareTest() { StructWithDoubleFieldTightlyPacked obj1 = new StructWithDoubleFieldTightlyPacked(); obj1.value1 = 1; obj1.value2 = 0.0; StructWithDoubleFieldTightlyPacked obj2 = new StructWithDoubleFieldTightlyPacked(); obj2.value1 = 1; obj2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithDoubleFieldNotTightlyPackedNaNCompareTest() { StructWithDoubleFieldNotTightlyPacked obj1 = new StructWithDoubleFieldNotTightlyPacked(); obj1.value1 = 1; obj1.value2 = double.NaN; StructWithDoubleFieldNotTightlyPacked obj2 = new StructWithDoubleFieldNotTightlyPacked(); obj2.value1 = 1; obj2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithDoubleFieldTightlyPackedNaNCompareTest() { StructWithDoubleFieldTightlyPacked obj1 = new StructWithDoubleFieldTightlyPacked(); obj1.value1 = 1; obj1.value2 = double.NaN; StructWithDoubleFieldTightlyPacked obj2 = new StructWithDoubleFieldTightlyPacked(); obj2.value1 = 1; obj2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldNotTightlyPackedZeroCompareTest() { StructWithDoubleFieldNestedNotTightlyPacked obj1 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = 0.0; StructWithDoubleFieldNestedNotTightlyPacked obj2 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldTightlyPackedZeroCompareTest() { StructWithDoubleFieldNestedTightlyPacked obj1 = new StructWithDoubleFieldNestedTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = 0.0; StructWithDoubleFieldNestedTightlyPacked obj2 = new StructWithDoubleFieldNestedTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldNotTightlyPackedNaNCompareTest() { StructWithDoubleFieldNestedNotTightlyPacked obj1 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = double.NaN; StructWithDoubleFieldNestedNotTightlyPacked obj2 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldTightlyPackedNaNCompareTest() { StructWithDoubleFieldNestedTightlyPacked obj1 = new StructWithDoubleFieldNestedTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = double.NaN; StructWithDoubleFieldNestedTightlyPacked obj2 = new StructWithDoubleFieldNestedTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldNotTightlyPackedZeroCompareTest() { StructWithFloatFieldNotTightlyPacked obj1 = new StructWithFloatFieldNotTightlyPacked(); obj1.value1 = 0.0f; obj1.value2 = 1; StructWithFloatFieldNotTightlyPacked obj2 = new StructWithFloatFieldNotTightlyPacked(); obj2.value1 = -0.0f; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldTightlyPackedZeroCompareTest() { StructWithFloatFieldTightlyPacked obj1 = new StructWithFloatFieldTightlyPacked(); obj1.value1 = 0.0f; obj1.value2 = 1; StructWithFloatFieldTightlyPacked obj2 = new StructWithFloatFieldTightlyPacked(); obj2.value1 = -0.0f; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldNotTightlyPackedNaNCompareTest() { StructWithFloatFieldNotTightlyPacked obj1 = new StructWithFloatFieldNotTightlyPacked(); obj1.value1 = float.NaN; obj1.value2 = 1; StructWithFloatFieldNotTightlyPacked obj2 = new StructWithFloatFieldNotTightlyPacked(); obj2.value1 = -float.NaN; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldTightlyPackedNaNCompareTest() { StructWithFloatFieldTightlyPacked obj1 = new StructWithFloatFieldTightlyPacked(); obj1.value1 = float.NaN; obj1.value2 = 1; StructWithFloatFieldTightlyPacked obj2 = new StructWithFloatFieldTightlyPacked(); obj2.value1 = -float.NaN; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldNotTightlyPackedZeroCompareTest() { StructWithFloatFieldNestedNotTightlyPacked obj1 = new StructWithFloatFieldNestedNotTightlyPacked(); obj1.value1.value1 = 0.0f; obj1.value2.value2 = 1; StructWithFloatFieldNestedNotTightlyPacked obj2 = new StructWithFloatFieldNestedNotTightlyPacked(); obj2.value1.value1 = -0.0f; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldTightlyPackedZeroCompareTest() { StructWithFloatFieldNestedTightlyPacked obj1 = new StructWithFloatFieldNestedTightlyPacked(); obj1.value1.value1 = 0.0f; obj1.value2.value2 = 1; StructWithFloatFieldNestedTightlyPacked obj2 = new StructWithFloatFieldNestedTightlyPacked(); obj2.value1.value1 = -0.0f; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldNotTightlyPackedNaNCompareTest() { StructWithFloatFieldNestedNotTightlyPacked obj1 = new StructWithFloatFieldNestedNotTightlyPacked(); obj1.value1.value1 = float.NaN; obj1.value2.value2 = 1; StructWithFloatFieldNestedNotTightlyPacked obj2 = new StructWithFloatFieldNestedNotTightlyPacked(); obj2.value1.value1 = -float.NaN; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldTightlyPackedNaNCompareTest() { StructWithFloatFieldNestedTightlyPacked obj1 = new StructWithFloatFieldNestedTightlyPacked(); obj1.value1.value1 = float.NaN; obj1.value2.value2 = 1; StructWithFloatFieldNestedTightlyPacked obj2 = new StructWithFloatFieldNestedTightlyPacked(); obj2.value1.value1 = -float.NaN; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithoutNestedOverriddenEqualsCompareTest() { StructWithoutNestedOverriddenEqualsAndGetHashCode obj1 = new StructWithoutNestedOverriddenEqualsAndGetHashCode(); obj1.value1.value = 1; obj1.value2.value = 2; StructWithoutNestedOverriddenEqualsAndGetHashCode obj2 = new StructWithoutNestedOverriddenEqualsAndGetHashCode(); obj2.value1.value = 1; obj2.value2.value = 2; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedOverriddenEqualsCompareTest() { StructWithNestedOverriddenEqualsAndGetHashCode obj1 = new StructWithNestedOverriddenEqualsAndGetHashCode(); obj1.value1.value = 1; obj1.value2.value = 2; StructWithNestedOverriddenEqualsAndGetHashCode obj2 = new StructWithNestedOverriddenEqualsAndGetHashCode(); obj2.value1.value = 1; obj2.value2.value = 2; Assert.False(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructContainsPointerCompareTest() { StructContainsPointer obj1 = new StructContainsPointer(); obj1.value1 = 1; obj1.value2 = 0.0; StructContainsPointer obj2 = new StructContainsPointer(); obj2.value1 = 1; obj2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } public struct S { public int x; public int y; } public struct StructWithDoubleFieldNotTightlyPacked { public int value1; public double value2; } public struct StructWithDoubleFieldTightlyPacked { public double value1; public double value2; } public struct StructWithDoubleFieldNestedNotTightlyPacked { public StructWithDoubleFieldNotTightlyPacked value1; public StructWithDoubleFieldNotTightlyPacked value2; } public struct StructWithDoubleFieldNestedTightlyPacked { public StructWithDoubleFieldTightlyPacked value1; public StructWithDoubleFieldTightlyPacked value2; } public struct StructWithFloatFieldNotTightlyPacked { public float value1; public long value2; } public struct StructWithFloatFieldTightlyPacked { public float value1; public float value2; } public struct StructWithFloatFieldNestedNotTightlyPacked { public StructWithFloatFieldNotTightlyPacked value1; public StructWithFloatFieldNotTightlyPacked value2; } public struct StructWithFloatFieldNestedTightlyPacked { public StructWithFloatFieldTightlyPacked value1; public StructWithFloatFieldTightlyPacked value2; } public struct StructNonOverriddenEqualsOrGetHasCode { public byte value; } public struct StructNeverEquals { public byte value; public override bool Equals(object obj) { return false; } public override int GetHashCode() { return 0; } } public struct StructWithoutNestedOverriddenEqualsAndGetHashCode { public StructNonOverriddenEqualsOrGetHasCode value1; public StructNonOverriddenEqualsOrGetHasCode value2; } public struct StructWithNestedOverriddenEqualsAndGetHashCode { public StructNeverEquals value1; public StructNeverEquals value2; } public struct StructContainsPointer { public string s; public double value1; public double value2; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Tests { public static class ValueTypeTests { [Fact] public static void ToStringTest() { object obj = new S(); Assert.Equal(obj.ToString(), obj.GetType().ToString()); Assert.Equal("System.Tests.ValueTypeTests+S", obj.ToString()); } [Fact] public static void StructWithDoubleFieldNotTightlyPackedZeroCompareTest() { StructWithDoubleFieldNotTightlyPacked obj1 = new StructWithDoubleFieldNotTightlyPacked(); obj1.value1 = 1; obj1.value2 = 0.0; StructWithDoubleFieldNotTightlyPacked obj2 = new StructWithDoubleFieldNotTightlyPacked(); obj2.value1 = 1; obj2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithDoubleFieldTightlyPackedZeroCompareTest() { StructWithDoubleFieldTightlyPacked obj1 = new StructWithDoubleFieldTightlyPacked(); obj1.value1 = 1; obj1.value2 = 0.0; StructWithDoubleFieldTightlyPacked obj2 = new StructWithDoubleFieldTightlyPacked(); obj2.value1 = 1; obj2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithDoubleFieldNotTightlyPackedNaNCompareTest() { StructWithDoubleFieldNotTightlyPacked obj1 = new StructWithDoubleFieldNotTightlyPacked(); obj1.value1 = 1; obj1.value2 = double.NaN; StructWithDoubleFieldNotTightlyPacked obj2 = new StructWithDoubleFieldNotTightlyPacked(); obj2.value1 = 1; obj2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithDoubleFieldTightlyPackedNaNCompareTest() { StructWithDoubleFieldTightlyPacked obj1 = new StructWithDoubleFieldTightlyPacked(); obj1.value1 = 1; obj1.value2 = double.NaN; StructWithDoubleFieldTightlyPacked obj2 = new StructWithDoubleFieldTightlyPacked(); obj2.value1 = 1; obj2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldNotTightlyPackedZeroCompareTest() { StructWithDoubleFieldNestedNotTightlyPacked obj1 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = 0.0; StructWithDoubleFieldNestedNotTightlyPacked obj2 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldTightlyPackedZeroCompareTest() { StructWithDoubleFieldNestedTightlyPacked obj1 = new StructWithDoubleFieldNestedTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = 0.0; StructWithDoubleFieldNestedTightlyPacked obj2 = new StructWithDoubleFieldNestedTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldNotTightlyPackedNaNCompareTest() { StructWithDoubleFieldNestedNotTightlyPacked obj1 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = double.NaN; StructWithDoubleFieldNestedNotTightlyPacked obj2 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldTightlyPackedNaNCompareTest() { StructWithDoubleFieldNestedTightlyPacked obj1 = new StructWithDoubleFieldNestedTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = double.NaN; StructWithDoubleFieldNestedTightlyPacked obj2 = new StructWithDoubleFieldNestedTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldNotTightlyPackedZeroCompareTest() { StructWithFloatFieldNotTightlyPacked obj1 = new StructWithFloatFieldNotTightlyPacked(); obj1.value1 = 0.0f; obj1.value2 = 1; StructWithFloatFieldNotTightlyPacked obj2 = new StructWithFloatFieldNotTightlyPacked(); obj2.value1 = -0.0f; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldTightlyPackedZeroCompareTest() { StructWithFloatFieldTightlyPacked obj1 = new StructWithFloatFieldTightlyPacked(); obj1.value1 = 0.0f; obj1.value2 = 1; StructWithFloatFieldTightlyPacked obj2 = new StructWithFloatFieldTightlyPacked(); obj2.value1 = -0.0f; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldNotTightlyPackedNaNCompareTest() { StructWithFloatFieldNotTightlyPacked obj1 = new StructWithFloatFieldNotTightlyPacked(); obj1.value1 = float.NaN; obj1.value2 = 1; StructWithFloatFieldNotTightlyPacked obj2 = new StructWithFloatFieldNotTightlyPacked(); obj2.value1 = -float.NaN; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldTightlyPackedNaNCompareTest() { StructWithFloatFieldTightlyPacked obj1 = new StructWithFloatFieldTightlyPacked(); obj1.value1 = float.NaN; obj1.value2 = 1; StructWithFloatFieldTightlyPacked obj2 = new StructWithFloatFieldTightlyPacked(); obj2.value1 = -float.NaN; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldNotTightlyPackedZeroCompareTest() { StructWithFloatFieldNestedNotTightlyPacked obj1 = new StructWithFloatFieldNestedNotTightlyPacked(); obj1.value1.value1 = 0.0f; obj1.value2.value2 = 1; StructWithFloatFieldNestedNotTightlyPacked obj2 = new StructWithFloatFieldNestedNotTightlyPacked(); obj2.value1.value1 = -0.0f; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldTightlyPackedZeroCompareTest() { StructWithFloatFieldNestedTightlyPacked obj1 = new StructWithFloatFieldNestedTightlyPacked(); obj1.value1.value1 = 0.0f; obj1.value2.value2 = 1; StructWithFloatFieldNestedTightlyPacked obj2 = new StructWithFloatFieldNestedTightlyPacked(); obj2.value1.value1 = -0.0f; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldNotTightlyPackedNaNCompareTest() { StructWithFloatFieldNestedNotTightlyPacked obj1 = new StructWithFloatFieldNestedNotTightlyPacked(); obj1.value1.value1 = float.NaN; obj1.value2.value2 = 1; StructWithFloatFieldNestedNotTightlyPacked obj2 = new StructWithFloatFieldNestedNotTightlyPacked(); obj2.value1.value1 = -float.NaN; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldTightlyPackedNaNCompareTest() { StructWithFloatFieldNestedTightlyPacked obj1 = new StructWithFloatFieldNestedTightlyPacked(); obj1.value1.value1 = float.NaN; obj1.value2.value2 = 1; StructWithFloatFieldNestedTightlyPacked obj2 = new StructWithFloatFieldNestedTightlyPacked(); obj2.value1.value1 = -float.NaN; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithoutNestedOverriddenEqualsCompareTest() { StructWithoutNestedOverriddenEqualsAndGetHashCode obj1 = new StructWithoutNestedOverriddenEqualsAndGetHashCode(); obj1.value1.value = 1; obj1.value2.value = 2; StructWithoutNestedOverriddenEqualsAndGetHashCode obj2 = new StructWithoutNestedOverriddenEqualsAndGetHashCode(); obj2.value1.value = 1; obj2.value2.value = 2; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedOverriddenEqualsCompareTest() { StructWithNestedOverriddenEqualsAndGetHashCode obj1 = new StructWithNestedOverriddenEqualsAndGetHashCode(); obj1.value1.value = 1; obj1.value2.value = 2; StructWithNestedOverriddenEqualsAndGetHashCode obj2 = new StructWithNestedOverriddenEqualsAndGetHashCode(); obj2.value1.value = 1; obj2.value2.value = 2; Assert.False(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructContainsPointerCompareTest() { StructContainsPointer obj1 = new StructContainsPointer(); obj1.value1 = 1; obj1.value2 = 0.0; StructContainsPointer obj2 = new StructContainsPointer(); obj2.value1 = 1; obj2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } public struct S { public int x; public int y; } public struct StructWithDoubleFieldNotTightlyPacked { public int value1; public double value2; } public struct StructWithDoubleFieldTightlyPacked { public double value1; public double value2; } public struct StructWithDoubleFieldNestedNotTightlyPacked { public StructWithDoubleFieldNotTightlyPacked value1; public StructWithDoubleFieldNotTightlyPacked value2; } public struct StructWithDoubleFieldNestedTightlyPacked { public StructWithDoubleFieldTightlyPacked value1; public StructWithDoubleFieldTightlyPacked value2; } public struct StructWithFloatFieldNotTightlyPacked { public float value1; public long value2; } public struct StructWithFloatFieldTightlyPacked { public float value1; public float value2; } public struct StructWithFloatFieldNestedNotTightlyPacked { public StructWithFloatFieldNotTightlyPacked value1; public StructWithFloatFieldNotTightlyPacked value2; } public struct StructWithFloatFieldNestedTightlyPacked { public StructWithFloatFieldTightlyPacked value1; public StructWithFloatFieldTightlyPacked value2; } public struct StructNonOverriddenEqualsOrGetHasCode { public byte value; } public struct StructNeverEquals { public byte value; public override bool Equals(object obj) { return false; } public override int GetHashCode() { return 0; } } public struct StructWithoutNestedOverriddenEqualsAndGetHashCode { public StructNonOverriddenEqualsOrGetHasCode value1; public StructNonOverriddenEqualsOrGetHasCode value2; } public struct StructWithNestedOverriddenEqualsAndGetHashCode { public StructNeverEquals value1; public StructNeverEquals value2; } public struct StructContainsPointer { public string s; public double value1; public double value2; } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition.Primitives; using Microsoft.Internal; namespace System.ComponentModel.Composition.Hosting { public partial class CompositionBatch { private readonly object _lock = new object(); private bool _copyNeededForAdd; private bool _copyNeededForRemove; private List<ComposablePart> _partsToAdd; private ReadOnlyCollection<ComposablePart> _readOnlyPartsToAdd; private List<ComposablePart> _partsToRemove; private ReadOnlyCollection<ComposablePart> _readOnlyPartsToRemove; /// <summary> /// Initializes a new instance of the <see cref="CompositionBatch"/> class. /// </summary> public CompositionBatch() : this(null, null) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionBatch"/> class. /// </summary> /// <param name="partsToAdd">The parts to add.</param> /// <param name="partsToRemove">The parts to remove.</param> public CompositionBatch(IEnumerable<ComposablePart>? partsToAdd, IEnumerable<ComposablePart>? partsToRemove) { _partsToAdd = new List<ComposablePart>(); if (partsToAdd != null) { foreach (var part in partsToAdd) { if (part == null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(partsToAdd)); } _partsToAdd.Add(part); } } _readOnlyPartsToAdd = _partsToAdd.AsReadOnly(); _partsToRemove = new List<ComposablePart>(); if (partsToRemove != null) { foreach (var part in partsToRemove) { if (part == null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(partsToRemove)); } _partsToRemove.Add(part); } } _readOnlyPartsToRemove = _partsToRemove.AsReadOnly(); } /// <summary> /// Returns the collection of parts that will be added. /// </summary> /// <value>The parts to be added.</value> public ReadOnlyCollection<ComposablePart> PartsToAdd { get { lock (_lock) { _copyNeededForAdd = true; Debug.Assert(_readOnlyPartsToAdd != null); return _readOnlyPartsToAdd; } } } /// <summary> /// Returns the collection of parts that will be removed. /// </summary> /// <value>The parts to be removed.</value> public ReadOnlyCollection<ComposablePart> PartsToRemove { get { lock (_lock) { _copyNeededForRemove = true; Debug.Assert(_readOnlyPartsToRemove != null); return _readOnlyPartsToRemove; } } } /// <summary> /// Adds the specified part to the <see cref="CompositionBatch"/>. /// </summary> /// <param name="part"> /// The part. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="part"/> is <see langword="null"/>. /// </exception> public void AddPart(ComposablePart part) { Requires.NotNull(part, nameof(part)); lock (_lock) { if (_copyNeededForAdd) { _partsToAdd = new List<ComposablePart>(_partsToAdd); _readOnlyPartsToAdd = _partsToAdd.AsReadOnly(); _copyNeededForAdd = false; } _partsToAdd.Add(part); } } /// <summary> /// Removes the specified part from the <see cref="CompositionBatch"/>. /// </summary> /// <param name="part"> /// The part. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="part"/> is <see langword="null"/>. /// </exception> public void RemovePart(ComposablePart part) { Requires.NotNull(part, nameof(part)); lock (_lock) { if (_copyNeededForRemove) { _partsToRemove = new List<ComposablePart>(_partsToRemove); _readOnlyPartsToRemove = _partsToRemove.AsReadOnly(); _copyNeededForRemove = false; } _partsToRemove.Add(part); } } /// <summary> /// Adds the specified export to the <see cref="CompositionBatch"/>. /// </summary> /// <param name="export"> /// The <see cref="Export"/> to add to the <see cref="CompositionBatch"/>. /// </param> /// <returns> /// A <see cref="ComposablePart"/> that can be used remove the <see cref="Export"/> /// from the <see cref="CompositionBatch"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="export"/> is <see langword="null"/>. /// </exception> /// <remarks> /// </remarks> public ComposablePart AddExport(Export export) { Requires.NotNull(export, nameof(export)); ComposablePart part = new SingleExportComposablePart(export); AddPart(part); return part; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition.Primitives; using Microsoft.Internal; namespace System.ComponentModel.Composition.Hosting { public partial class CompositionBatch { private readonly object _lock = new object(); private bool _copyNeededForAdd; private bool _copyNeededForRemove; private List<ComposablePart> _partsToAdd; private ReadOnlyCollection<ComposablePart> _readOnlyPartsToAdd; private List<ComposablePart> _partsToRemove; private ReadOnlyCollection<ComposablePart> _readOnlyPartsToRemove; /// <summary> /// Initializes a new instance of the <see cref="CompositionBatch"/> class. /// </summary> public CompositionBatch() : this(null, null) { } /// <summary> /// Initializes a new instance of the <see cref="CompositionBatch"/> class. /// </summary> /// <param name="partsToAdd">The parts to add.</param> /// <param name="partsToRemove">The parts to remove.</param> public CompositionBatch(IEnumerable<ComposablePart>? partsToAdd, IEnumerable<ComposablePart>? partsToRemove) { _partsToAdd = new List<ComposablePart>(); if (partsToAdd != null) { foreach (var part in partsToAdd) { if (part == null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(partsToAdd)); } _partsToAdd.Add(part); } } _readOnlyPartsToAdd = _partsToAdd.AsReadOnly(); _partsToRemove = new List<ComposablePart>(); if (partsToRemove != null) { foreach (var part in partsToRemove) { if (part == null) { throw ExceptionBuilder.CreateContainsNullElement(nameof(partsToRemove)); } _partsToRemove.Add(part); } } _readOnlyPartsToRemove = _partsToRemove.AsReadOnly(); } /// <summary> /// Returns the collection of parts that will be added. /// </summary> /// <value>The parts to be added.</value> public ReadOnlyCollection<ComposablePart> PartsToAdd { get { lock (_lock) { _copyNeededForAdd = true; Debug.Assert(_readOnlyPartsToAdd != null); return _readOnlyPartsToAdd; } } } /// <summary> /// Returns the collection of parts that will be removed. /// </summary> /// <value>The parts to be removed.</value> public ReadOnlyCollection<ComposablePart> PartsToRemove { get { lock (_lock) { _copyNeededForRemove = true; Debug.Assert(_readOnlyPartsToRemove != null); return _readOnlyPartsToRemove; } } } /// <summary> /// Adds the specified part to the <see cref="CompositionBatch"/>. /// </summary> /// <param name="part"> /// The part. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="part"/> is <see langword="null"/>. /// </exception> public void AddPart(ComposablePart part) { Requires.NotNull(part, nameof(part)); lock (_lock) { if (_copyNeededForAdd) { _partsToAdd = new List<ComposablePart>(_partsToAdd); _readOnlyPartsToAdd = _partsToAdd.AsReadOnly(); _copyNeededForAdd = false; } _partsToAdd.Add(part); } } /// <summary> /// Removes the specified part from the <see cref="CompositionBatch"/>. /// </summary> /// <param name="part"> /// The part. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="part"/> is <see langword="null"/>. /// </exception> public void RemovePart(ComposablePart part) { Requires.NotNull(part, nameof(part)); lock (_lock) { if (_copyNeededForRemove) { _partsToRemove = new List<ComposablePart>(_partsToRemove); _readOnlyPartsToRemove = _partsToRemove.AsReadOnly(); _copyNeededForRemove = false; } _partsToRemove.Add(part); } } /// <summary> /// Adds the specified export to the <see cref="CompositionBatch"/>. /// </summary> /// <param name="export"> /// The <see cref="Export"/> to add to the <see cref="CompositionBatch"/>. /// </param> /// <returns> /// A <see cref="ComposablePart"/> that can be used remove the <see cref="Export"/> /// from the <see cref="CompositionBatch"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="export"/> is <see langword="null"/>. /// </exception> /// <remarks> /// </remarks> public ComposablePart AddExport(Export export) { Requires.NotNull(export, nameof(export)); ComposablePart part = new SingleExportComposablePart(export); AddPart(part); return part; } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/JIT/HardwareIntrinsics/General/Vector256/Xor.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void XorByte() { var test = new VectorBinaryOpTest__XorByte(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__XorByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Byte> _fld1; public Vector256<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__XorByte testClass) { var result = Vector256.Xor(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__XorByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); } public VectorBinaryOpTest__XorByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Xor( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Xor), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Xor), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Byte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Xor( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Vector256.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__XorByte(); var result = Vector256.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Xor(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Byte> op1, Vector256<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (byte)(left[0] ^ right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (byte)(left[i] ^ right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Xor)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void XorByte() { var test = new VectorBinaryOpTest__XorByte(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__XorByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Byte> _fld1; public Vector256<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__XorByte testClass) { var result = Vector256.Xor(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__XorByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); } public VectorBinaryOpTest__XorByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Xor( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Xor), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Xor), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Byte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Xor( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Vector256.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__XorByte(); var result = Vector256.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Xor(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Byte> op1, Vector256<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (byte)(left[0] ^ right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (byte)(left[i] ^ right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Xor)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata { public readonly struct MethodDefinition { private readonly MetadataReader _reader; // Workaround: JIT doesn't generate good code for nested structures, so use RowId. private readonly uint _treatmentAndRowId; internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId) { Debug.Assert(reader != null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; _treatmentAndRowId = treatmentAndRowId; } private int RowId { get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); } } private MethodDefTreatment Treatment { get { return (MethodDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); } } private MethodDefinitionHandle Handle { get { return MethodDefinitionHandle.FromRowId(RowId); } } public StringHandle Name { get { if (Treatment == 0) { return _reader.MethodDefTable.GetName(Handle); } return GetProjectedName(); } } public BlobHandle Signature { get { if (Treatment == 0) { return _reader.MethodDefTable.GetSignature(Handle); } return GetProjectedSignature(); } } public MethodSignature<TType> DecodeSignature<TType, TGenericContext>(ISignatureTypeProvider<TType, TGenericContext> provider, TGenericContext genericContext) { var decoder = new SignatureDecoder<TType, TGenericContext>(provider, _reader, genericContext); var blobReader = _reader.GetBlobReader(Signature); return decoder.DecodeMethodSignature(ref blobReader); } public int RelativeVirtualAddress { get { if (Treatment == 0) { return _reader.MethodDefTable.GetRva(Handle); } return GetProjectedRelativeVirtualAddress(); } } public MethodAttributes Attributes { get { if (Treatment == 0) { return _reader.MethodDefTable.GetFlags(Handle); } return GetProjectedFlags(); } } public MethodImplAttributes ImplAttributes { get { if (Treatment == 0) { return _reader.MethodDefTable.GetImplFlags(Handle); } return GetProjectedImplFlags(); } } 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 implMapRid = _reader.ImplMapTable.FindImplForMethod(Handle); if (implMapRid == 0) { return default(MethodImport); } return _reader.ImplMapTable.GetImport(implMapRid); } public CustomAttributeHandleCollection GetCustomAttributes() { return new CustomAttributeHandleCollection(_reader, Handle); } public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes() { return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle); } #region Projections private StringHandle GetProjectedName() { if ((Treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.DisposeMethod) { return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose); } return _reader.MethodDefTable.GetName(Handle); } private MethodAttributes GetProjectedFlags() { MethodAttributes flags = _reader.MethodDefTable.GetFlags(Handle); MethodDefTreatment treatment = Treatment; if ((treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.HiddenInterfaceImplementation) { flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Private; } if ((treatment & MethodDefTreatment.MarkAbstractFlag) != 0) { flags |= MethodAttributes.Abstract; } if ((treatment & MethodDefTreatment.MarkPublicFlag) != 0) { flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public; } return flags | MethodAttributes.HideBySig; } private MethodImplAttributes GetProjectedImplFlags() { MethodImplAttributes flags = _reader.MethodDefTable.GetImplFlags(Handle); switch (Treatment & MethodDefTreatment.KindMask) { case MethodDefTreatment.DelegateMethod: flags |= MethodImplAttributes.Runtime; break; case MethodDefTreatment.DisposeMethod: case MethodDefTreatment.AttributeMethod: case MethodDefTreatment.InterfaceMethod: case MethodDefTreatment.HiddenInterfaceImplementation: case MethodDefTreatment.Other: flags |= MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall; break; } return flags; } private BlobHandle GetProjectedSignature() { return _reader.MethodDefTable.GetSignature(Handle); } private int GetProjectedRelativeVirtualAddress() { return 0; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata { public readonly struct MethodDefinition { private readonly MetadataReader _reader; // Workaround: JIT doesn't generate good code for nested structures, so use RowId. private readonly uint _treatmentAndRowId; internal MethodDefinition(MetadataReader reader, uint treatmentAndRowId) { Debug.Assert(reader != null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; _treatmentAndRowId = treatmentAndRowId; } private int RowId { get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); } } private MethodDefTreatment Treatment { get { return (MethodDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); } } private MethodDefinitionHandle Handle { get { return MethodDefinitionHandle.FromRowId(RowId); } } public StringHandle Name { get { if (Treatment == 0) { return _reader.MethodDefTable.GetName(Handle); } return GetProjectedName(); } } public BlobHandle Signature { get { if (Treatment == 0) { return _reader.MethodDefTable.GetSignature(Handle); } return GetProjectedSignature(); } } public MethodSignature<TType> DecodeSignature<TType, TGenericContext>(ISignatureTypeProvider<TType, TGenericContext> provider, TGenericContext genericContext) { var decoder = new SignatureDecoder<TType, TGenericContext>(provider, _reader, genericContext); var blobReader = _reader.GetBlobReader(Signature); return decoder.DecodeMethodSignature(ref blobReader); } public int RelativeVirtualAddress { get { if (Treatment == 0) { return _reader.MethodDefTable.GetRva(Handle); } return GetProjectedRelativeVirtualAddress(); } } public MethodAttributes Attributes { get { if (Treatment == 0) { return _reader.MethodDefTable.GetFlags(Handle); } return GetProjectedFlags(); } } public MethodImplAttributes ImplAttributes { get { if (Treatment == 0) { return _reader.MethodDefTable.GetImplFlags(Handle); } return GetProjectedImplFlags(); } } 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 implMapRid = _reader.ImplMapTable.FindImplForMethod(Handle); if (implMapRid == 0) { return default(MethodImport); } return _reader.ImplMapTable.GetImport(implMapRid); } public CustomAttributeHandleCollection GetCustomAttributes() { return new CustomAttributeHandleCollection(_reader, Handle); } public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes() { return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle); } #region Projections private StringHandle GetProjectedName() { if ((Treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.DisposeMethod) { return StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.Dispose); } return _reader.MethodDefTable.GetName(Handle); } private MethodAttributes GetProjectedFlags() { MethodAttributes flags = _reader.MethodDefTable.GetFlags(Handle); MethodDefTreatment treatment = Treatment; if ((treatment & MethodDefTreatment.KindMask) == MethodDefTreatment.HiddenInterfaceImplementation) { flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Private; } if ((treatment & MethodDefTreatment.MarkAbstractFlag) != 0) { flags |= MethodAttributes.Abstract; } if ((treatment & MethodDefTreatment.MarkPublicFlag) != 0) { flags = (flags & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public; } return flags | MethodAttributes.HideBySig; } private MethodImplAttributes GetProjectedImplFlags() { MethodImplAttributes flags = _reader.MethodDefTable.GetImplFlags(Handle); switch (Treatment & MethodDefTreatment.KindMask) { case MethodDefTreatment.DelegateMethod: flags |= MethodImplAttributes.Runtime; break; case MethodDefTreatment.DisposeMethod: case MethodDefTreatment.AttributeMethod: case MethodDefTreatment.InterfaceMethod: case MethodDefTreatment.HiddenInterfaceImplementation: case MethodDefTreatment.Other: flags |= MethodImplAttributes.Runtime | MethodImplAttributes.InternalCall; break; } return flags; } private BlobHandle GetProjectedSignature() { return _reader.MethodDefTable.GetSignature(Handle); } private int GetProjectedRelativeVirtualAddress() { return 0; } #endregion } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.IO.Ports/tests/SerialPort/WriteLine_Generic.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Ports.Tests { public class WriteLine_Generic : PortsTest { //Set bounds for random timeout values. //If the min is to low write will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the write method and the testcase fails. private const double maxPercentageDifference = .15; //The string used when we expect the ReadCall to throw an exception for something other //then the contents of the string itself private const string DEFAULT_STRING = "DEFAULT_STRING"; //The string size used when veryifying BytesToWrite private static readonly int s_STRING_SIZE_BYTES_TO_WRITE = TCSupport.MinimumBlockingByteCount; //The string size used when veryifying Handshake private static readonly int s_STRING_SIZE_HANDSHAKE = TCSupport.MinimumBlockingByteCount; private const int NUM_TRYS = 5; #region Test Cases [Fact] public void WriteWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Case WriteWithoutOpen : Verifying write method throws System.InvalidOperationException without a call to Open()"); VerifyWriteException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Case WriteAfterFailedOpen : Verifying write method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a write method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyWriteException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Case WriteAfterClose : Verifying write method throws exception after a call to Close()"); com.Open(); com.Close(); VerifyWriteException(com, typeof(InvalidOperationException)); } } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void SimpleTimeout() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] XOffBuffer = new byte[1]; XOffBuffer[0] = 19; com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.XOnXOff; Debug.WriteLine("Case SimpleTimeout : Verifying WriteTimeout={0}", com1.WriteTimeout); com1.Open(); com2.Open(); com2.Write(XOffBuffer, 0, 1); Thread.Sleep(250); com2.Close(); VerifyTimeout(com1); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com.Handshake = Handshake.RequestToSendXOnXOff; com.Encoding = Encoding.Unicode; Debug.WriteLine("Case SuccessiveReadTimeout : Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); com.Open(); try { com.WriteLine(DEFAULT_STRING); } catch (TimeoutException) { } VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeoutWithWriteSucceeding() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); var t = new Task(asyncEnableRts.EnableRTS); com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.RequestToSend; com1.Encoding = new UTF8Encoding(); Debug.WriteLine("Case SuccessiveReadTimeoutWithWriteSucceeding : Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout); com1.Open(); //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed //before the timeout is reached t.Start(); TCSupport.WaitForTaskToStart(t); try { com1.WriteLine(DEFAULT_STRING); } catch (TimeoutException) { } asyncEnableRts.Stop(); TCSupport.WaitForTaskCompletion(t); VerifyTimeout(com1); } } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void BytesToWrite() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_BYTES_TO_WRITE); var t = new Task(asyncWriteRndStr.WriteRndStr); int numNewLineBytes; Debug.WriteLine("Case BytesToWrite : Verifying BytesToWrite with one call to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 500; numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray()); //Write a random string asynchronously so we can verify some things while the write call is blocking t.Start(); TCSupport.WaitForTaskToStart(t); TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes); TCSupport.WaitForTaskCompletion(t); } } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void BytesToWriteSuccessive() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_BYTES_TO_WRITE); var t1 = new Task(asyncWriteRndStr.WriteRndStr); var t2 = new Task(asyncWriteRndStr.WriteRndStr); int numNewLineBytes; Debug.WriteLine("Case BytesToWriteSuccessive : Verifying BytesToWrite with successive calls to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 1000; numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray()); //Write a random string asynchronously so we can verify some things while the write call is blocking t1.Start(); TCSupport.WaitForTaskToStart(t1); TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes); //Write a random string asynchronously so we can verify some things while the write call is blocking t2.Start(); TCSupport.WaitForTaskToStart(t2); TCSupport.WaitForWriteBufferToLoad(com, (s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes) * 2); //Wait for both write methods to timeout TCSupport.WaitForTaskCompletion(t1); var aggregatedException = Assert.Throws<AggregateException>(() => TCSupport.WaitForTaskCompletion(t2)); Assert.IsType<IOException>(aggregatedException.InnerException); } } [ConditionalFact(nameof(HasNullModem))] public void Handshake_None() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_HANDSHAKE); var t = new Task(asyncWriteRndStr.WriteRndStr); //Write a random string asynchronously so we can verify some things while the write call is blocking Debug.WriteLine("Case Handshake_None : Verifying Handshake=None"); com.Open(); t.Start(); TCSupport.WaitForTaskCompletion(t); Assert.Equal(0, com.BytesToWrite); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Handshake_RequestToSend() { Debug.WriteLine("Case Handshake_RequestToSend : Verifying Handshake=RequestToSend"); Verify_Handshake(Handshake.RequestToSend); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void Handshake_XOnXOff() { Debug.WriteLine("Case Handshake_XOnXOff : Verifying Handshake=XOnXOff"); Verify_Handshake(Handshake.XOnXOff); } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Handshake_RequestToSendXOnXOff() { Debug.WriteLine("Case Handshake_RequestToSendXOnXOff : Verifying Handshake=RequestToSendXOnXOff"); Verify_Handshake(Handshake.RequestToSendXOnXOff); } private class AsyncEnableRts { private bool _stop; public void EnableRTS() { lock (this) { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.RtsEnable = true; while (!_stop) Monitor.Wait(this); com2.RtsEnable = false; } } } public void Stop() { lock (this) { _stop = true; Monitor.Pulse(this); } } } private class AsyncWriteRndStr { private readonly SerialPort _com; private readonly int _strSize; public AsyncWriteRndStr(SerialPort com, int strSize) { _com = com; _strSize = strSize; } public void WriteRndStr() { string stringToWrite = TCSupport.GetRandomString(_strSize, TCSupport.CharacterOptions.Surrogates); try { _com.WriteLine(stringToWrite); } catch (TimeoutException) { } } } #endregion #region Verification for Test Cases private static void VerifyWriteException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.WriteLine(DEFAULT_STRING)); } private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.WriteTimeout; int actualTime = 0; double percentageDifference; try { com.WriteLine(DEFAULT_STRING); //Warm up write method } catch (TimeoutException) { } Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); try { com.WriteLine(DEFAULT_STRING); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void Verify_Handshake(Handshake handshake) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { byte[] XOffBuffer = new byte[1]; byte[] XOnBuffer = new byte[1]; XOffBuffer[0] = 19; XOnBuffer[0] = 17; int numNewLineBytes; Debug.WriteLine("Verifying Handshake={0}", handshake); com1.WriteTimeout = 3000; com1.Handshake = handshake; com1.Open(); com2.Open(); numNewLineBytes = com1.Encoding.GetByteCount(com1.NewLine.ToCharArray()); //Setup to ensure write will block with type of handshake method being used if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = false; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.Write(XOffBuffer, 0, 1); Thread.Sleep(250); } //Write a random string asynchronously so we can verify some things while the write call is blocking string randomLine = TCSupport.GetRandomString(s_STRING_SIZE_HANDSHAKE, TCSupport.CharacterOptions.Surrogates); byte[] randomLineBytes = com1.Encoding.GetBytes(randomLine); Task task = Task.Run(() => com1.WriteLine(randomLine)); TCSupport.WaitForTaskToStart(task); TCSupport.WaitForWriteBufferToLoad(com1, randomLineBytes.Length + numNewLineBytes); //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) { Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); } //Setup to ensure write will succeed if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = true; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.Write(XOnBuffer, 0, 1); } //Wait till write finishes TCSupport.WaitForTaskCompletion(task); Assert.Equal(0, com1.BytesToWrite); //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) { Fail("ERROR!!! Expected CtsHolding={0} actual {1}", true, com1.CtsHolding); } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Ports.Tests { public class WriteLine_Generic : PortsTest { //Set bounds for random timeout values. //If the min is to low write will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the write method and the testcase fails. private const double maxPercentageDifference = .15; //The string used when we expect the ReadCall to throw an exception for something other //then the contents of the string itself private const string DEFAULT_STRING = "DEFAULT_STRING"; //The string size used when veryifying BytesToWrite private static readonly int s_STRING_SIZE_BYTES_TO_WRITE = TCSupport.MinimumBlockingByteCount; //The string size used when veryifying Handshake private static readonly int s_STRING_SIZE_HANDSHAKE = TCSupport.MinimumBlockingByteCount; private const int NUM_TRYS = 5; #region Test Cases [Fact] public void WriteWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Case WriteWithoutOpen : Verifying write method throws System.InvalidOperationException without a call to Open()"); VerifyWriteException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Case WriteAfterFailedOpen : Verifying write method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a write method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyWriteException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Case WriteAfterClose : Verifying write method throws exception after a call to Close()"); com.Open(); com.Close(); VerifyWriteException(com, typeof(InvalidOperationException)); } } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void SimpleTimeout() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] XOffBuffer = new byte[1]; XOffBuffer[0] = 19; com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.XOnXOff; Debug.WriteLine("Case SimpleTimeout : Verifying WriteTimeout={0}", com1.WriteTimeout); com1.Open(); com2.Open(); com2.Write(XOffBuffer, 0, 1); Thread.Sleep(250); com2.Close(); VerifyTimeout(com1); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com.Handshake = Handshake.RequestToSendXOnXOff; com.Encoding = Encoding.Unicode; Debug.WriteLine("Case SuccessiveReadTimeout : Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); com.Open(); try { com.WriteLine(DEFAULT_STRING); } catch (TimeoutException) { } VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeoutWithWriteSucceeding() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); var t = new Task(asyncEnableRts.EnableRTS); com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.RequestToSend; com1.Encoding = new UTF8Encoding(); Debug.WriteLine("Case SuccessiveReadTimeoutWithWriteSucceeding : Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout); com1.Open(); //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed //before the timeout is reached t.Start(); TCSupport.WaitForTaskToStart(t); try { com1.WriteLine(DEFAULT_STRING); } catch (TimeoutException) { } asyncEnableRts.Stop(); TCSupport.WaitForTaskCompletion(t); VerifyTimeout(com1); } } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void BytesToWrite() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_BYTES_TO_WRITE); var t = new Task(asyncWriteRndStr.WriteRndStr); int numNewLineBytes; Debug.WriteLine("Case BytesToWrite : Verifying BytesToWrite with one call to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 500; numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray()); //Write a random string asynchronously so we can verify some things while the write call is blocking t.Start(); TCSupport.WaitForTaskToStart(t); TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes); TCSupport.WaitForTaskCompletion(t); } } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void BytesToWriteSuccessive() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_BYTES_TO_WRITE); var t1 = new Task(asyncWriteRndStr.WriteRndStr); var t2 = new Task(asyncWriteRndStr.WriteRndStr); int numNewLineBytes; Debug.WriteLine("Case BytesToWriteSuccessive : Verifying BytesToWrite with successive calls to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 1000; numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray()); //Write a random string asynchronously so we can verify some things while the write call is blocking t1.Start(); TCSupport.WaitForTaskToStart(t1); TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes); //Write a random string asynchronously so we can verify some things while the write call is blocking t2.Start(); TCSupport.WaitForTaskToStart(t2); TCSupport.WaitForWriteBufferToLoad(com, (s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes) * 2); //Wait for both write methods to timeout TCSupport.WaitForTaskCompletion(t1); var aggregatedException = Assert.Throws<AggregateException>(() => TCSupport.WaitForTaskCompletion(t2)); Assert.IsType<IOException>(aggregatedException.InnerException); } } [ConditionalFact(nameof(HasNullModem))] public void Handshake_None() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_HANDSHAKE); var t = new Task(asyncWriteRndStr.WriteRndStr); //Write a random string asynchronously so we can verify some things while the write call is blocking Debug.WriteLine("Case Handshake_None : Verifying Handshake=None"); com.Open(); t.Start(); TCSupport.WaitForTaskCompletion(t); Assert.Equal(0, com.BytesToWrite); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Handshake_RequestToSend() { Debug.WriteLine("Case Handshake_RequestToSend : Verifying Handshake=RequestToSend"); Verify_Handshake(Handshake.RequestToSend); } [KnownFailure] [ConditionalFact(nameof(HasNullModem))] public void Handshake_XOnXOff() { Debug.WriteLine("Case Handshake_XOnXOff : Verifying Handshake=XOnXOff"); Verify_Handshake(Handshake.XOnXOff); } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Handshake_RequestToSendXOnXOff() { Debug.WriteLine("Case Handshake_RequestToSendXOnXOff : Verifying Handshake=RequestToSendXOnXOff"); Verify_Handshake(Handshake.RequestToSendXOnXOff); } private class AsyncEnableRts { private bool _stop; public void EnableRTS() { lock (this) { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.RtsEnable = true; while (!_stop) Monitor.Wait(this); com2.RtsEnable = false; } } } public void Stop() { lock (this) { _stop = true; Monitor.Pulse(this); } } } private class AsyncWriteRndStr { private readonly SerialPort _com; private readonly int _strSize; public AsyncWriteRndStr(SerialPort com, int strSize) { _com = com; _strSize = strSize; } public void WriteRndStr() { string stringToWrite = TCSupport.GetRandomString(_strSize, TCSupport.CharacterOptions.Surrogates); try { _com.WriteLine(stringToWrite); } catch (TimeoutException) { } } } #endregion #region Verification for Test Cases private static void VerifyWriteException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.WriteLine(DEFAULT_STRING)); } private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.WriteTimeout; int actualTime = 0; double percentageDifference; try { com.WriteLine(DEFAULT_STRING); //Warm up write method } catch (TimeoutException) { } Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); try { com.WriteLine(DEFAULT_STRING); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void Verify_Handshake(Handshake handshake) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { byte[] XOffBuffer = new byte[1]; byte[] XOnBuffer = new byte[1]; XOffBuffer[0] = 19; XOnBuffer[0] = 17; int numNewLineBytes; Debug.WriteLine("Verifying Handshake={0}", handshake); com1.WriteTimeout = 3000; com1.Handshake = handshake; com1.Open(); com2.Open(); numNewLineBytes = com1.Encoding.GetByteCount(com1.NewLine.ToCharArray()); //Setup to ensure write will block with type of handshake method being used if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = false; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.Write(XOffBuffer, 0, 1); Thread.Sleep(250); } //Write a random string asynchronously so we can verify some things while the write call is blocking string randomLine = TCSupport.GetRandomString(s_STRING_SIZE_HANDSHAKE, TCSupport.CharacterOptions.Surrogates); byte[] randomLineBytes = com1.Encoding.GetBytes(randomLine); Task task = Task.Run(() => com1.WriteLine(randomLine)); TCSupport.WaitForTaskToStart(task); TCSupport.WaitForWriteBufferToLoad(com1, randomLineBytes.Length + numNewLineBytes); //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) { Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); } //Setup to ensure write will succeed if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = true; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.Write(XOnBuffer, 0, 1); } //Wait till write finishes TCSupport.WaitForTaskCompletion(task); Assert.Equal(0, com1.BytesToWrite); //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) { Fail("ERROR!!! Expected CtsHolding={0} actual {1}", true, com1.CtsHolding); } } } #endregion } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/JIT/Generics/Instantiation/delegates/Delegate008.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; internal delegate T GenDelegate<T>(T p1, out T p2); internal class Foo<T> { virtual public T Function<U>(U i, out U j) { j = i; return (T)(Object)i; } } internal class Test_Delegate008 { public static int Main() { int i, j; Foo<int> inst = new Foo<int>(); GenDelegate<int> MyDelegate = new GenDelegate<int>(inst.Function<int>); i = MyDelegate(10, out j); if ((i != 10) || (j != 10)) { Console.WriteLine("Failed Sync Invokation"); return 1; } Console.WriteLine("Test Passes"); return 100; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; internal delegate T GenDelegate<T>(T p1, out T p2); internal class Foo<T> { virtual public T Function<U>(U i, out U j) { j = i; return (T)(Object)i; } } internal class Test_Delegate008 { public static int Main() { int i, j; Foo<int> inst = new Foo<int>(); GenDelegate<int> MyDelegate = new GenDelegate<int>(inst.Function<int>); i = MyDelegate(10, out j); if ((i != 10) || (j != 10)) { Console.WriteLine("Failed Sync Invokation"); return 1; } Console.WriteLine("Test Passes"); return 100; } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; namespace System.Security.Cryptography.Xml { public sealed class ReferenceList : IList { private readonly ArrayList _references; public ReferenceList() { _references = new ArrayList(); } public IEnumerator GetEnumerator() { return _references.GetEnumerator(); } public int Count { get { return _references.Count; } } public int Add(object value!!) { if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); return _references.Add(value); } public void Clear() { _references.Clear(); } public bool Contains(object value) { return _references.Contains(value); } public int IndexOf(object value) { return _references.IndexOf(value); } public void Insert(int index, object value!!) { if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _references.Insert(index, value); } public void Remove(object value) { _references.Remove(value); } public void RemoveAt(int index) { _references.RemoveAt(index); } public EncryptedReference Item(int index) { return (EncryptedReference)_references[index]; } [System.Runtime.CompilerServices.IndexerName("ItemOf")] public EncryptedReference this[int index] { get { return Item(index); } set { ((IList)this)[index] = value; } } /// <internalonly/> object IList.this[int index] { get { return _references[index]; } set { if (value == null) throw new ArgumentNullException(nameof(value)); if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _references[index] = value; } } public void CopyTo(Array array, int index) { _references.CopyTo(array, index); } bool IList.IsFixedSize { get { return _references.IsFixedSize; } } bool IList.IsReadOnly { get { return _references.IsReadOnly; } } public object SyncRoot { get { return _references.SyncRoot; } } public bool IsSynchronized { get { return _references.IsSynchronized; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; namespace System.Security.Cryptography.Xml { public sealed class ReferenceList : IList { private readonly ArrayList _references; public ReferenceList() { _references = new ArrayList(); } public IEnumerator GetEnumerator() { return _references.GetEnumerator(); } public int Count { get { return _references.Count; } } public int Add(object value!!) { if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); return _references.Add(value); } public void Clear() { _references.Clear(); } public bool Contains(object value) { return _references.Contains(value); } public int IndexOf(object value) { return _references.IndexOf(value); } public void Insert(int index, object value!!) { if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _references.Insert(index, value); } public void Remove(object value) { _references.Remove(value); } public void RemoveAt(int index) { _references.RemoveAt(index); } public EncryptedReference Item(int index) { return (EncryptedReference)_references[index]; } [System.Runtime.CompilerServices.IndexerName("ItemOf")] public EncryptedReference this[int index] { get { return Item(index); } set { ((IList)this)[index] = value; } } /// <internalonly/> object IList.this[int index] { get { return _references[index]; } set { if (value == null) throw new ArgumentNullException(nameof(value)); if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _references[index] = value; } } public void CopyTo(Array array, int index) { _references.CopyTo(array, index); } bool IList.IsFixedSize { get { return _references.IsFixedSize; } } bool IList.IsReadOnly { get { return _references.IsReadOnly; } } public object SyncRoot { get { return _references.SyncRoot; } } public bool IsSynchronized { get { return _references.IsSynchronized; } } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Runtime/tests/System/Reflection/AssemblyMetadataAttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Reflection.Tests { public class AssemblyMetadataAttributeTests { [Theory] [InlineData(null, null)] [InlineData("", "")] [InlineData("key", "value")] public void Ctor_String_String(string key, string value) { var attribute = new AssemblyMetadataAttribute(key, value); Assert.Equal(key, attribute.Key); Assert.Equal(value, attribute.Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Reflection.Tests { public class AssemblyMetadataAttributeTests { [Theory] [InlineData(null, null)] [InlineData("", "")] [InlineData("key", "value")] public void Ctor_String_String(string key, string value) { var attribute = new AssemblyMetadataAttribute(key, value); Assert.Equal(key, attribute.Key); Assert.Equal(value, attribute.Value); } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Xml.Serialization; namespace System.Xml.Serialization { ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlReflectionMember { private string? _memberName; private Type? _type; private XmlAttributes _xmlAttributes = new XmlAttributes(); private SoapAttributes _soapAttributes = new SoapAttributes(); private bool _isReturnValue; private bool _overrideIsNullable; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Type? MemberType { get { return _type; } set { _type = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttributes XmlAttributes { get { return _xmlAttributes; } set { _xmlAttributes = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapAttributes SoapAttributes { get { return _soapAttributes; } set { _soapAttributes = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string MemberName { get { return _memberName == null ? string.Empty : _memberName; } set { _memberName = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsReturnValue { get { return _isReturnValue; } set { _isReturnValue = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool OverrideIsNullable { get { return _overrideIsNullable; } set { _overrideIsNullable = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Xml.Serialization; namespace System.Xml.Serialization { ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlReflectionMember { private string? _memberName; private Type? _type; private XmlAttributes _xmlAttributes = new XmlAttributes(); private SoapAttributes _soapAttributes = new SoapAttributes(); private bool _isReturnValue; private bool _overrideIsNullable; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Type? MemberType { get { return _type; } set { _type = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttributes XmlAttributes { get { return _xmlAttributes; } set { _xmlAttributes = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapAttributes SoapAttributes { get { return _soapAttributes; } set { _soapAttributes = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string MemberName { get { return _memberName == null ? string.Empty : _memberName; } set { _memberName = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsReturnValue { get { return _isReturnValue; } set { _isReturnValue = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool OverrideIsNullable { get { return _overrideIsNullable; } set { _overrideIsNullable = value; } } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellman.Xml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography { public abstract partial class ECDiffieHellman : ECAlgorithm { public override void FromXmlString(string xmlString) { throw new NotImplementedException(SR.Cryptography_ECXmlSerializationFormatRequired); } public override string ToXmlString(bool includePrivateParameters) { throw new NotImplementedException(SR.Cryptography_ECXmlSerializationFormatRequired); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography { public abstract partial class ECDiffieHellman : ECAlgorithm { public override void FromXmlString(string xmlString) { throw new NotImplementedException(SR.Cryptography_ECXmlSerializationFormatRequired); } public override string ToXmlString(bool includePrivateParameters) { throw new NotImplementedException(SR.Cryptography_ECXmlSerializationFormatRequired); } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/JIT/Methodical/VT/etc/han3_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="han3.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="han3.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/JIT/jit64/valuetypes/nullable/castclass/null/castclass-null014.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="castclass-null014.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="castclass-null014.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/coreclr/vm/gcheaputilities.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _GCHEAPUTILITIES_H_ #define _GCHEAPUTILITIES_H_ #include "gcinterface.h" // The singular heap instance. GPTR_DECL(IGCHeap, g_pGCHeap); #ifndef DACCESS_COMPILE extern "C" { #endif // !DACCESS_COMPILE GPTR_DECL(uint8_t,g_lowest_address); GPTR_DECL(uint8_t,g_highest_address); GPTR_DECL(uint32_t,g_card_table); GVAL_DECL(GCHeapType, g_heap_type); #ifndef DACCESS_COMPILE } #endif // !DACCESS_COMPILE // For single-proc machines, the EE will use a single, shared alloc context // for all allocations. In order to avoid extra indirections in assembly // allocation helpers, the EE owns the global allocation context and the // GC will update it when it needs to. extern "C" gc_alloc_context g_global_alloc_context; extern "C" uint32_t* g_card_bundle_table; extern "C" uint8_t* g_ephemeral_low; extern "C" uint8_t* g_ephemeral_high; #ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP // Table containing the dirty state. This table is translated to exclude the lowest address it represents, see // TranslateTableToExcludeHeapStartAddress. extern "C" uint8_t *g_sw_ww_table; // Write watch may be disabled when it is not needed (between GCs for instance). This indicates whether it is enabled. extern "C" bool g_sw_ww_enabled_for_gc_heap; #endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP // g_gc_dac_vars is a structure of pointers to GC globals that the // DAC uses. It is not exposed directly to the DAC. extern GcDacVars g_gc_dac_vars; // Instead of exposing g_gc_dac_vars to the DAC, a pointer to it // is exposed here (g_gcDacGlobals). The reason for this is to avoid // a problem in which a debugger attaches to a program while the program // is in the middle of initializing the GC DAC vars - if the "publishing" // of DAC vars isn't atomic, the debugger could see a partially initialized // GcDacVars structure. // // Instead, the debuggee "publishes" GcDacVars by assigning a pointer to g_gc_dac_vars // to this global, and the DAC will read this global. typedef DPTR(GcDacVars) PTR_GcDacVars; GPTR_DECL(GcDacVars, g_gcDacGlobals); // GCHeapUtilities provides a number of static methods // that operate on the global heap instance. It can't be // instantiated. class GCHeapUtilities { public: // Retrieves the GC heap. inline static IGCHeap* GetGCHeap() { LIMITED_METHOD_CONTRACT; assert(g_pGCHeap != nullptr); return g_pGCHeap; } // Returns true if the heap has been initialized, false otherwise. inline static bool IsGCHeapInitialized() { LIMITED_METHOD_CONTRACT; return g_pGCHeap != nullptr; } // Returns true if a the heap is initialized and a garbage collection // is in progress, false otherwise. inline static bool IsGCInProgress(bool bConsiderGCStart = false) { WRAPPER_NO_CONTRACT; return (IsGCHeapInitialized() ? GetGCHeap()->IsGCInProgressHelper(bConsiderGCStart) : false); } // Returns true if we should be competing marking for statics. This // influences the behavior of `GCToEEInterface::GcScanRoots`. inline static bool MarkShouldCompeteForStatics() { WRAPPER_NO_CONTRACT; return IsServerHeap() && g_SystemInfo.dwNumberOfProcessors >= 2; } // Waits until a GC is complete, if the heap has been initialized. inline static void WaitForGCCompletion(bool bConsiderGCStart = false) { WRAPPER_NO_CONTRACT; if (IsGCHeapInitialized()) GetGCHeap()->WaitUntilGCComplete(bConsiderGCStart); } // Returns true if the held GC heap is a Server GC heap, false otherwise. inline static bool IsServerHeap() { LIMITED_METHOD_CONTRACT; #ifdef FEATURE_SVR_GC _ASSERTE(g_heap_type != GC_HEAP_INVALID); return g_heap_type == GC_HEAP_SVR; #else return false; #endif // FEATURE_SVR_GC } static bool UseThreadAllocationContexts() { // When running on a single-proc Intel system, it's more efficient to use a single global // allocation context for SOH allocations than to use one for every thread. #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && !defined(TARGET_UNIX) return IsServerHeap() || ::g_SystemInfo.dwNumberOfProcessors != 1 || CPUGroupInfo::CanEnableGCCPUGroups(); #else return true; #endif } #ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP // Returns True if software write watch is currently enabled for the GC Heap, // or False if it is not. inline static bool SoftwareWriteWatchIsEnabled() { WRAPPER_NO_CONTRACT; return g_sw_ww_enabled_for_gc_heap; } // In accordance with the SoftwareWriteWatch scheme, marks a given address as // "dirty" (e.g. has been written to). inline static void SoftwareWriteWatchSetDirty(void* address, size_t write_size) { LIMITED_METHOD_CONTRACT; // We presumably have just written something to this address, so it can't be null. assert(address != nullptr); // The implementation is limited to writes of a pointer size or less. Writes larger // than pointer size may cross page boundaries and would require us to potentially // set more than one entry in the SWW table, which can't be done atomically under // the current scheme. assert(write_size <= sizeof(void*)); size_t table_byte_index = reinterpret_cast<size_t>(address) >> SOFTWARE_WRITE_WATCH_AddressToTableByteIndexShift; // The table byte index that we calculate for the address should be the same as the one // calculated for a pointer to the end of the written region. If this were not the case, // this write crossed a boundary and would dirty two pages. #ifdef _DEBUG uint8_t* end_of_write_ptr = reinterpret_cast<uint8_t*>(address) + (write_size - 1); assert(table_byte_index == reinterpret_cast<size_t>(end_of_write_ptr) >> SOFTWARE_WRITE_WATCH_AddressToTableByteIndexShift); #endif uint8_t* table_address = &g_sw_ww_table[table_byte_index]; if (*table_address == 0) { *table_address = 0xFF; } } // In accordance with the SoftwareWriteWatch scheme, marks a range of addresses // as dirty, starting at the given address and with the given length. inline static void SoftwareWriteWatchSetDirtyRegion(void* address, size_t length) { LIMITED_METHOD_CONTRACT; // We presumably have just memcopied something to this address, so it can't be null. assert(address != nullptr); // The "base index" is the first index in the SWW table that covers the target // region of memory. size_t base_index = reinterpret_cast<size_t>(address) >> SOFTWARE_WRITE_WATCH_AddressToTableByteIndexShift; // The "end_index" is the last index in the SWW table that covers the target // region of memory. uint8_t* end_pointer = reinterpret_cast<uint8_t*>(address) + length - 1; size_t end_index = reinterpret_cast<size_t>(end_pointer) >> SOFTWARE_WRITE_WATCH_AddressToTableByteIndexShift; // We'll mark the entire region of memory as dirty by memseting all entries in // the SWW table between the start and end indexes. memset(&g_sw_ww_table[base_index], ~0, end_index - base_index + 1); } #endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP #ifndef DACCESS_COMPILE // Gets a pointer to the module that contains the GC. static PTR_VOID GetGCModuleBase(); // Loads (if using a standalone GC) and initializes the GC. static HRESULT LoadAndInitialize(); // Records a change in eventing state. This ultimately will inform the GC that it needs to be aware // of new events being enabled. static void RecordEventStateChange(bool isPublicProvider, GCEventKeyword keywords, GCEventLevel level); #endif // DACCESS_COMPILE private: // This class should never be instantiated. GCHeapUtilities() = delete; }; #endif // _GCHEAPUTILITIES_H_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _GCHEAPUTILITIES_H_ #define _GCHEAPUTILITIES_H_ #include "gcinterface.h" // The singular heap instance. GPTR_DECL(IGCHeap, g_pGCHeap); #ifndef DACCESS_COMPILE extern "C" { #endif // !DACCESS_COMPILE GPTR_DECL(uint8_t,g_lowest_address); GPTR_DECL(uint8_t,g_highest_address); GPTR_DECL(uint32_t,g_card_table); GVAL_DECL(GCHeapType, g_heap_type); #ifndef DACCESS_COMPILE } #endif // !DACCESS_COMPILE // For single-proc machines, the EE will use a single, shared alloc context // for all allocations. In order to avoid extra indirections in assembly // allocation helpers, the EE owns the global allocation context and the // GC will update it when it needs to. extern "C" gc_alloc_context g_global_alloc_context; extern "C" uint32_t* g_card_bundle_table; extern "C" uint8_t* g_ephemeral_low; extern "C" uint8_t* g_ephemeral_high; #ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP // Table containing the dirty state. This table is translated to exclude the lowest address it represents, see // TranslateTableToExcludeHeapStartAddress. extern "C" uint8_t *g_sw_ww_table; // Write watch may be disabled when it is not needed (between GCs for instance). This indicates whether it is enabled. extern "C" bool g_sw_ww_enabled_for_gc_heap; #endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP // g_gc_dac_vars is a structure of pointers to GC globals that the // DAC uses. It is not exposed directly to the DAC. extern GcDacVars g_gc_dac_vars; // Instead of exposing g_gc_dac_vars to the DAC, a pointer to it // is exposed here (g_gcDacGlobals). The reason for this is to avoid // a problem in which a debugger attaches to a program while the program // is in the middle of initializing the GC DAC vars - if the "publishing" // of DAC vars isn't atomic, the debugger could see a partially initialized // GcDacVars structure. // // Instead, the debuggee "publishes" GcDacVars by assigning a pointer to g_gc_dac_vars // to this global, and the DAC will read this global. typedef DPTR(GcDacVars) PTR_GcDacVars; GPTR_DECL(GcDacVars, g_gcDacGlobals); // GCHeapUtilities provides a number of static methods // that operate on the global heap instance. It can't be // instantiated. class GCHeapUtilities { public: // Retrieves the GC heap. inline static IGCHeap* GetGCHeap() { LIMITED_METHOD_CONTRACT; assert(g_pGCHeap != nullptr); return g_pGCHeap; } // Returns true if the heap has been initialized, false otherwise. inline static bool IsGCHeapInitialized() { LIMITED_METHOD_CONTRACT; return g_pGCHeap != nullptr; } // Returns true if a the heap is initialized and a garbage collection // is in progress, false otherwise. inline static bool IsGCInProgress(bool bConsiderGCStart = false) { WRAPPER_NO_CONTRACT; return (IsGCHeapInitialized() ? GetGCHeap()->IsGCInProgressHelper(bConsiderGCStart) : false); } // Returns true if we should be competing marking for statics. This // influences the behavior of `GCToEEInterface::GcScanRoots`. inline static bool MarkShouldCompeteForStatics() { WRAPPER_NO_CONTRACT; return IsServerHeap() && g_SystemInfo.dwNumberOfProcessors >= 2; } // Waits until a GC is complete, if the heap has been initialized. inline static void WaitForGCCompletion(bool bConsiderGCStart = false) { WRAPPER_NO_CONTRACT; if (IsGCHeapInitialized()) GetGCHeap()->WaitUntilGCComplete(bConsiderGCStart); } // Returns true if the held GC heap is a Server GC heap, false otherwise. inline static bool IsServerHeap() { LIMITED_METHOD_CONTRACT; #ifdef FEATURE_SVR_GC _ASSERTE(g_heap_type != GC_HEAP_INVALID); return g_heap_type == GC_HEAP_SVR; #else return false; #endif // FEATURE_SVR_GC } static bool UseThreadAllocationContexts() { // When running on a single-proc Intel system, it's more efficient to use a single global // allocation context for SOH allocations than to use one for every thread. #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && !defined(TARGET_UNIX) return IsServerHeap() || ::g_SystemInfo.dwNumberOfProcessors != 1 || CPUGroupInfo::CanEnableGCCPUGroups(); #else return true; #endif } #ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP // Returns True if software write watch is currently enabled for the GC Heap, // or False if it is not. inline static bool SoftwareWriteWatchIsEnabled() { WRAPPER_NO_CONTRACT; return g_sw_ww_enabled_for_gc_heap; } // In accordance with the SoftwareWriteWatch scheme, marks a given address as // "dirty" (e.g. has been written to). inline static void SoftwareWriteWatchSetDirty(void* address, size_t write_size) { LIMITED_METHOD_CONTRACT; // We presumably have just written something to this address, so it can't be null. assert(address != nullptr); // The implementation is limited to writes of a pointer size or less. Writes larger // than pointer size may cross page boundaries and would require us to potentially // set more than one entry in the SWW table, which can't be done atomically under // the current scheme. assert(write_size <= sizeof(void*)); size_t table_byte_index = reinterpret_cast<size_t>(address) >> SOFTWARE_WRITE_WATCH_AddressToTableByteIndexShift; // The table byte index that we calculate for the address should be the same as the one // calculated for a pointer to the end of the written region. If this were not the case, // this write crossed a boundary and would dirty two pages. #ifdef _DEBUG uint8_t* end_of_write_ptr = reinterpret_cast<uint8_t*>(address) + (write_size - 1); assert(table_byte_index == reinterpret_cast<size_t>(end_of_write_ptr) >> SOFTWARE_WRITE_WATCH_AddressToTableByteIndexShift); #endif uint8_t* table_address = &g_sw_ww_table[table_byte_index]; if (*table_address == 0) { *table_address = 0xFF; } } // In accordance with the SoftwareWriteWatch scheme, marks a range of addresses // as dirty, starting at the given address and with the given length. inline static void SoftwareWriteWatchSetDirtyRegion(void* address, size_t length) { LIMITED_METHOD_CONTRACT; // We presumably have just memcopied something to this address, so it can't be null. assert(address != nullptr); // The "base index" is the first index in the SWW table that covers the target // region of memory. size_t base_index = reinterpret_cast<size_t>(address) >> SOFTWARE_WRITE_WATCH_AddressToTableByteIndexShift; // The "end_index" is the last index in the SWW table that covers the target // region of memory. uint8_t* end_pointer = reinterpret_cast<uint8_t*>(address) + length - 1; size_t end_index = reinterpret_cast<size_t>(end_pointer) >> SOFTWARE_WRITE_WATCH_AddressToTableByteIndexShift; // We'll mark the entire region of memory as dirty by memseting all entries in // the SWW table between the start and end indexes. memset(&g_sw_ww_table[base_index], ~0, end_index - base_index + 1); } #endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP #ifndef DACCESS_COMPILE // Gets a pointer to the module that contains the GC. static PTR_VOID GetGCModuleBase(); // Loads (if using a standalone GC) and initializes the GC. static HRESULT LoadAndInitialize(); // Records a change in eventing state. This ultimately will inform the GC that it needs to be aware // of new events being enabled. static void RecordEventStateChange(bool isPublicProvider, GCEventKeyword keywords, GCEventLevel level); #endif // DACCESS_COMPILE private: // This class should never be instantiated. GCHeapUtilities() = delete; }; #endif // _GCHEAPUTILITIES_H_
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/ForwarderMarshallingGeneratorFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Interop { internal class ForwarderMarshallingGeneratorFactory : IMarshallingGeneratorFactory { private static readonly Forwarder s_forwarder = new Forwarder(); public IMarshallingGenerator Create(TypePositionInfo info, StubCodeContext context) => s_forwarder; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.Interop { internal class ForwarderMarshallingGeneratorFactory : IMarshallingGeneratorFactory { private static readonly Forwarder s_forwarder = new Forwarder(); public IMarshallingGenerator Create(TypePositionInfo info, StubCodeContext context) => s_forwarder; } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/baseservices/threading/generics/TimerCallback/thread23.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="thread23.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="thread23.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/JIT/HardwareIntrinsics/General/Vector128/GreaterThanOrEqualAll.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GreaterThanOrEqualAllByte() { var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte testClass) { var result = Vector128.GreaterThanOrEqualAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.GreaterThanOrEqualAll( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanOrEqualAll), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanOrEqualAll), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Byte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.GreaterThanOrEqualAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Vector128.GreaterThanOrEqualAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte(); var result = Vector128.GreaterThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.GreaterThanOrEqualAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.GreaterThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] >= right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.GreaterThanOrEqualAll)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GreaterThanOrEqualAllByte() { var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte testClass) { var result = Vector128.GreaterThanOrEqualAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.GreaterThanOrEqualAll( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanOrEqualAll), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanOrEqualAll), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Byte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.GreaterThanOrEqualAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Vector128.GreaterThanOrEqualAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllByte(); var result = Vector128.GreaterThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.GreaterThanOrEqualAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.GreaterThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] >= right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.GreaterThanOrEqualAll)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/tests/JIT/jit64/mcc/interop/mcc_i33.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> <!-- Test unsupported outside of windows --> <CLRTestTargetUnsupported Condition="'$(TargetsWindows)' != 'true'">true</CLRTestTargetUnsupported> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="mcc_i33.il ..\common\common.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="CMakeLists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> <!-- Test unsupported outside of windows --> <CLRTestTargetUnsupported Condition="'$(TargetsWindows)' != 'true'">true</CLRTestTargetUnsupported> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="mcc_i33.il ..\common\common.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="CMakeLists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/coreclr/pal/src/libunwind/src/tilegx/Lglobal.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gglobal.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gglobal.c" #endif
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ITypeDescriptorFilterService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; namespace System.ComponentModel.Design { /// <summary> /// Modifies the set of type descriptors that a component provides. /// </summary> public interface ITypeDescriptorFilterService { /// <summary> /// Provides a way to filter the attributes from a component that are displayed to the user. /// </summary> bool FilterAttributes(IComponent component, IDictionary attributes); /// <summary> /// Provides a way to filter the events from a component that are displayed to the user. /// </summary> bool FilterEvents(IComponent component, IDictionary events); /// <summary> /// Provides a way to filter the properties from a component that are displayed to the user. /// </summary> bool FilterProperties(IComponent component, IDictionary properties); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; namespace System.ComponentModel.Design { /// <summary> /// Modifies the set of type descriptors that a component provides. /// </summary> public interface ITypeDescriptorFilterService { /// <summary> /// Provides a way to filter the attributes from a component that are displayed to the user. /// </summary> bool FilterAttributes(IComponent component, IDictionary attributes); /// <summary> /// Provides a way to filter the events from a component that are displayed to the user. /// </summary> bool FilterEvents(IComponent component, IDictionary events); /// <summary> /// Provides a way to filter the properties from a component that are displayed to the user. /// </summary> bool FilterProperties(IComponent component, IDictionary properties); } }
-1
dotnet/runtime
66,178
Clean up stale use of runtextbeg/end in RegexInterpreter
stephentoub
2022-03-04T02:45:31Z
2022-03-04T20:33:55Z
94b830f2a8599ea44e719d23f2132069a02bbc44
b259ef087d3faf2e3147e2bc21369b03794eae0d
Clean up stale use of runtextbeg/end in RegexInterpreter.
./src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ClassInterfaceType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.InteropServices { public enum ClassInterfaceType { None = 0, AutoDispatch = 1, AutoDual = 2 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.InteropServices { public enum ClassInterfaceType { None = 0, AutoDispatch = 1, AutoDual = 2 } }
-1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonCollectionConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization.Metadata; namespace System.Text.Json.Serialization { /// <summary> /// Base class for all collections. Collections are assumed to implement <see cref="IEnumerable{T}"/> /// or a variant thereof e.g. <see cref="IAsyncEnumerable{T}"/>. /// </summary> internal abstract class JsonCollectionConverter<TCollection, TElement> : JsonResumableConverter<TCollection> { internal sealed override ConverterStrategy ConverterStrategy => ConverterStrategy.Enumerable; internal override Type ElementType => typeof(TElement); protected abstract void Add(in TElement value, ref ReadStack state); /// <summary> /// When overridden, create the collection. It may be a temporary collection or the final collection. /// </summary> protected virtual void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { JsonTypeInfo typeInfo = state.Current.JsonTypeInfo; if (typeInfo.CreateObject is null) { // The contract model was not able to produce a default constructor for two possible reasons: // 1. Either the declared collection type is abstract and cannot be instantiated. // 2. The collection type does not specify a default constructor. if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } else { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } } state.Current.ReturnValue = typeInfo.CreateObject()!; Debug.Assert(state.Current.ReturnValue is TCollection); } protected virtual void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) { } protected static JsonConverter<TElement> GetElementConverter(JsonTypeInfo elementTypeInfo) { JsonConverter<TElement> converter = (JsonConverter<TElement>)elementTypeInfo.PropertyInfoForTypeInfo.ConverterBase; Debug.Assert(converter != null); // It should not be possible to have a null converter at this point. return converter; } protected static JsonConverter<TElement> GetElementConverter(ref WriteStack state) { JsonConverter<TElement> converter = (JsonConverter<TElement>)state.Current.JsonPropertyInfo!.ConverterBase; Debug.Assert(converter != null); // It should not be possible to have a null converter at this point. return converter; } internal override bool OnTryRead( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out TCollection value) { JsonTypeInfo elementTypeInfo = state.Current.JsonTypeInfo.ElementTypeInfo!; if (state.UseFastPath) { // Fast path that avoids maintaining state variables and dealing with preserved references. if (reader.TokenType != JsonTokenType.StartArray) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } CreateCollection(ref reader, ref state, options); JsonConverter<TElement> elementConverter = GetElementConverter(elementTypeInfo); if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) { // Fast path that avoids validation and extra indirection. while (true) { reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndArray) { break; } // Obtain the CLR value from the JSON and apply to the object. TElement? element = elementConverter.Read(ref reader, elementConverter.TypeToConvert, options); Add(element!, ref state); } } else { // Process all elements. while (true) { reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndArray) { break; } // Get the value from the converter and add it. elementConverter.TryRead(ref reader, typeof(TElement), options, ref state, out TElement? element); Add(element!, ref state); } } } else { // Slower path that supports continuation and preserved references. bool preserveReferences = options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve; if (state.Current.ObjectState == StackFrameObjectState.None) { if (reader.TokenType == JsonTokenType.StartArray) { state.Current.ObjectState = StackFrameObjectState.PropertyValue; } else if (preserveReferences) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.StartToken; } else { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } } // Handle the metadata properties. if (preserveReferences && state.Current.ObjectState < StackFrameObjectState.PropertyValue) { if (JsonSerializer.ResolveMetadataForJsonArray<TCollection>(ref reader, ref state, options)) { if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject) { // This will never throw since it was previously validated in ResolveMetadataForJsonArray. value = (TCollection)state.Current.ReturnValue!; return true; } } else { value = default; return false; } } if (state.Current.ObjectState < StackFrameObjectState.CreatedObject) { CreateCollection(ref reader, ref state, options); state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo!.PropertyInfoForTypeInfo; state.Current.ObjectState = StackFrameObjectState.CreatedObject; } if (state.Current.ObjectState < StackFrameObjectState.ReadElements) { JsonConverter<TElement> elementConverter = GetElementConverter(elementTypeInfo); // Process all elements. while (true) { if (state.Current.PropertyState < StackFramePropertyState.ReadValue) { state.Current.PropertyState = StackFramePropertyState.ReadValue; if (!SingleValueReadWithReadAhead(elementConverter.RequiresReadAhead, ref reader, ref state)) { value = default; return false; } } if (state.Current.PropertyState < StackFramePropertyState.ReadValueIsEnd) { if (reader.TokenType == JsonTokenType.EndArray) { break; } state.Current.PropertyState = StackFramePropertyState.ReadValueIsEnd; } if (state.Current.PropertyState < StackFramePropertyState.TryRead) { // Get the value from the converter and add it. if (!elementConverter.TryRead(ref reader, typeof(TElement), options, ref state, out TElement? element)) { value = default; return false; } Add(element!, ref state); // No need to set PropertyState to TryRead since we're done with this element now. state.Current.EndElement(); } } state.Current.ObjectState = StackFrameObjectState.ReadElements; } if (state.Current.ObjectState < StackFrameObjectState.EndToken) { state.Current.ObjectState = StackFrameObjectState.EndToken; // Read the EndObject token for an array with preserve semantics. if (state.Current.ValidateEndTokenOnArray) { if (!reader.Read()) { value = default; return false; } } } if (state.Current.ObjectState < StackFrameObjectState.EndTokenValidation) { if (state.Current.ValidateEndTokenOnArray) { if (reader.TokenType != JsonTokenType.EndObject) { Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); ThrowHelper.ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref state, typeToConvert, 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 success; if (value == null) { writer.WriteNullValue(); success = true; } else { if (!state.Current.ProcessedStartToken) { state.Current.ProcessedStartToken = true; if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve) { MetadataPropertyName metadata = JsonSerializer.WriteReferenceForCollection(this, ref state, writer); Debug.Assert(metadata != MetadataPropertyName.Ref); state.Current.MetadataPropertyName = metadata; } else { writer.WriteStartArray(); } state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo!.PropertyInfoForTypeInfo; } success = OnWriteResume(writer, value, options, ref state); if (success) { if (!state.Current.ProcessedEndToken) { state.Current.ProcessedEndToken = true; writer.WriteEndArray(); if (state.Current.MetadataPropertyName == MetadataPropertyName.Id) { // Write the EndObject for $values. writer.WriteEndObject(); } } } } return success; } protected abstract bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state); internal sealed override void CreateInstanceForReferenceResolver(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) => CreateCollection(ref reader, ref state, options); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization.Metadata; namespace System.Text.Json.Serialization { /// <summary> /// Base class for all collections. Collections are assumed to implement <see cref="IEnumerable{T}"/> /// or a variant thereof e.g. <see cref="IAsyncEnumerable{T}"/>. /// </summary> internal abstract class JsonCollectionConverter<TCollection, TElement> : JsonResumableConverter<TCollection> { internal sealed override ConverterStrategy ConverterStrategy => ConverterStrategy.Enumerable; internal override Type ElementType => typeof(TElement); protected abstract void Add(in TElement value, ref ReadStack state); /// <summary> /// When overridden, create the collection. It may be a temporary collection or the final collection. /// </summary> protected virtual void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) { JsonTypeInfo typeInfo = state.Current.JsonTypeInfo; if (typeInfo.CreateObject is null) { // The contract model was not able to produce a default constructor for two possible reasons: // 1. Either the declared collection type is abstract and cannot be instantiated. // 2. The collection type does not specify a default constructor. if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } else { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } } state.Current.ReturnValue = typeInfo.CreateObject()!; Debug.Assert(state.Current.ReturnValue is TCollection); } protected virtual void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) { } protected static JsonConverter<TElement> GetElementConverter(JsonTypeInfo elementTypeInfo) { JsonConverter<TElement> converter = (JsonConverter<TElement>)elementTypeInfo.PropertyInfoForTypeInfo.ConverterBase; Debug.Assert(converter != null); // It should not be possible to have a null converter at this point. return converter; } protected static JsonConverter<TElement> GetElementConverter(ref WriteStack state) { JsonConverter<TElement> converter = (JsonConverter<TElement>)state.Current.JsonPropertyInfo!.ConverterBase; Debug.Assert(converter != null); // It should not be possible to have a null converter at this point. return converter; } internal override bool OnTryRead( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out TCollection value) { JsonTypeInfo elementTypeInfo = state.Current.JsonTypeInfo.ElementTypeInfo!; if (state.UseFastPath) { // Fast path that avoids maintaining state variables and dealing with preserved references. if (reader.TokenType != JsonTokenType.StartArray) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } CreateCollection(ref reader, ref state, options); state.Current.JsonPropertyInfo = elementTypeInfo.PropertyInfoForTypeInfo; JsonConverter<TElement> elementConverter = GetElementConverter(elementTypeInfo); if (elementConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) { // Fast path that avoids validation and extra indirection. while (true) { reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndArray) { break; } // Obtain the CLR value from the JSON and apply to the object. TElement? element = elementConverter.Read(ref reader, elementConverter.TypeToConvert, options); Add(element!, ref state); } } else { // Process all elements. while (true) { reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndArray) { break; } // Get the value from the converter and add it. elementConverter.TryRead(ref reader, typeof(TElement), options, ref state, out TElement? element); Add(element!, ref state); } } } else { // Slower path that supports continuation and preserved references. bool preserveReferences = options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve; if (state.Current.ObjectState == StackFrameObjectState.None) { if (reader.TokenType == JsonTokenType.StartArray) { state.Current.ObjectState = StackFrameObjectState.PropertyValue; } else if (preserveReferences) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.StartToken; } else { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.JsonPropertyInfo = elementTypeInfo.PropertyInfoForTypeInfo; } // Handle the metadata properties. if (preserveReferences && state.Current.ObjectState < StackFrameObjectState.PropertyValue) { if (JsonSerializer.ResolveMetadataForJsonArray<TCollection>(ref reader, ref state, options)) { if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject) { // This will never throw since it was previously validated in ResolveMetadataForJsonArray. value = (TCollection)state.Current.ReturnValue!; return true; } } else { value = default; return false; } } if (state.Current.ObjectState < StackFrameObjectState.CreatedObject) { CreateCollection(ref reader, ref state, options); state.Current.ObjectState = StackFrameObjectState.CreatedObject; } if (state.Current.ObjectState < StackFrameObjectState.ReadElements) { JsonConverter<TElement> elementConverter = GetElementConverter(elementTypeInfo); // Process all elements. while (true) { if (state.Current.PropertyState < StackFramePropertyState.ReadValue) { state.Current.PropertyState = StackFramePropertyState.ReadValue; if (!SingleValueReadWithReadAhead(elementConverter.RequiresReadAhead, ref reader, ref state)) { value = default; return false; } } if (state.Current.PropertyState < StackFramePropertyState.ReadValueIsEnd) { if (reader.TokenType == JsonTokenType.EndArray) { break; } state.Current.PropertyState = StackFramePropertyState.ReadValueIsEnd; } if (state.Current.PropertyState < StackFramePropertyState.TryRead) { // Get the value from the converter and add it. if (!elementConverter.TryRead(ref reader, typeof(TElement), options, ref state, out TElement? element)) { value = default; return false; } Add(element!, ref state); // No need to set PropertyState to TryRead since we're done with this element now. state.Current.EndElement(); } } state.Current.ObjectState = StackFrameObjectState.ReadElements; } if (state.Current.ObjectState < StackFrameObjectState.EndToken) { state.Current.ObjectState = StackFrameObjectState.EndToken; // Read the EndObject token for an array with preserve semantics. if (state.Current.ValidateEndTokenOnArray) { if (!reader.Read()) { value = default; return false; } } } if (state.Current.ObjectState < StackFrameObjectState.EndTokenValidation) { if (state.Current.ValidateEndTokenOnArray) { if (reader.TokenType != JsonTokenType.EndObject) { Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); ThrowHelper.ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref state, typeToConvert, 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 success; if (value == null) { writer.WriteNullValue(); success = true; } else { if (!state.Current.ProcessedStartToken) { state.Current.ProcessedStartToken = true; if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve) { MetadataPropertyName metadata = JsonSerializer.WriteReferenceForCollection(this, ref state, writer); Debug.Assert(metadata != MetadataPropertyName.Ref); state.Current.MetadataPropertyName = metadata; } else { writer.WriteStartArray(); } state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo!.PropertyInfoForTypeInfo; } success = OnWriteResume(writer, value, options, ref state); if (success) { if (!state.Current.ProcessedEndToken) { state.Current.ProcessedEndToken = true; writer.WriteEndArray(); if (state.Current.MetadataPropertyName == MetadataPropertyName.Id) { // Write the EndObject for $values. writer.WriteEndObject(); } } } } return success; } protected abstract bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state); internal sealed override void CreateInstanceForReferenceResolver(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) => CreateCollection(ref reader, ref state, options); } }
1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonDictionaryConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization.Metadata; namespace System.Text.Json.Serialization { /// <summary> /// Base class for dictionary converters such as IDictionary, Hashtable, Dictionary{,} IDictionary{,} and SortedList. /// </summary> internal abstract class JsonDictionaryConverter<TDictionary> : JsonResumableConverter<TDictionary> { internal sealed override ConverterStrategy ConverterStrategy => ConverterStrategy.Dictionary; protected internal abstract bool OnWriteResume(Utf8JsonWriter writer, TDictionary dictionary, JsonSerializerOptions options, ref WriteStack state); } /// <summary> /// Base class for dictionary converters such as IDictionary, Hashtable, Dictionary{,} IDictionary{,} and SortedList. /// </summary> internal abstract class JsonDictionaryConverter<TDictionary, TKey, TValue> : JsonDictionaryConverter<TDictionary> where TKey : notnull { /// <summary> /// When overridden, adds the value to the collection. /// </summary> protected abstract void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state); /// <summary> /// When overridden, converts the temporary collection held in state.Current.ReturnValue to the final collection. /// This is used with immutable collections. /// </summary> protected virtual void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) { } /// <summary> /// When overridden, create the collection. It may be a temporary collection or the final collection. /// </summary> protected virtual void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state) { JsonTypeInfo typeInfo = state.Current.JsonTypeInfo; if (typeInfo.CreateObject is null) { // The contract model was not able to produce a default constructor for two possible reasons: // 1. Either the declared collection type is abstract and cannot be instantiated. // 2. The collection type does not specify a default constructor. if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } else { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } } state.Current.ReturnValue = typeInfo.CreateObject()!; Debug.Assert(state.Current.ReturnValue is TDictionary); } internal override Type ElementType => typeof(TValue); internal override Type KeyType => typeof(TKey); protected JsonConverter<TKey>? _keyConverter; protected JsonConverter<TValue>? _valueConverter; protected static JsonConverter<T> GetConverter<T>(JsonTypeInfo typeInfo) { JsonConverter<T> converter = (JsonConverter<T>)typeInfo.PropertyInfoForTypeInfo.ConverterBase; Debug.Assert(converter != null); // It should not be possible to have a null converter at this point. return converter; } internal sealed override bool OnTryRead( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out TDictionary value) { JsonTypeInfo elementTypeInfo = state.Current.JsonTypeInfo.ElementTypeInfo!; if (state.UseFastPath) { // Fast path that avoids maintaining state variables and dealing with preserved references. if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } CreateCollection(ref reader, ref state); _valueConverter ??= GetConverter<TValue>(elementTypeInfo); if (_valueConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) { // Process all elements. while (true) { // Read the key name. reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndObject) { break; } // Read method would have thrown if otherwise. Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); TKey key = ReadDictionaryKey(ref reader, ref state); // Read the value and add. reader.ReadWithVerify(); TValue? element = _valueConverter.Read(ref reader, ElementType, options); Add(key, element!, options, ref state); } } else { // Process all elements. while (true) { // Read the key name. reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndObject) { break; } // Read method would have thrown if otherwise. Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); TKey key = ReadDictionaryKey(ref reader, ref state); reader.ReadWithVerify(); // Get the value from the converter and add it. _valueConverter.TryRead(ref reader, ElementType, options, ref state, out TValue? element); Add(key, element!, options, ref state); } } } else { // Slower path that supports continuation and preserved references. if (state.Current.ObjectState == StackFrameObjectState.None) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.StartToken; } // Handle the metadata properties. bool preserveReferences = options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve; if (preserveReferences && state.Current.ObjectState < StackFrameObjectState.PropertyValue) { if (JsonSerializer.ResolveMetadataForJsonObject<TDictionary>(ref reader, ref state, options)) { if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject) { // This will never throw since it was previously validated in ResolveMetadataForJsonObject. value = (TDictionary)state.Current.ReturnValue!; return true; } } else { value = default; return false; } } // Create the dictionary. if (state.Current.ObjectState < StackFrameObjectState.CreatedObject) { CreateCollection(ref reader, ref state); state.Current.ObjectState = StackFrameObjectState.CreatedObject; } // Process all elements. _valueConverter ??= GetConverter<TValue>(elementTypeInfo); while (true) { if (state.Current.PropertyState == StackFramePropertyState.None) { state.Current.PropertyState = StackFramePropertyState.ReadName; // Read the key name. if (!reader.Read()) { value = default; return false; } } // Determine the property. TKey key; if (state.Current.PropertyState < StackFramePropertyState.Name) { if (reader.TokenType == JsonTokenType.EndObject) { break; } // Read method would have thrown if otherwise. Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); state.Current.PropertyState = StackFramePropertyState.Name; if (preserveReferences) { ReadOnlySpan<byte> propertyName = reader.GetSpan(); if (propertyName.Length > 0 && propertyName[0] == '$') { ThrowHelper.ThrowUnexpectedMetadataException(propertyName, ref reader, ref state); } } key = ReadDictionaryKey(ref reader, ref state); } else { // DictionaryKey is assigned before all return false cases, null value is unreachable key = (TKey)state.Current.DictionaryKey!; } if (state.Current.PropertyState < StackFramePropertyState.ReadValue) { state.Current.PropertyState = StackFramePropertyState.ReadValue; if (!SingleValueReadWithReadAhead(_valueConverter.RequiresReadAhead, ref reader, ref state)) { state.Current.DictionaryKey = key; value = default; return false; } } if (state.Current.PropertyState < StackFramePropertyState.TryRead) { // Get the value from the converter and add it. bool success = _valueConverter.TryRead(ref reader, typeof(TValue), options, ref state, out TValue? element); if (!success) { state.Current.DictionaryKey = key; value = default; return false; } Add(key, element!, options, ref state); state.Current.EndElement(); } } } ConvertCollection(ref state, options); value = (TDictionary)state.Current.ReturnValue!; return true; TKey ReadDictionaryKey(ref Utf8JsonReader reader, ref ReadStack state) { TKey key; string unescapedPropertyNameAsString; _keyConverter ??= GetConverter<TKey>(state.Current.JsonTypeInfo.KeyTypeInfo!); // Special case string to avoid calling GetString twice and save one allocation. if (_keyConverter.IsInternalConverter && KeyType == typeof(string)) { unescapedPropertyNameAsString = reader.GetString()!; key = (TKey)(object)unescapedPropertyNameAsString; } else { key = _keyConverter.ReadAsPropertyNameCore(ref reader, KeyType, options); unescapedPropertyNameAsString = reader.GetString()!; } // Copy key name for JSON Path support in case of error. state.Current.JsonPropertyNameAsString = unescapedPropertyNameAsString; return key; } } 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 (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve) { MetadataPropertyName propertyName = JsonSerializer.WriteReferenceForObject(this, ref state, writer); Debug.Assert(propertyName != MetadataPropertyName.Ref); } state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo!.PropertyInfoForTypeInfo; } bool success = OnWriteResume(writer, dictionary, options, ref state); if (success) { if (!state.Current.ProcessedEndToken) { state.Current.ProcessedEndToken = true; writer.WriteEndObject(); } } return success; } internal sealed override void CreateInstanceForReferenceResolver(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) => CreateCollection(ref reader, ref state); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization.Metadata; namespace System.Text.Json.Serialization { /// <summary> /// Base class for dictionary converters such as IDictionary, Hashtable, Dictionary{,} IDictionary{,} and SortedList. /// </summary> internal abstract class JsonDictionaryConverter<TDictionary> : JsonResumableConverter<TDictionary> { internal sealed override ConverterStrategy ConverterStrategy => ConverterStrategy.Dictionary; protected internal abstract bool OnWriteResume(Utf8JsonWriter writer, TDictionary dictionary, JsonSerializerOptions options, ref WriteStack state); } /// <summary> /// Base class for dictionary converters such as IDictionary, Hashtable, Dictionary{,} IDictionary{,} and SortedList. /// </summary> internal abstract class JsonDictionaryConverter<TDictionary, TKey, TValue> : JsonDictionaryConverter<TDictionary> where TKey : notnull { /// <summary> /// When overridden, adds the value to the collection. /// </summary> protected abstract void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state); /// <summary> /// When overridden, converts the temporary collection held in state.Current.ReturnValue to the final collection. /// This is used with immutable collections. /// </summary> protected virtual void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) { } /// <summary> /// When overridden, create the collection. It may be a temporary collection or the final collection. /// </summary> protected virtual void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state) { JsonTypeInfo typeInfo = state.Current.JsonTypeInfo; if (typeInfo.CreateObject is null) { // The contract model was not able to produce a default constructor for two possible reasons: // 1. Either the declared collection type is abstract and cannot be instantiated. // 2. The collection type does not specify a default constructor. if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } else { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } } state.Current.ReturnValue = typeInfo.CreateObject()!; Debug.Assert(state.Current.ReturnValue is TDictionary); } internal override Type ElementType => typeof(TValue); internal override Type KeyType => typeof(TKey); protected JsonConverter<TKey>? _keyConverter; protected JsonConverter<TValue>? _valueConverter; protected static JsonConverter<T> GetConverter<T>(JsonTypeInfo typeInfo) { JsonConverter<T> converter = (JsonConverter<T>)typeInfo.PropertyInfoForTypeInfo.ConverterBase; Debug.Assert(converter != null); // It should not be possible to have a null converter at this point. return converter; } internal sealed override bool OnTryRead( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out TDictionary value) { JsonTypeInfo elementTypeInfo = state.Current.JsonTypeInfo.ElementTypeInfo!; if (state.UseFastPath) { // Fast path that avoids maintaining state variables and dealing with preserved references. if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } CreateCollection(ref reader, ref state); state.Current.JsonPropertyInfo = elementTypeInfo.PropertyInfoForTypeInfo; _valueConverter ??= GetConverter<TValue>(elementTypeInfo); if (_valueConverter.CanUseDirectReadOrWrite && state.Current.NumberHandling == null) { // Process all elements. while (true) { // Read the key name. reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndObject) { break; } // Read method would have thrown if otherwise. Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); TKey key = ReadDictionaryKey(ref reader, ref state); // Read the value and add. reader.ReadWithVerify(); TValue? element = _valueConverter.Read(ref reader, ElementType, options); Add(key, element!, options, ref state); } } else { // Process all elements. while (true) { // Read the key name. reader.ReadWithVerify(); if (reader.TokenType == JsonTokenType.EndObject) { break; } // Read method would have thrown if otherwise. Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); TKey key = ReadDictionaryKey(ref reader, ref state); reader.ReadWithVerify(); // Get the value from the converter and add it. _valueConverter.TryRead(ref reader, ElementType, options, ref state, out TValue? element); Add(key, element!, options, ref state); } } } else { // Slower path that supports continuation and preserved references. if (state.Current.ObjectState == StackFrameObjectState.None) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.StartToken; state.Current.JsonPropertyInfo = elementTypeInfo.PropertyInfoForTypeInfo; } // Handle the metadata properties. bool preserveReferences = options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve; if (preserveReferences && state.Current.ObjectState < StackFrameObjectState.PropertyValue) { if (JsonSerializer.ResolveMetadataForJsonObject<TDictionary>(ref reader, ref state, options)) { if (state.Current.ObjectState == StackFrameObjectState.ReadRefEndObject) { // This will never throw since it was previously validated in ResolveMetadataForJsonObject. value = (TDictionary)state.Current.ReturnValue!; return true; } } else { value = default; return false; } } // Create the dictionary. if (state.Current.ObjectState < StackFrameObjectState.CreatedObject) { CreateCollection(ref reader, ref state); state.Current.ObjectState = StackFrameObjectState.CreatedObject; } // Process all elements. _valueConverter ??= GetConverter<TValue>(elementTypeInfo); while (true) { if (state.Current.PropertyState == StackFramePropertyState.None) { state.Current.PropertyState = StackFramePropertyState.ReadName; // Read the key name. if (!reader.Read()) { value = default; return false; } } // Determine the property. TKey key; if (state.Current.PropertyState < StackFramePropertyState.Name) { if (reader.TokenType == JsonTokenType.EndObject) { break; } // Read method would have thrown if otherwise. Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); state.Current.PropertyState = StackFramePropertyState.Name; if (preserveReferences) { ReadOnlySpan<byte> propertyName = reader.GetSpan(); if (propertyName.Length > 0 && propertyName[0] == '$') { ThrowHelper.ThrowUnexpectedMetadataException(propertyName, ref reader, ref state); } } key = ReadDictionaryKey(ref reader, ref state); } else { // DictionaryKey is assigned before all return false cases, null value is unreachable key = (TKey)state.Current.DictionaryKey!; } if (state.Current.PropertyState < StackFramePropertyState.ReadValue) { state.Current.PropertyState = StackFramePropertyState.ReadValue; if (!SingleValueReadWithReadAhead(_valueConverter.RequiresReadAhead, ref reader, ref state)) { state.Current.DictionaryKey = key; value = default; return false; } } if (state.Current.PropertyState < StackFramePropertyState.TryRead) { // Get the value from the converter and add it. bool success = _valueConverter.TryRead(ref reader, typeof(TValue), options, ref state, out TValue? element); if (!success) { state.Current.DictionaryKey = key; value = default; return false; } Add(key, element!, options, ref state); state.Current.EndElement(); } } } ConvertCollection(ref state, options); value = (TDictionary)state.Current.ReturnValue!; return true; TKey ReadDictionaryKey(ref Utf8JsonReader reader, ref ReadStack state) { TKey key; string unescapedPropertyNameAsString; _keyConverter ??= GetConverter<TKey>(state.Current.JsonTypeInfo.KeyTypeInfo!); // Special case string to avoid calling GetString twice and save one allocation. if (_keyConverter.IsInternalConverter && KeyType == typeof(string)) { unescapedPropertyNameAsString = reader.GetString()!; key = (TKey)(object)unescapedPropertyNameAsString; } else { key = _keyConverter.ReadAsPropertyNameCore(ref reader, KeyType, options); unescapedPropertyNameAsString = reader.GetString()!; } // Copy key name for JSON Path support in case of error. state.Current.JsonPropertyNameAsString = unescapedPropertyNameAsString; return key; } } 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 (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve) { MetadataPropertyName propertyName = JsonSerializer.WriteReferenceForObject(this, ref state, writer); Debug.Assert(propertyName != MetadataPropertyName.Ref); } state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo!.PropertyInfoForTypeInfo; } bool success = OnWriteResume(writer, dictionary, options, ref state); if (success) { if (!state.Current.ProcessedEndToken) { state.Current.ProcessedEndToken = true; writer.WriteEndObject(); } } return success; } internal sealed override void CreateInstanceForReferenceResolver(ref Utf8JsonReader reader, ref ReadStack state, JsonSerializerOptions options) => CreateCollection(ref reader, ref state); } }
1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReadStack.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; namespace System.Text.Json { [DebuggerDisplay("{DebuggerDisplay,nq}")] internal struct ReadStack { internal static readonly char[] SpecialCharacters = { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; /// <summary> /// Exposes the stackframe that is currently active. /// </summary> public ReadStackFrame Current; /// <summary> /// Buffer containing all frames in the stack. For performance it is only populated for serialization depths > 1. /// </summary> private ReadStackFrame[] _stack; /// <summary> /// Tracks the current depth of the stack. /// </summary> private int _count; /// <summary> /// If not zero, indicates that the stack is part of a re-entrant continuation of given depth. /// </summary> private int _continuationCount; // State cache when deserializing objects with parameterized constructors. private List<ArgumentState>? _ctorArgStateCache; /// <summary> /// Bytes consumed in the current loop. /// </summary> public long BytesConsumed; /// <summary> /// Indicates that the state still contains suspended frames waiting re-entry. /// </summary> public bool IsContinuation => _continuationCount != 0; /// <summary> /// Internal flag to let us know that we need to read ahead in the inner read loop. /// </summary> public bool ReadAhead; // The bag of preservable references. public ReferenceResolver ReferenceResolver; /// <summary> /// Whether we need to read ahead in the inner read loop. /// </summary> public bool SupportContinuation; /// <summary> /// Whether we can read without the need of saving state for stream and preserve references cases. /// </summary> public bool UseFastPath; /// <summary> /// Ensures that the stack buffer has sufficient capacity to hold an additional frame. /// </summary> private void EnsurePushCapacity() { if (_stack is null) { _stack = new ReadStackFrame[4]; } else if (_count - 1 == _stack.Length) { Array.Resize(ref _stack, 2 * _stack.Length); } } public void Initialize(Type type, JsonSerializerOptions options, bool supportContinuation) { JsonTypeInfo jsonTypeInfo = options.GetOrAddJsonTypeInfoForRootType(type); Initialize(jsonTypeInfo, supportContinuation); } internal void Initialize(JsonTypeInfo jsonTypeInfo, bool supportContinuation = false) { Current.JsonTypeInfo = jsonTypeInfo; // The initial JsonPropertyInfo will be used to obtain the converter. Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; Current.NumberHandling = Current.JsonPropertyInfo.NumberHandling; JsonSerializerOptions options = jsonTypeInfo.Options; bool preserveReferences = options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve; if (preserveReferences) { ReferenceResolver = options.ReferenceHandler!.CreateResolver(writing: false); } SupportContinuation = supportContinuation; UseFastPath = !supportContinuation && !preserveReferences; } public void Push() { if (_continuationCount == 0) { if (_count == 0) { // Performance optimization: reuse the first stackframe on the first push operation. // NB need to be careful when making writes to Current _before_ the first `Push` // operation is performed. _count = 1; } else { JsonTypeInfo jsonTypeInfo; JsonNumberHandling? numberHandling = Current.NumberHandling; ConverterStrategy converterStrategy = Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterStrategy; if (converterStrategy == ConverterStrategy.Object) { if (Current.JsonPropertyInfo != null) { jsonTypeInfo = Current.JsonPropertyInfo.JsonTypeInfo; } else { jsonTypeInfo = Current.CtorArgumentState!.JsonParameterInfo!.JsonTypeInfo; } } else if (converterStrategy == ConverterStrategy.Value) { // Although ConverterStrategy.Value doesn't push, a custom custom converter may re-enter serialization. jsonTypeInfo = Current.JsonPropertyInfo!.JsonTypeInfo; } else { Debug.Assert(((ConverterStrategy.Enumerable | ConverterStrategy.Dictionary) & converterStrategy) != 0); jsonTypeInfo = Current.JsonTypeInfo.ElementTypeInfo!; } EnsurePushCapacity(); _stack[_count - 1] = Current; Current = default; _count++; Current.JsonTypeInfo = jsonTypeInfo; Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; // Allow number handling on property to win over handling on type. Current.NumberHandling = numberHandling ?? Current.JsonPropertyInfo.NumberHandling; } } else { // We are re-entering a continuation, adjust indices accordingly if (_count++ > 0) { Current = _stack[_count - 1]; } // check if we are done if (_continuationCount == _count) { _continuationCount = 0; } } SetConstructorArgumentState(); #if DEBUG // Ensure the method is always exercised in debug builds. _ = JsonPath(); #endif } public void Pop(bool success) { Debug.Assert(_count > 0); if (!success) { // Check if we need to initialize the continuation. if (_continuationCount == 0) { if (_count == 1) { // No need to copy any frames here. _continuationCount = 1; _count = 0; return; } // Need to push the Current frame to the stack, // ensure that we have sufficient capacity. EnsurePushCapacity(); _continuationCount = _count--; } else if (--_count == 0) { // reached the root, no need to copy frames. return; } _stack[_count] = Current; Current = _stack[_count - 1]; } else { Debug.Assert(_continuationCount == 0); if (--_count > 0) { Current = _stack[_count - 1]; } } SetConstructorArgumentState(); } // Return a JSONPath using simple dot-notation when possible. When special characters are present, bracket-notation is used: // $.x.y[0].z // $['PropertyName.With.Special.Chars'] public string JsonPath() { StringBuilder sb = new StringBuilder("$"); // If a continuation, always report back full stack which does not use Current for the last frame. int count = Math.Max(_count, _continuationCount + 1); for (int i = 0; i < count - 1; i++) { AppendStackFrame(sb, ref _stack[i]); } if (_continuationCount == 0) { AppendStackFrame(sb, ref Current); } return sb.ToString(); static void AppendStackFrame(StringBuilder sb, ref ReadStackFrame frame) { // Append the property name. string? propertyName = GetPropertyName(ref frame); AppendPropertyName(sb, propertyName); if (frame.JsonTypeInfo != null && frame.IsProcessingEnumerable()) { if (frame.ReturnValue is not IEnumerable enumerable) { return; } // For continuation scenarios only, before or after all elements are read, the exception is not within the array. if (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 count = 0; IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { count++; } return count; } static void AppendPropertyName(StringBuilder sb, string? propertyName) { if (propertyName != null) { if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append(@"['"); sb.Append(propertyName); sb.Append(@"']"); } else { sb.Append('.'); sb.Append(propertyName); } } } static string? GetPropertyName(ref ReadStackFrame frame) { string? propertyName = null; // Attempt to get the JSON property name from the frame. byte[]? utf8PropertyName = frame.JsonPropertyName; if (utf8PropertyName == null) { if (frame.JsonPropertyNameAsString != null) { // Attempt to get the JSON property name set manually for dictionary // keys and KeyValuePair property names. propertyName = frame.JsonPropertyNameAsString; } else { // Attempt to get the JSON property name from the JsonPropertyInfo or JsonParameterInfo. utf8PropertyName = frame.JsonPropertyInfo?.NameAsUtf8Bytes ?? frame.CtorArgumentState?.JsonParameterInfo?.NameAsUtf8Bytes; } } if (utf8PropertyName != null) { propertyName = JsonHelpers.Utf8GetString(utf8PropertyName); } return propertyName; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SetConstructorArgumentState() { if (Current.JsonTypeInfo.IsObjectWithParameterizedCtor) { // A zero index indicates a new stack frame. if (Current.CtorArgumentStateIndex == 0) { _ctorArgStateCache ??= new List<ArgumentState>(); var newState = new ArgumentState(); _ctorArgStateCache.Add(newState); (Current.CtorArgumentStateIndex, Current.CtorArgumentState) = (_ctorArgStateCache.Count, newState); } else { Current.CtorArgumentState = _ctorArgStateCache![Current.CtorArgumentStateIndex - 1]; } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => $"Path:{JsonPath()} Current: ConverterStrategy.{Current.JsonTypeInfo?.PropertyInfoForTypeInfo.ConverterStrategy}, {Current.JsonTypeInfo?.Type.Name}"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; namespace System.Text.Json { [DebuggerDisplay("{DebuggerDisplay,nq}")] internal struct ReadStack { internal static readonly char[] SpecialCharacters = { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; /// <summary> /// Exposes the stackframe that is currently active. /// </summary> public ReadStackFrame Current; /// <summary> /// Buffer containing all frames in the stack. For performance it is only populated for serialization depths > 1. /// </summary> private ReadStackFrame[] _stack; /// <summary> /// Tracks the current depth of the stack. /// </summary> private int _count; /// <summary> /// If not zero, indicates that the stack is part of a re-entrant continuation of given depth. /// </summary> private int _continuationCount; // State cache when deserializing objects with parameterized constructors. private List<ArgumentState>? _ctorArgStateCache; /// <summary> /// Bytes consumed in the current loop. /// </summary> public long BytesConsumed; /// <summary> /// Indicates that the state still contains suspended frames waiting re-entry. /// </summary> public bool IsContinuation => _continuationCount != 0; /// <summary> /// Internal flag to let us know that we need to read ahead in the inner read loop. /// </summary> public bool ReadAhead; // The bag of preservable references. public ReferenceResolver ReferenceResolver; /// <summary> /// Whether we need to read ahead in the inner read loop. /// </summary> public bool SupportContinuation; /// <summary> /// Whether we can read without the need of saving state for stream and preserve references cases. /// </summary> public bool UseFastPath; /// <summary> /// Ensures that the stack buffer has sufficient capacity to hold an additional frame. /// </summary> private void EnsurePushCapacity() { if (_stack is null) { _stack = new ReadStackFrame[4]; } else if (_count - 1 == _stack.Length) { Array.Resize(ref _stack, 2 * _stack.Length); } } public void Initialize(Type type, JsonSerializerOptions options, bool supportContinuation) { JsonTypeInfo jsonTypeInfo = options.GetOrAddJsonTypeInfoForRootType(type); Initialize(jsonTypeInfo, supportContinuation); } internal void Initialize(JsonTypeInfo jsonTypeInfo, bool supportContinuation = false) { Current.JsonTypeInfo = jsonTypeInfo; // The initial JsonPropertyInfo will be used to obtain the converter. Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; Current.NumberHandling = Current.JsonPropertyInfo.NumberHandling; JsonSerializerOptions options = jsonTypeInfo.Options; bool preserveReferences = options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve; if (preserveReferences) { ReferenceResolver = options.ReferenceHandler!.CreateResolver(writing: false); } SupportContinuation = supportContinuation; UseFastPath = !supportContinuation && !preserveReferences; } public void Push() { if (_continuationCount == 0) { if (_count == 0) { // Performance optimization: reuse the first stackframe on the first push operation. // NB need to be careful when making writes to Current _before_ the first `Push` // operation is performed. _count = 1; } else { JsonTypeInfo jsonTypeInfo = Current.JsonPropertyInfo?.JsonTypeInfo ?? Current.CtorArgumentState!.JsonParameterInfo!.JsonTypeInfo; JsonNumberHandling? numberHandling = Current.NumberHandling; ConverterStrategy converterStrategy = Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterStrategy; EnsurePushCapacity(); _stack[_count - 1] = Current; Current = default; _count++; Current.JsonTypeInfo = jsonTypeInfo; Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; // Allow number handling on property to win over handling on type. Current.NumberHandling = numberHandling ?? Current.JsonPropertyInfo.NumberHandling; } } else { // We are re-entering a continuation, adjust indices accordingly if (_count++ > 0) { Current = _stack[_count - 1]; } // check if we are done if (_continuationCount == _count) { _continuationCount = 0; } } SetConstructorArgumentState(); #if DEBUG // Ensure the method is always exercised in debug builds. _ = JsonPath(); #endif } public void Pop(bool success) { Debug.Assert(_count > 0); if (!success) { // Check if we need to initialize the continuation. if (_continuationCount == 0) { if (_count == 1) { // No need to copy any frames here. _continuationCount = 1; _count = 0; return; } // Need to push the Current frame to the stack, // ensure that we have sufficient capacity. EnsurePushCapacity(); _continuationCount = _count--; } else if (--_count == 0) { // reached the root, no need to copy frames. return; } _stack[_count] = Current; Current = _stack[_count - 1]; } else { Debug.Assert(_continuationCount == 0); if (--_count > 0) { Current = _stack[_count - 1]; } } SetConstructorArgumentState(); } // Return a JSONPath using simple dot-notation when possible. When special characters are present, bracket-notation is used: // $.x.y[0].z // $['PropertyName.With.Special.Chars'] public string JsonPath() { StringBuilder sb = new StringBuilder("$"); // If a continuation, always report back full stack which does not use Current for the last frame. int count = Math.Max(_count, _continuationCount + 1); for (int i = 0; i < count - 1; i++) { AppendStackFrame(sb, ref _stack[i]); } if (_continuationCount == 0) { AppendStackFrame(sb, ref Current); } return sb.ToString(); static void AppendStackFrame(StringBuilder sb, ref ReadStackFrame frame) { // Append the property name. string? propertyName = GetPropertyName(ref frame); AppendPropertyName(sb, propertyName); if (frame.JsonTypeInfo != null && frame.IsProcessingEnumerable()) { if (frame.ReturnValue is not IEnumerable enumerable) { return; } // For continuation scenarios only, before or after all elements are read, the exception is not within the array. if (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 count = 0; IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { count++; } return count; } static void AppendPropertyName(StringBuilder sb, string? propertyName) { if (propertyName != null) { if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append(@"['"); sb.Append(propertyName); sb.Append(@"']"); } else { sb.Append('.'); sb.Append(propertyName); } } } static string? GetPropertyName(ref ReadStackFrame frame) { string? propertyName = null; // Attempt to get the JSON property name from the frame. byte[]? utf8PropertyName = frame.JsonPropertyName; if (utf8PropertyName == null) { if (frame.JsonPropertyNameAsString != null) { // Attempt to get the JSON property name set manually for dictionary // keys and KeyValuePair property names. propertyName = frame.JsonPropertyNameAsString; } else { // Attempt to get the JSON property name from the JsonPropertyInfo or JsonParameterInfo. utf8PropertyName = frame.JsonPropertyInfo?.NameAsUtf8Bytes ?? frame.CtorArgumentState?.JsonParameterInfo?.NameAsUtf8Bytes; } } if (utf8PropertyName != null) { propertyName = JsonHelpers.Utf8GetString(utf8PropertyName); } return propertyName; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SetConstructorArgumentState() { if (Current.JsonTypeInfo.IsObjectWithParameterizedCtor) { // A zero index indicates a new stack frame. if (Current.CtorArgumentStateIndex == 0) { _ctorArgStateCache ??= new List<ArgumentState>(); var newState = new ArgumentState(); _ctorArgStateCache.Add(newState); (Current.CtorArgumentStateIndex, Current.CtorArgumentState) = (_ctorArgStateCache.Count, newState); } else { Current.CtorArgumentState = _ctorArgStateCache![Current.CtorArgumentStateIndex - 1]; } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => $"Path:{JsonPath()} Current: ConverterStrategy.{Current.JsonTypeInfo?.PropertyInfoForTypeInfo.ConverterStrategy}, {Current.JsonTypeInfo?.Type.Name}"; } }
1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.Serialization.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; namespace System.Text.Json { internal static partial class ThrowHelper { [DoesNotReturn] public static void ThrowArgumentException_DeserializeWrongType(Type type, object value) { throw new ArgumentException(SR.Format(SR.DeserializeWrongType, type, value.GetType())); } [DoesNotReturn] public static void ThrowNotSupportedException_SerializationNotSupported(Type propertyType) { throw new NotSupportedException(SR.Format(SR.SerializationNotSupportedType, propertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_TypeRequiresAsyncSerialization(Type propertyType) { throw new NotSupportedException(SR.Format(SR.TypeRequiresAsyncSerialization, propertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_ConstructorMaxOf64Parameters(Type type) { throw new NotSupportedException(SR.Format(SR.ConstructorMaxOf64Parameters, type)); } [DoesNotReturn] public static void ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type keyType, JsonConverter converter) { throw new NotSupportedException(SR.Format(SR.DictionaryKeyTypeNotSupported, keyType, converter.GetType())); } [DoesNotReturn] public static void ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType) { throw new JsonException(SR.Format(SR.DeserializeUnableToConvertValue, propertyType)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType) { throw new InvalidCastException(SR.Format(SR.DeserializeUnableToAssignValue, typeOfValue, declaredType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_DeserializeUnableToAssignNull(Type declaredType) { throw new InvalidOperationException(SR.Format(SR.DeserializeUnableToAssignNull, declaredType)); } [DoesNotReturn] public static void ThrowJsonException_SerializationConverterRead(JsonConverter? converter) { throw new JsonException(SR.Format(SR.SerializationConverterRead, converter)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException_SerializationConverterWrite(JsonConverter? converter) { throw new JsonException(SR.Format(SR.SerializationConverterWrite, converter)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException_SerializerCycleDetected(int maxDepth) { throw new JsonException(SR.Format(SR.SerializerCycleDetected, maxDepth)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException(string? message = null) { throw new JsonException(message) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type type, Type? parentClassType, MemberInfo? memberInfo) { if (parentClassType == null) { Debug.Assert(memberInfo == null); throw new InvalidOperationException(SR.Format(SR.CannotSerializeInvalidType, type)); } Debug.Assert(memberInfo != null); throw new InvalidOperationException(SR.Format(SR.CannotSerializeInvalidMember, type, memberInfo.Name, parentClassType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterNotCompatible(Type converterType, Type type) { throw new InvalidOperationException(SR.Format(SR.SerializationConverterNotCompatible, converterType, type)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, MemberInfo? memberInfo) { string location = classType.ToString(); if (memberInfo != null) { location += $".{memberInfo.Name}"; } throw new InvalidOperationException(SR.Format(SR.SerializationConverterOnAttributeInvalid, location)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, MemberInfo? memberInfo, Type typeToConvert) { string location = classTypeAttributeIsOn.ToString(); if (memberInfo != null) { location += $".{memberInfo.Name}"; } throw new InvalidOperationException(SR.Format(SR.SerializationConverterOnAttributeNotCompatible, location, typeToConvert)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerOptionsImmutable(JsonSerializerContext? context) { string message = context == null ? SR.SerializerOptionsImmutable : SR.SerializerContextOptionsImmutable; throw new InvalidOperationException(message); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(SR.Format(SR.SerializerPropertyNameConflict, type, jsonPropertyInfo.ClrName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameNull(Type parentType, JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(SR.Format(SR.SerializerPropertyNameNull, parentType, jsonPropertyInfo.MemberInfo?.Name)); } [DoesNotReturn] public static void ThrowInvalidOperationException_NamingPolicyReturnNull(JsonNamingPolicy namingPolicy) { throw new InvalidOperationException(SR.Format(SR.NamingPolicyReturnNull, namingPolicy)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(Type converterType) { throw new InvalidOperationException(SR.Format(SR.SerializerConverterFactoryReturnsNull, converterType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsJsonConverterFactorty(Type converterType) { throw new InvalidOperationException(SR.Format(SR.SerializerConverterFactoryReturnsJsonConverterFactory, converterType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters( Type parentType, string parameterName, string firstMatchName, string secondMatchName) { throw new InvalidOperationException( SR.Format( SR.MultipleMembersBindWithConstructorParameter, firstMatchName, secondMatchName, parentType, parameterName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType) { throw new InvalidOperationException(SR.Format(SR.ConstructorParamIncompleteBinding, parentType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(SR.Format(SR.ExtensionDataCannotBindToCtorParam, jsonPropertyInfo.ClrName, jsonPropertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(string memberName, Type declaringType) { throw new InvalidOperationException(SR.Format(SR.JsonIncludeOnNonPublicInvalid, memberName, declaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_IgnoreConditionOnValueTypeInvalid(string clrPropertyName, Type propertyDeclaringType) { throw new InvalidOperationException(SR.Format(SR.IgnoreConditionOnValueTypeInvalid, clrPropertyName, propertyDeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(JsonPropertyInfo jsonPropertyInfo) { MemberInfo? memberInfo = jsonPropertyInfo.MemberInfo; Debug.Assert(memberInfo != null); Debug.Assert(!jsonPropertyInfo.IsForTypeInfo); throw new InvalidOperationException(SR.Format(SR.NumberHandlingOnPropertyInvalid, memberInfo.Name, memberInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ConverterCanConvertMultipleTypes(Type runtimePropertyType, JsonConverter jsonConverter) { throw new InvalidOperationException(SR.Format(SR.ConverterCanConvertMultipleTypes, jsonConverter.GetType(), jsonConverter.TypeToConvert, runtimePropertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored( ReadOnlySpan<byte> propertyName, ref Utf8JsonReader reader, ref ReadStack state) { state.Current.JsonPropertyName = propertyName.ToArray(); NotSupportedException ex = new NotSupportedException( SR.Format(SR.ObjectWithParameterizedCtorRefMetadataNotHonored, state.Current.JsonTypeInfo.Type)); ThrowNotSupportedException(ref state, reader, ex); } [DoesNotReturn] public static void ReThrowWithPath(ref ReadStack state, JsonReaderException ex) { Debug.Assert(ex.Path == null); string path = state.JsonPath(); string message = ex.Message; // Insert the "Path" portion before "LineNumber" and "BytePositionInLine". #if BUILDING_INBOX_LIBRARY int iPos = message.AsSpan().LastIndexOf(" LineNumber: "); #else int iPos = message.LastIndexOf(" LineNumber: ", StringComparison.InvariantCulture); #endif if (iPos >= 0) { message = $"{message.Substring(0, iPos)} Path: {path} |{message.Substring(iPos)}"; } else { message += $" Path: {path}."; } throw new JsonException(message, path, ex.LineNumber, ex.BytePositionInLine, ex); } [DoesNotReturn] public static void ReThrowWithPath(ref ReadStack state, in Utf8JsonReader reader, Exception ex) { JsonException jsonException = new JsonException(null, ex); AddJsonExceptionInformation(ref state, reader, jsonException); throw jsonException; } public static void AddJsonExceptionInformation(ref ReadStack state, in Utf8JsonReader reader, JsonException ex) { Debug.Assert(ex.Path is null); // do not overwrite existing path information long lineNumber = reader.CurrentState._lineNumber; ex.LineNumber = lineNumber; long bytePositionInLine = reader.CurrentState._bytePositionInLine; ex.BytePositionInLine = bytePositionInLine; string path = state.JsonPath(); ex.Path = path; string? message = ex._message; if (string.IsNullOrEmpty(message)) { // Use a default message. Type? propertyType = state.Current.JsonPropertyInfo?.PropertyType; if (propertyType == null) { propertyType = state.Current.JsonTypeInfo?.Type; } message = SR.Format(SR.DeserializeUnableToConvertValue, propertyType); ex.AppendPathInformation = true; } if (ex.AppendPathInformation) { message += $" Path: {path} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; ex.SetMessage(message); } } [DoesNotReturn] public static void ReThrowWithPath(ref WriteStack state, Exception ex) { JsonException jsonException = new JsonException(null, ex); AddJsonExceptionInformation(ref state, jsonException); throw jsonException; } public static void AddJsonExceptionInformation(ref WriteStack state, JsonException ex) { Debug.Assert(ex.Path is null); // do not overwrite existing path information string path = state.PropertyPath(); ex.Path = path; string? message = ex._message; if (string.IsNullOrEmpty(message)) { // Use a default message. message = SR.Format(SR.SerializeUnableToSerialize); ex.AppendPathInformation = true; } if (ex.AppendPathInformation) { message += $" Path: {path}."; ex.SetMessage(message); } } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateAttribute(Type attribute, Type classType, MemberInfo? memberInfo) { string location = classType.ToString(); if (memberInfo != null) { location += $".{memberInfo.Name}"; } throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateAttribute, attribute, location)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type classType, Type attribute) { throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateTypeAttribute, classType, attribute)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute<TAttribute>(Type classType) { throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateTypeAttribute, classType, typeof(TAttribute))); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(Type type, JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(SR.Format(SR.SerializationDataExtensionPropertyInvalid, type, jsonPropertyInfo.MemberInfo?.Name)); } [DoesNotReturn] public static void ThrowNotSupportedException(ref ReadStack state, in Utf8JsonReader reader, NotSupportedException ex) { string message = ex.Message; // The caller should check to ensure path is not already set. Debug.Assert(!message.Contains(" Path: ")); // Obtain the type to show in the message. Type? propertyType = state.Current.JsonPropertyInfo?.PropertyType; if (propertyType == null) { propertyType = state.Current.JsonTypeInfo.Type; } if (!message.Contains(propertyType.ToString())) { if (message.Length > 0) { message += " "; } message += SR.Format(SR.SerializationNotSupportedParentType, propertyType); } long lineNumber = reader.CurrentState._lineNumber; long bytePositionInLine = reader.CurrentState._bytePositionInLine; message += $" Path: {state.JsonPath()} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; throw new NotSupportedException(message, ex); } [DoesNotReturn] public static void ThrowNotSupportedException(ref WriteStack state, NotSupportedException ex) { string message = ex.Message; // The caller should check to ensure path is not already set. Debug.Assert(!message.Contains(" Path: ")); // Obtain the type to show in the message. Type? propertyType = state.Current.JsonPropertyInfo?.PropertyType; if (propertyType == null) { propertyType = state.Current.JsonTypeInfo.Type; } if (!message.Contains(propertyType.ToString())) { if (message.Length > 0) { message += " "; } message += SR.Format(SR.SerializationNotSupportedParentType, propertyType); } message += $" Path: {state.PropertyPath()}."; throw new NotSupportedException(message, ex); } [DoesNotReturn] public static void ThrowNotSupportedException_DeserializeNoConstructor(Type type, ref Utf8JsonReader reader, ref ReadStack state) { string message; if (type.IsInterface) { message = SR.Format(SR.DeserializePolymorphicInterface, type); } else { message = SR.Format(SR.DeserializeNoConstructor, nameof(JsonConstructorAttribute), type); } ThrowNotSupportedException(ref state, reader, new NotSupportedException(message)); } [DoesNotReturn] public static void ThrowNotSupportedException_CannotPopulateCollection(Type type, ref Utf8JsonReader reader, ref ReadStack state) { ThrowNotSupportedException(ref state, reader, new NotSupportedException(SR.Format(SR.CannotPopulateCollection, type))); } [DoesNotReturn] public static void ThrowJsonException_MetadataValuesInvalidToken(JsonTokenType tokenType) { ThrowJsonException(SR.Format(SR.MetadataInvalidTokenAfterValues, tokenType)); } [DoesNotReturn] public static void ThrowJsonException_MetadataReferenceNotFound(string id) { ThrowJsonException(SR.Format(SR.MetadataReferenceNotFound, id)); } [DoesNotReturn] public static void ThrowJsonException_MetadataValueWasNotString(JsonTokenType tokenType) { ThrowJsonException(SR.Format(SR.MetadataValueWasNotString, tokenType)); } [DoesNotReturn] public static void ThrowJsonException_MetadataValueWasNotString(JsonValueKind valueKind) { ThrowJsonException(SR.Format(SR.MetadataValueWasNotString, valueKind)); } [DoesNotReturn] public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(ReadOnlySpan<byte> propertyName, ref ReadStack state) { state.Current.JsonPropertyName = propertyName.ToArray(); ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); } [DoesNotReturn] public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties() { ThrowJsonException(SR.MetadataReferenceCannotContainOtherProperties); } [DoesNotReturn] public static void ThrowJsonException_MetadataIdIsNotFirstProperty(ReadOnlySpan<byte> propertyName, ref ReadStack state) { state.Current.JsonPropertyName = propertyName.ToArray(); ThrowJsonException(SR.MetadataIdIsNotFirstProperty); } [DoesNotReturn] public static void ThrowJsonException_MetadataMissingIdBeforeValues(ref ReadStack state, ReadOnlySpan<byte> propertyName) { state.Current.JsonPropertyName = propertyName.ToArray(); ThrowJsonException(SR.MetadataPreservedArrayPropertyNotFound); } [DoesNotReturn] public static void ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(ReadOnlySpan<byte> propertyName, ref ReadStack state, in Utf8JsonReader reader) { // Set PropertyInfo or KeyName to write down the conflicting property name in JsonException.Path if (state.Current.IsProcessingDictionary()) { state.Current.JsonPropertyNameAsString = reader.GetString(); } else { state.Current.JsonPropertyName = propertyName.ToArray(); } ThrowJsonException(SR.MetadataInvalidPropertyWithLeadingDollarSign); } [DoesNotReturn] public static void ThrowJsonException_MetadataDuplicateIdFound(string id) { ThrowJsonException(SR.Format(SR.MetadataDuplicateIdFound, id)); } [DoesNotReturn] public static void ThrowJsonException_MetadataInvalidReferenceToValueType(Type propertyType) { ThrowJsonException(SR.Format(SR.MetadataInvalidReferenceToValueType, propertyType)); } [DoesNotReturn] public static void ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref ReadStack state, Type propertyType, in Utf8JsonReader reader) { state.Current.JsonPropertyName = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan.ToArray(); string propertyNameAsString = reader.GetString()!; ThrowJsonException(SR.Format(SR.MetadataPreservedArrayFailed, SR.Format(SR.MetadataPreservedArrayInvalidProperty, propertyNameAsString), SR.Format(SR.DeserializeUnableToConvertValue, propertyType))); } [DoesNotReturn] public static void ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref ReadStack state, Type propertyType) { // Missing $values, JSON path should point to the property's object. state.Current.JsonPropertyName = null; ThrowJsonException(SR.Format(SR.MetadataPreservedArrayFailed, SR.MetadataPreservedArrayPropertyNotFound, SR.Format(SR.DeserializeUnableToConvertValue, propertyType))); } [DoesNotReturn] public static void ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(Type propertyType) { ThrowJsonException(SR.Format(SR.MetadataCannotParsePreservedObjectToImmutable, propertyType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_MetadataReferenceOfTypeCannotBeAssignedToType(string referenceId, Type currentType, Type typeToConvert) { throw new InvalidOperationException(SR.Format(SR.MetadataReferenceOfTypeCannotBeAssignedToType, referenceId, currentType, typeToConvert)); } [DoesNotReturn] internal static void ThrowUnexpectedMetadataException( ReadOnlySpan<byte> propertyName, ref Utf8JsonReader reader, ref ReadStack state) { if (state.Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterBase.ConstructorIsParameterized) { ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored(propertyName, ref reader, ref state); } MetadataPropertyName name = JsonSerializer.GetMetadataPropertyName(propertyName); if (name == MetadataPropertyName.Id) { ThrowJsonException_MetadataIdIsNotFirstProperty(propertyName, ref state); } else if (name == MetadataPropertyName.Ref) { ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(propertyName, ref state); } else { ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(propertyName, ref state, reader); } } [DoesNotReturn] public static void ThrowNotSupportedException_BuiltInConvertersNotRooted(Type type) { throw new NotSupportedException(SR.Format(SR.BuiltInConvertersNotRooted, type)); } [DoesNotReturn] public static void ThrowNotSupportedException_NoMetadataForType(Type type) { throw new NotSupportedException(SR.Format(SR.NoMetadataForType, type)); } [DoesNotReturn] public static void ThrowInvalidOperationException_NoMetadataForType(Type type) { throw new InvalidOperationException(SR.Format(SR.NoMetadataForType, type)); } [DoesNotReturn] public static void ThrowInvalidOperationException_MetadatInitFuncsNull() { throw new InvalidOperationException(SR.Format(SR.MetadataInitFuncsNull)); } public static void ThrowInvalidOperationException_NoMetadataForTypeProperties(JsonSerializerContext context, Type type) { throw new InvalidOperationException(SR.Format(SR.NoMetadataForTypeProperties, context.GetType(), type)); } public static void ThrowInvalidOperationException_NoMetadataForTypeCtorParams(JsonSerializerContext context, Type type) { throw new InvalidOperationException(SR.Format(SR.NoMetadataForTypeCtorParams, context.GetType(), type)); } public static void ThrowInvalidOperationException_NoDefaultOptionsForContext(JsonSerializerContext context, Type type) { throw new InvalidOperationException(SR.Format(SR.NoDefaultOptionsForContext, context.GetType(), type)); } [DoesNotReturn] public static void ThrowMissingMemberException_MissingFSharpCoreMember(string missingFsharpCoreMember) { throw new MissingMemberException(SR.Format(SR.MissingFSharpCoreMember, missingFsharpCoreMember)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; namespace System.Text.Json { internal static partial class ThrowHelper { [DoesNotReturn] public static void ThrowArgumentException_DeserializeWrongType(Type type, object value) { throw new ArgumentException(SR.Format(SR.DeserializeWrongType, type, value.GetType())); } [DoesNotReturn] public static void ThrowNotSupportedException_SerializationNotSupported(Type propertyType) { throw new NotSupportedException(SR.Format(SR.SerializationNotSupportedType, propertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_TypeRequiresAsyncSerialization(Type propertyType) { throw new NotSupportedException(SR.Format(SR.TypeRequiresAsyncSerialization, propertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_ConstructorMaxOf64Parameters(Type type) { throw new NotSupportedException(SR.Format(SR.ConstructorMaxOf64Parameters, type)); } [DoesNotReturn] public static void ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type keyType, JsonConverter converter) { throw new NotSupportedException(SR.Format(SR.DictionaryKeyTypeNotSupported, keyType, converter.GetType())); } [DoesNotReturn] public static void ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType) { throw new JsonException(SR.Format(SR.DeserializeUnableToConvertValue, propertyType)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType) { throw new InvalidCastException(SR.Format(SR.DeserializeUnableToAssignValue, typeOfValue, declaredType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_DeserializeUnableToAssignNull(Type declaredType) { throw new InvalidOperationException(SR.Format(SR.DeserializeUnableToAssignNull, declaredType)); } [DoesNotReturn] public static void ThrowJsonException_SerializationConverterRead(JsonConverter? converter) { throw new JsonException(SR.Format(SR.SerializationConverterRead, converter)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException_SerializationConverterWrite(JsonConverter? converter) { throw new JsonException(SR.Format(SR.SerializationConverterWrite, converter)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException_SerializerCycleDetected(int maxDepth) { throw new JsonException(SR.Format(SR.SerializerCycleDetected, maxDepth)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException(string? message = null) { throw new JsonException(message) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type type, Type? parentClassType, MemberInfo? memberInfo) { if (parentClassType == null) { Debug.Assert(memberInfo == null); throw new InvalidOperationException(SR.Format(SR.CannotSerializeInvalidType, type)); } Debug.Assert(memberInfo != null); throw new InvalidOperationException(SR.Format(SR.CannotSerializeInvalidMember, type, memberInfo.Name, parentClassType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterNotCompatible(Type converterType, Type type) { throw new InvalidOperationException(SR.Format(SR.SerializationConverterNotCompatible, converterType, type)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, MemberInfo? memberInfo) { string location = classType.ToString(); if (memberInfo != null) { location += $".{memberInfo.Name}"; } throw new InvalidOperationException(SR.Format(SR.SerializationConverterOnAttributeInvalid, location)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, MemberInfo? memberInfo, Type typeToConvert) { string location = classTypeAttributeIsOn.ToString(); if (memberInfo != null) { location += $".{memberInfo.Name}"; } throw new InvalidOperationException(SR.Format(SR.SerializationConverterOnAttributeNotCompatible, location, typeToConvert)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerOptionsImmutable(JsonSerializerContext? context) { string message = context == null ? SR.SerializerOptionsImmutable : SR.SerializerContextOptionsImmutable; throw new InvalidOperationException(message); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(SR.Format(SR.SerializerPropertyNameConflict, type, jsonPropertyInfo.ClrName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameNull(Type parentType, JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(SR.Format(SR.SerializerPropertyNameNull, parentType, jsonPropertyInfo.MemberInfo?.Name)); } [DoesNotReturn] public static void ThrowInvalidOperationException_NamingPolicyReturnNull(JsonNamingPolicy namingPolicy) { throw new InvalidOperationException(SR.Format(SR.NamingPolicyReturnNull, namingPolicy)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(Type converterType) { throw new InvalidOperationException(SR.Format(SR.SerializerConverterFactoryReturnsNull, converterType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsJsonConverterFactorty(Type converterType) { throw new InvalidOperationException(SR.Format(SR.SerializerConverterFactoryReturnsJsonConverterFactory, converterType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters( Type parentType, string parameterName, string firstMatchName, string secondMatchName) { throw new InvalidOperationException( SR.Format( SR.MultipleMembersBindWithConstructorParameter, firstMatchName, secondMatchName, parentType, parameterName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType) { throw new InvalidOperationException(SR.Format(SR.ConstructorParamIncompleteBinding, parentType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(SR.Format(SR.ExtensionDataCannotBindToCtorParam, jsonPropertyInfo.ClrName, jsonPropertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(string memberName, Type declaringType) { throw new InvalidOperationException(SR.Format(SR.JsonIncludeOnNonPublicInvalid, memberName, declaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_IgnoreConditionOnValueTypeInvalid(string clrPropertyName, Type propertyDeclaringType) { throw new InvalidOperationException(SR.Format(SR.IgnoreConditionOnValueTypeInvalid, clrPropertyName, propertyDeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(JsonPropertyInfo jsonPropertyInfo) { MemberInfo? memberInfo = jsonPropertyInfo.MemberInfo; Debug.Assert(memberInfo != null); Debug.Assert(!jsonPropertyInfo.IsForTypeInfo); throw new InvalidOperationException(SR.Format(SR.NumberHandlingOnPropertyInvalid, memberInfo.Name, memberInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ConverterCanConvertMultipleTypes(Type runtimePropertyType, JsonConverter jsonConverter) { throw new InvalidOperationException(SR.Format(SR.ConverterCanConvertMultipleTypes, jsonConverter.GetType(), jsonConverter.TypeToConvert, runtimePropertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored( ReadOnlySpan<byte> propertyName, ref Utf8JsonReader reader, ref ReadStack state) { state.Current.JsonPropertyName = propertyName.ToArray(); NotSupportedException ex = new NotSupportedException( SR.Format(SR.ObjectWithParameterizedCtorRefMetadataNotHonored, state.Current.JsonTypeInfo.Type)); ThrowNotSupportedException(ref state, reader, ex); } [DoesNotReturn] public static void ReThrowWithPath(ref ReadStack state, JsonReaderException ex) { Debug.Assert(ex.Path == null); string path = state.JsonPath(); string message = ex.Message; // Insert the "Path" portion before "LineNumber" and "BytePositionInLine". #if BUILDING_INBOX_LIBRARY int iPos = message.AsSpan().LastIndexOf(" LineNumber: "); #else int iPos = message.LastIndexOf(" LineNumber: ", StringComparison.InvariantCulture); #endif if (iPos >= 0) { message = $"{message.Substring(0, iPos)} Path: {path} |{message.Substring(iPos)}"; } else { message += $" Path: {path}."; } throw new JsonException(message, path, ex.LineNumber, ex.BytePositionInLine, ex); } [DoesNotReturn] public static void ReThrowWithPath(ref ReadStack state, in Utf8JsonReader reader, Exception ex) { JsonException jsonException = new JsonException(null, ex); AddJsonExceptionInformation(ref state, reader, jsonException); throw jsonException; } public static void AddJsonExceptionInformation(ref ReadStack state, in Utf8JsonReader reader, JsonException ex) { Debug.Assert(ex.Path is null); // do not overwrite existing path information long lineNumber = reader.CurrentState._lineNumber; ex.LineNumber = lineNumber; long bytePositionInLine = reader.CurrentState._bytePositionInLine; ex.BytePositionInLine = bytePositionInLine; string path = state.JsonPath(); ex.Path = path; string? message = ex._message; if (string.IsNullOrEmpty(message)) { // Use a default message. Type propertyType = state.Current.JsonTypeInfo.Type; message = SR.Format(SR.DeserializeUnableToConvertValue, propertyType); ex.AppendPathInformation = true; } if (ex.AppendPathInformation) { message += $" Path: {path} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; ex.SetMessage(message); } } [DoesNotReturn] public static void ReThrowWithPath(ref WriteStack state, Exception ex) { JsonException jsonException = new JsonException(null, ex); AddJsonExceptionInformation(ref state, jsonException); throw jsonException; } public static void AddJsonExceptionInformation(ref WriteStack state, JsonException ex) { Debug.Assert(ex.Path is null); // do not overwrite existing path information string path = state.PropertyPath(); ex.Path = path; string? message = ex._message; if (string.IsNullOrEmpty(message)) { // Use a default message. message = SR.Format(SR.SerializeUnableToSerialize); ex.AppendPathInformation = true; } if (ex.AppendPathInformation) { message += $" Path: {path}."; ex.SetMessage(message); } } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateAttribute(Type attribute, Type classType, MemberInfo? memberInfo) { string location = classType.ToString(); if (memberInfo != null) { location += $".{memberInfo.Name}"; } throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateAttribute, attribute, location)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type classType, Type attribute) { throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateTypeAttribute, classType, attribute)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute<TAttribute>(Type classType) { throw new InvalidOperationException(SR.Format(SR.SerializationDuplicateTypeAttribute, classType, typeof(TAttribute))); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(Type type, JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(SR.Format(SR.SerializationDataExtensionPropertyInvalid, type, jsonPropertyInfo.MemberInfo?.Name)); } [DoesNotReturn] public static void ThrowNotSupportedException(ref ReadStack state, in Utf8JsonReader reader, NotSupportedException ex) { string message = ex.Message; // The caller should check to ensure path is not already set. Debug.Assert(!message.Contains(" Path: ")); // Obtain the type to show in the message. Type propertyType = state.Current.JsonTypeInfo.Type; if (!message.Contains(propertyType.ToString())) { if (message.Length > 0) { message += " "; } message += SR.Format(SR.SerializationNotSupportedParentType, propertyType); } long lineNumber = reader.CurrentState._lineNumber; long bytePositionInLine = reader.CurrentState._bytePositionInLine; message += $" Path: {state.JsonPath()} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; throw new NotSupportedException(message, ex); } [DoesNotReturn] public static void ThrowNotSupportedException(ref WriteStack state, NotSupportedException ex) { string message = ex.Message; // The caller should check to ensure path is not already set. Debug.Assert(!message.Contains(" Path: ")); // Obtain the type to show in the message. Type propertyType = state.Current.JsonTypeInfo.Type; if (!message.Contains(propertyType.ToString())) { if (message.Length > 0) { message += " "; } message += SR.Format(SR.SerializationNotSupportedParentType, propertyType); } message += $" Path: {state.PropertyPath()}."; throw new NotSupportedException(message, ex); } [DoesNotReturn] public static void ThrowNotSupportedException_DeserializeNoConstructor(Type type, ref Utf8JsonReader reader, ref ReadStack state) { string message; if (type.IsInterface) { message = SR.Format(SR.DeserializePolymorphicInterface, type); } else { message = SR.Format(SR.DeserializeNoConstructor, nameof(JsonConstructorAttribute), type); } ThrowNotSupportedException(ref state, reader, new NotSupportedException(message)); } [DoesNotReturn] public static void ThrowNotSupportedException_CannotPopulateCollection(Type type, ref Utf8JsonReader reader, ref ReadStack state) { ThrowNotSupportedException(ref state, reader, new NotSupportedException(SR.Format(SR.CannotPopulateCollection, type))); } [DoesNotReturn] public static void ThrowJsonException_MetadataValuesInvalidToken(JsonTokenType tokenType) { ThrowJsonException(SR.Format(SR.MetadataInvalidTokenAfterValues, tokenType)); } [DoesNotReturn] public static void ThrowJsonException_MetadataReferenceNotFound(string id) { ThrowJsonException(SR.Format(SR.MetadataReferenceNotFound, id)); } [DoesNotReturn] public static void ThrowJsonException_MetadataValueWasNotString(JsonTokenType tokenType) { ThrowJsonException(SR.Format(SR.MetadataValueWasNotString, tokenType)); } [DoesNotReturn] public static void ThrowJsonException_MetadataValueWasNotString(JsonValueKind valueKind) { ThrowJsonException(SR.Format(SR.MetadataValueWasNotString, valueKind)); } [DoesNotReturn] public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(ReadOnlySpan<byte> propertyName, ref ReadStack state) { state.Current.JsonPropertyName = propertyName.ToArray(); ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); } [DoesNotReturn] public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties() { ThrowJsonException(SR.MetadataReferenceCannotContainOtherProperties); } [DoesNotReturn] public static void ThrowJsonException_MetadataIdIsNotFirstProperty(ReadOnlySpan<byte> propertyName, ref ReadStack state) { state.Current.JsonPropertyName = propertyName.ToArray(); ThrowJsonException(SR.MetadataIdIsNotFirstProperty); } [DoesNotReturn] public static void ThrowJsonException_MetadataMissingIdBeforeValues(ref ReadStack state, ReadOnlySpan<byte> propertyName) { state.Current.JsonPropertyName = propertyName.ToArray(); ThrowJsonException(SR.MetadataPreservedArrayPropertyNotFound); } [DoesNotReturn] public static void ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(ReadOnlySpan<byte> propertyName, ref ReadStack state, in Utf8JsonReader reader) { // Set PropertyInfo or KeyName to write down the conflicting property name in JsonException.Path if (state.Current.IsProcessingDictionary()) { state.Current.JsonPropertyNameAsString = reader.GetString(); } else { state.Current.JsonPropertyName = propertyName.ToArray(); } ThrowJsonException(SR.MetadataInvalidPropertyWithLeadingDollarSign); } [DoesNotReturn] public static void ThrowJsonException_MetadataDuplicateIdFound(string id) { ThrowJsonException(SR.Format(SR.MetadataDuplicateIdFound, id)); } [DoesNotReturn] public static void ThrowJsonException_MetadataInvalidReferenceToValueType(Type propertyType) { ThrowJsonException(SR.Format(SR.MetadataInvalidReferenceToValueType, propertyType)); } [DoesNotReturn] public static void ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref ReadStack state, Type propertyType, in Utf8JsonReader reader) { state.Current.JsonPropertyName = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan.ToArray(); string propertyNameAsString = reader.GetString()!; ThrowJsonException(SR.Format(SR.MetadataPreservedArrayFailed, SR.Format(SR.MetadataPreservedArrayInvalidProperty, propertyNameAsString), SR.Format(SR.DeserializeUnableToConvertValue, propertyType))); } [DoesNotReturn] public static void ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref ReadStack state, Type propertyType) { // Missing $values, JSON path should point to the property's object. state.Current.JsonPropertyName = null; ThrowJsonException(SR.Format(SR.MetadataPreservedArrayFailed, SR.MetadataPreservedArrayPropertyNotFound, SR.Format(SR.DeserializeUnableToConvertValue, propertyType))); } [DoesNotReturn] public static void ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(Type propertyType) { ThrowJsonException(SR.Format(SR.MetadataCannotParsePreservedObjectToImmutable, propertyType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_MetadataReferenceOfTypeCannotBeAssignedToType(string referenceId, Type currentType, Type typeToConvert) { throw new InvalidOperationException(SR.Format(SR.MetadataReferenceOfTypeCannotBeAssignedToType, referenceId, currentType, typeToConvert)); } [DoesNotReturn] internal static void ThrowUnexpectedMetadataException( ReadOnlySpan<byte> propertyName, ref Utf8JsonReader reader, ref ReadStack state) { if (state.Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterBase.ConstructorIsParameterized) { ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored(propertyName, ref reader, ref state); } MetadataPropertyName name = JsonSerializer.GetMetadataPropertyName(propertyName); if (name == MetadataPropertyName.Id) { ThrowJsonException_MetadataIdIsNotFirstProperty(propertyName, ref state); } else if (name == MetadataPropertyName.Ref) { ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(propertyName, ref state); } else { ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(propertyName, ref state, reader); } } [DoesNotReturn] public static void ThrowNotSupportedException_BuiltInConvertersNotRooted(Type type) { throw new NotSupportedException(SR.Format(SR.BuiltInConvertersNotRooted, type)); } [DoesNotReturn] public static void ThrowNotSupportedException_NoMetadataForType(Type type) { throw new NotSupportedException(SR.Format(SR.NoMetadataForType, type)); } [DoesNotReturn] public static void ThrowInvalidOperationException_NoMetadataForType(Type type) { throw new InvalidOperationException(SR.Format(SR.NoMetadataForType, type)); } [DoesNotReturn] public static void ThrowInvalidOperationException_MetadatInitFuncsNull() { throw new InvalidOperationException(SR.Format(SR.MetadataInitFuncsNull)); } public static void ThrowInvalidOperationException_NoMetadataForTypeProperties(JsonSerializerContext context, Type type) { throw new InvalidOperationException(SR.Format(SR.NoMetadataForTypeProperties, context.GetType(), type)); } public static void ThrowInvalidOperationException_NoMetadataForTypeCtorParams(JsonSerializerContext context, Type type) { throw new InvalidOperationException(SR.Format(SR.NoMetadataForTypeCtorParams, context.GetType(), type)); } public static void ThrowInvalidOperationException_NoDefaultOptionsForContext(JsonSerializerContext context, Type type) { throw new InvalidOperationException(SR.Format(SR.NoDefaultOptionsForContext, context.GetType(), type)); } [DoesNotReturn] public static void ThrowMissingMemberException_MissingFSharpCoreMember(string missingFsharpCoreMember) { throw new MissingMemberException(SR.Format(SR.MissingFSharpCoreMember, missingFsharpCoreMember)); } } }
1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.Callback.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { /// <summary> /// A converter that calls back in the serializer. /// </summary> private class CustomerCallbackConverter : JsonConverter<Customer> { public override bool CanConvert(Type typeToConvert) { return typeof(Customer).IsAssignableFrom(typeToConvert); } public override Customer Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // The options are not passed here as that would cause an infinite loop. Customer value = JsonSerializer.Deserialize<Customer>(ref reader); value.Name += "Hello!"; return value; } public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options) { writer.WriteStartArray(); long bytesWrittenSoFar = writer.BytesCommitted + writer.BytesPending; JsonSerializer.Serialize(writer, value); Debug.Assert(writer.BytesPending == 0); long payloadLength = writer.BytesCommitted - bytesWrittenSoFar; writer.WriteNumberValue(payloadLength); writer.WriteEndArray(); } } [Fact] public static void ConverterWithCallback() { const string json = @"{""Name"":""MyName""}"; var options = new JsonSerializerOptions(); options.Converters.Add(new CustomerCallbackConverter()); Customer customer = JsonSerializer.Deserialize<Customer>(json, options); Assert.Equal("MyNameHello!", customer.Name); string result = JsonSerializer.Serialize(customer, options); int expectedLength = JsonSerializer.Serialize(customer).Length; Assert.Equal(@"[{""CreditLimit"":0,""Name"":""MyNameHello!"",""Address"":{""City"":null}}," + $"{expectedLength}]", result); } /// <summary> /// A converter that calls back in the serializer with not supported types. /// </summary> private class PocoWithNotSupportedChildConverter : JsonConverter<ChildPocoWithConverter> { public override bool CanConvert(Type typeToConvert) { return typeof(ChildPocoWithConverter).IsAssignableFrom(typeToConvert); } public override ChildPocoWithConverter Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { reader.Read(); Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); Debug.Assert(reader.GetString() == "Child"); reader.Read(); Debug.Assert(reader.TokenType == JsonTokenType.StartObject); // The options are not passed here as that would cause an infinite loop. ChildPocoWithNoConverter value = JsonSerializer.Deserialize<ChildPocoWithNoConverter>(ref reader); // Should not get here due to exception. Debug.Assert(false); return default; } public override void Write(Utf8JsonWriter writer, ChildPocoWithConverter value, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WritePropertyName("Child"); JsonSerializer.Serialize<ChildPocoWithNoConverter>(writer, value.Child); // Should not get here due to exception. Debug.Assert(false); } } private class TopLevelPocoWithNoConverter { public ChildPocoWithConverter Child { get; set; } } private class ChildPocoWithConverter { public ChildPocoWithNoConverter Child { get; set; } } private class ChildPocoWithNoConverter { public ChildPocoWithNoConverterAndInvalidProperty InvalidProperty { get; set; } } private class ChildPocoWithNoConverterAndInvalidProperty { public int[,] NotSupported { get; set; } } [Fact] public static void ConverterWithReentryFail() { const string Json = @"{""Child"":{""Child"":{""InvalidProperty"":{""NotSupported"":[1]}}}}"; NotSupportedException ex; var options = new JsonSerializerOptions(); options.Converters.Add(new PocoWithNotSupportedChildConverter()); // This verifies: // - Path does not flow through to custom converters that re-enter the serializer. // - "Path:" is not repeated due to having two try\catch blocks (the second block does not append "Path:" again). ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<TopLevelPocoWithNoConverter>(Json, options)); Assert.Contains(typeof(int[,]).ToString(), ex.ToString()); Assert.Contains(typeof(ChildPocoWithNoConverterAndInvalidProperty).ToString(), ex.ToString()); Assert.Contains("Path: $.InvalidProperty | LineNumber: 0 | BytePositionInLine: 20.", ex.ToString()); Assert.Equal(2, ex.ToString().Split(new string[] { "Path:" }, StringSplitOptions.None).Length); var poco = new TopLevelPocoWithNoConverter() { Child = new ChildPocoWithConverter() { Child = new ChildPocoWithNoConverter() { InvalidProperty = new ChildPocoWithNoConverterAndInvalidProperty() { NotSupported = new int[,] { { 1, 2 } } } } } }; ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(poco, options)); Assert.Contains(typeof(int[,]).ToString(), ex.ToString()); Assert.Contains(typeof(ChildPocoWithNoConverterAndInvalidProperty).ToString(), ex.ToString()); Assert.Contains("Path: $.InvalidProperty.", ex.ToString()); Assert.Equal(2, ex.ToString().Split(new string[] { "Path:" }, StringSplitOptions.None).Length); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { /// <summary> /// A converter that calls back in the serializer. /// </summary> private class CustomerCallbackConverter : JsonConverter<Customer> { public override bool CanConvert(Type typeToConvert) { return typeof(Customer).IsAssignableFrom(typeToConvert); } public override Customer Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // The options are not passed here as that would cause an infinite loop. Customer value = JsonSerializer.Deserialize<Customer>(ref reader); value.Name += "Hello!"; return value; } public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options) { writer.WriteStartArray(); long bytesWrittenSoFar = writer.BytesCommitted + writer.BytesPending; JsonSerializer.Serialize(writer, value); Debug.Assert(writer.BytesPending == 0); long payloadLength = writer.BytesCommitted - bytesWrittenSoFar; writer.WriteNumberValue(payloadLength); writer.WriteEndArray(); } } [Fact] public static void ConverterWithCallback() { const string json = @"{""Name"":""MyName""}"; var options = new JsonSerializerOptions(); options.Converters.Add(new CustomerCallbackConverter()); Customer customer = JsonSerializer.Deserialize<Customer>(json, options); Assert.Equal("MyNameHello!", customer.Name); string result = JsonSerializer.Serialize(customer, options); int expectedLength = JsonSerializer.Serialize(customer).Length; Assert.Equal(@"[{""CreditLimit"":0,""Name"":""MyNameHello!"",""Address"":{""City"":null}}," + $"{expectedLength}]", result); } /// <summary> /// A converter that calls back in the serializer with not supported types. /// </summary> private class PocoWithNotSupportedChildConverter : JsonConverter<ChildPocoWithConverter> { public override bool CanConvert(Type typeToConvert) { return typeof(ChildPocoWithConverter).IsAssignableFrom(typeToConvert); } public override ChildPocoWithConverter Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { reader.Read(); Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); Debug.Assert(reader.GetString() == "Child"); reader.Read(); Debug.Assert(reader.TokenType == JsonTokenType.StartObject); // The options are not passed here as that would cause an infinite loop. ChildPocoWithNoConverter value = JsonSerializer.Deserialize<ChildPocoWithNoConverter>(ref reader); // Should not get here due to exception. Debug.Assert(false); return default; } public override void Write(Utf8JsonWriter writer, ChildPocoWithConverter value, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WritePropertyName("Child"); JsonSerializer.Serialize<ChildPocoWithNoConverter>(writer, value.Child); // Should not get here due to exception. Debug.Assert(false); } } private class TopLevelPocoWithNoConverter { public ChildPocoWithConverter Child { get; set; } } private class ChildPocoWithConverter { public ChildPocoWithNoConverter Child { get; set; } } private class ChildPocoWithNoConverter { public ChildPocoWithNoConverterAndInvalidProperty InvalidProperty { get; set; } } private class ChildPocoWithNoConverterAndInvalidProperty { public int[,] NotSupported { get; set; } } [Fact] public static void ConverterWithReentryFail() { const string Json = @"{""Child"":{""Child"":{""InvalidProperty"":{""NotSupported"":[1]}}}}"; NotSupportedException ex; var options = new JsonSerializerOptions(); options.Converters.Add(new PocoWithNotSupportedChildConverter()); // This verifies: // - Path does not flow through to custom converters that re-enter the serializer. // - "Path:" is not repeated due to having two try\catch blocks (the second block does not append "Path:" again). ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<TopLevelPocoWithNoConverter>(Json, options)); Assert.Contains(typeof(int[,]).ToString(), ex.ToString()); Assert.Contains(typeof(ChildPocoWithNoConverter).ToString(), ex.ToString()); Assert.Contains("Path: $.InvalidProperty | LineNumber: 0 | BytePositionInLine: 20.", ex.ToString()); Assert.Equal(2, ex.ToString().Split(new string[] { "Path:" }, StringSplitOptions.None).Length); var poco = new TopLevelPocoWithNoConverter() { Child = new ChildPocoWithConverter() { Child = new ChildPocoWithNoConverter() { InvalidProperty = new ChildPocoWithNoConverterAndInvalidProperty() { NotSupported = new int[,] { { 1, 2 } } } } } }; ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(poco, options)); Assert.Contains(typeof(int[,]).ToString(), ex.ToString()); Assert.Contains(typeof(ChildPocoWithNoConverter).ToString(), ex.ToString()); Assert.Contains("Path: $.InvalidProperty.", ex.ToString()); Assert.Equal(2, ex.ToString().Split(new string[] { "Path:" }, StringSplitOptions.None).Length); } } }
1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/ExceptionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization; using System.Text.Encodings.Web; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class ExceptionTests { [Fact] public static void RootThrownFromReaderFails() { try { int i2 = JsonSerializer.Deserialize<int>("12bad"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal(0, e.LineNumber); Assert.Equal(2, e.BytePositionInLine); Assert.Equal("$", e.Path); Assert.Contains("Path: $ | LineNumber: 0 | BytePositionInLine: 2.", e.Message); // Verify Path is not repeated. Assert.True(e.Message.IndexOf("Path:") == e.Message.LastIndexOf("Path:")); } } [Fact] public static void TypeMismatchIDictionaryExceptionThrown() { try { JsonSerializer.Deserialize<IDictionary<string, string>>(@"{""Key"":1}"); Assert.True(false, "Type Mismatch JsonException was not thrown."); } catch (JsonException e) { Assert.Equal(0, e.LineNumber); Assert.Equal(8, e.BytePositionInLine); Assert.Contains("LineNumber: 0 | BytePositionInLine: 8.", e.Message); Assert.Contains("$.Key", e.Path); // Verify Path is not repeated. Assert.True(e.Message.IndexOf("Path:") == e.Message.LastIndexOf("Path:")); } } [Fact] public static void TypeMismatchIDictionaryExceptionWithCustomEscaperThrown() { var options = new JsonSerializerOptions(); options.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; JsonException e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, int>>("{\"Key\u0467\":1", options)); Assert.Equal(0, e.LineNumber); Assert.Equal(10, e.BytePositionInLine); Assert.Contains("LineNumber: 0 | BytePositionInLine: 10.", e.Message); Assert.Contains("$.Key\u0467", e.Path); // Verify Path is not repeated. Assert.True(e.Message.IndexOf("Path:") == e.Message.LastIndexOf("Path:")); } [Fact] public static void ThrownFromReaderFails() { string json = Encoding.UTF8.GetString(BasicCompany.s_data); json = json.Replace(@"""zip"" : 98052", @"""zip"" : bad"); try { JsonSerializer.Deserialize<BasicCompany>(json); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal(18, e.LineNumber); Assert.Equal(8, e.BytePositionInLine); Assert.Equal("$.mainSite.zip", e.Path); Assert.Contains("Path: $.mainSite.zip | LineNumber: 18 | BytePositionInLine: 8.", e.Message); // Verify Path is not repeated. Assert.True(e.Message.IndexOf("Path:") == e.Message.LastIndexOf("Path:")); Assert.NotNull(e.InnerException); JsonException inner = (JsonException)e.InnerException; Assert.Equal(18, inner.LineNumber); Assert.Equal(8, inner.BytePositionInLine); } } [Fact] public static void PathForDictionaryFails() { try { JsonSerializer.Deserialize<Dictionary<string, int>>(@"{""Key1"":1, ""Key2"":bad}"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Key2", e.Path); } try { JsonSerializer.Deserialize<Dictionary<string, int>>(@"{""Key1"":1, ""Key2"":"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Key2", e.Path); } try { JsonSerializer.Deserialize<Dictionary<string, int>>(@"{""Key1"":1, ""Key2"""); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { // Key2 is not yet a valid key name since there is no : delimiter. Assert.Equal("$.Key1", e.Path); } } [Fact] public static void DeserializePathForDictionaryFails() { const string Json = "{\"Key1\u0467\":1, \"Key2\u0467\":bad}"; const string JsonEscaped = "{\"Key1\\u0467\":1, \"Key2\\u0467\":bad}"; const string Expected = "$.Key2\u0467"; JsonException e; // Without custom escaper. e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, int>>(Json)); Assert.Equal(Expected, e.Path); e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, int>>(JsonEscaped)); Assert.Equal(Expected, e.Path); // Custom escaper should not change Path. var options = new JsonSerializerOptions(); options.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, int>>(Json, options)); Assert.Equal(Expected, e.Path); e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, int>>(JsonEscaped, options)); Assert.Equal(Expected, e.Path); } private class ClassWithUnicodePropertyName { public int Property\u04671 { get; set; } // contains a trailing "1" } [Fact] public static void DeserializePathForObjectFails() { const string GoodJson = "{\"Property\u04671\":1}"; const string GoodJsonEscaped = "{\"Property\\u04671\":1}"; const string BadJson = "{\"Property\u04671\":bad}"; const string BadJsonEscaped = "{\"Property\\u04671\":bad}"; const string Expected = "$.Property\u04671"; ClassWithUnicodePropertyName obj; // Baseline. obj = JsonSerializer.Deserialize<ClassWithUnicodePropertyName>(GoodJson); Assert.Equal(1, obj.Property\u04671); obj = JsonSerializer.Deserialize<ClassWithUnicodePropertyName>(GoodJsonEscaped); Assert.Equal(1, obj.Property\u04671); JsonException e; // Exception. e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<ClassWithUnicodePropertyName>(BadJson)); Assert.Equal(Expected, e.Path); e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<ClassWithUnicodePropertyName>(BadJsonEscaped)); Assert.Equal(Expected, e.Path); } [Fact] public static void PathForArrayFails() { try { JsonSerializer.Deserialize<int[]>(@"[1, bad]"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$[1]", e.Path); } try { JsonSerializer.Deserialize<int[]>(@"[1,"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$[1]", e.Path); } try { JsonSerializer.Deserialize<int[]>(@"[1"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { // No delimiter. Assert.Equal("$[0]", e.Path); } try { JsonSerializer.Deserialize<int[]>(@"[1 /* comment starts but doesn't end"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { // The reader treats the space as a delimiter. Assert.Equal("$[1]", e.Path); } } [Fact] public static void PathForListFails() { try { JsonSerializer.Deserialize<List<int>>(@"[1, bad]"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$[1]", e.Path); } } [Fact] public static void PathFor2dArrayFails() { try { JsonSerializer.Deserialize<int[][]>(@"[[1, 2],[3,bad]]"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$[1][1]", e.Path); } } [Fact] public static void PathFor2dListFails() { try { JsonSerializer.Deserialize<List<List<int>>>(@"[[1, 2],[3,bad]]"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$[1][1]", e.Path); } } [Fact] public static void PathForChildPropertyFails() { try { JsonSerializer.Deserialize<RootClass>(@"{""Child"":{""MyInt"":bad]}"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Child.MyInt", e.Path); } } [Fact] public static void PathForChildListFails() { try { JsonSerializer.Deserialize<RootClass>(@"{""Child"":{""MyIntArray"":[1, bad]}"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Child.MyIntArray[1]", e.Path); } } [Fact] public static void PathForChildDictionaryFails() { try { JsonSerializer.Deserialize<RootClass>(@"{""Child"":{""MyDictionary"":{""Key"": bad]"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Child.MyDictionary.Key", e.Path); } } [Fact] public static void PathForSpecialCharacterFails() { try { JsonSerializer.Deserialize<RootClass>(@"{""Child"":{""MyDictionary"":{""Key1"":{""Children"":[{""MyDictionary"":{""K.e.y"":"""); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Child.MyDictionary.Key1.Children[0].MyDictionary['K.e.y']", e.Path); } } [Fact] public static void PathForSpecialCharacterNestedFails() { try { JsonSerializer.Deserialize<RootClass>(@"{""Child"":{""Children"":[{}, {""MyDictionary"":{""K.e.y"": {""MyInt"":bad"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Child.Children[1].MyDictionary['K.e.y'].MyInt", e.Path); } } [Fact] public static void EscapingFails() { try { ClassWithUnicodeProperty obj = JsonSerializer.Deserialize<ClassWithUnicodeProperty>("{\"A\u0467\":bad}"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.A\u0467", e.Path); } } [Fact] public static void CaseInsensitiveFails() { var options = new JsonSerializerOptions(); options.PropertyNameCaseInsensitive = true; // Baseline (no exception) { SimpleTestClass obj = JsonSerializer.Deserialize<SimpleTestClass>(@"{""myint32"":1}", options); Assert.Equal(1, obj.MyInt32); } { SimpleTestClass obj = JsonSerializer.Deserialize<SimpleTestClass>(@"{""MYINT32"":1}", options); Assert.Equal(1, obj.MyInt32); } try { JsonSerializer.Deserialize<SimpleTestClass>(@"{""myint32"":bad}", options); } catch (JsonException e) { // The Path should reflect the case even though it is different from the property. Assert.Equal("$.myint32", e.Path); } try { JsonSerializer.Deserialize<SimpleTestClass>(@"{""MYINT32"":bad}", options); } catch (JsonException e) { // Verify the previous json property name was not cached. Assert.Equal("$.MYINT32", e.Path); } } public class RootClass { public ChildClass Child { get; set; } } public class ChildClass { public int MyInt { get; set; } public int[] MyIntArray { get; set; } public Dictionary<string, ChildClass> MyDictionary { get; set; } public ChildClass[] Children { get; set; } } private class ClassWithPropertyToClassWithInvalidArray { public ClassWithInvalidArray Inner { get; set; } = new ClassWithInvalidArray(); } private class ClassWithInvalidArray { public int[,] UnsupportedArray { get; set; } } private class ClassWithInvalidDictionary { public Dictionary<string, int[,]> UnsupportedDictionary { get; set; } } [Fact] public static void ClassWithUnsupportedArray() { Exception ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<ClassWithInvalidArray>(@"{""UnsupportedArray"":[]}")); // The exception contains the type. Assert.Contains(typeof(int[,]).ToString(), ex.Message); ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(new ClassWithInvalidArray())); Assert.Contains(typeof(int[,]).ToString(), ex.Message); Assert.DoesNotContain("Path: ", ex.Message); } [Fact] public static void ClassWithUnsupportedArrayInProperty() { Exception ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<ClassWithPropertyToClassWithInvalidArray>(@"{""Inner"":{""UnsupportedArray"":[]}}")); // The exception contains the type and Path. Assert.Contains(typeof(int[,]).ToString(), ex.Message); Assert.Contains("Path: $.Inner | LineNumber: 0 | BytePositionInLine: 10.", ex.Message); ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(new ClassWithPropertyToClassWithInvalidArray())); Assert.Contains(typeof(int[,]).ToString(), ex.Message); Assert.Contains(typeof(ClassWithInvalidArray).ToString(), ex.Message); Assert.Contains("Path: $.Inner.", ex.Message); // The original exception contains the type. Assert.NotNull(ex.InnerException); Assert.Contains(typeof(int[,]).ToString(), ex.InnerException.Message); Assert.DoesNotContain("Path: ", ex.InnerException.Message); } [Fact] public static void ClassWithUnsupportedDictionary() { Exception ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<ClassWithInvalidDictionary>(@"{""UnsupportedDictionary"":{}}")); Assert.Contains("System.Int32[,]", ex.Message); // The exception for element types does not contain the parent type and the property name // since the verification occurs later and is no longer bound to the parent type. Assert.DoesNotContain("ClassWithInvalidDictionary.UnsupportedDictionary", ex.Message); // The exception for element types includes Path. Assert.Contains("Path: $.UnsupportedDictionary", ex.Message); // Serializing works for unsupported types if the property is null; elements are not verified until serialization occurs. var obj = new ClassWithInvalidDictionary(); string json = JsonSerializer.Serialize(obj); Assert.Equal(@"{""UnsupportedDictionary"":null}", json); obj.UnsupportedDictionary = new Dictionary<string, int[,]>(); ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(obj)); // The exception contains the type and Path. Assert.Contains(typeof(int[,]).ToString(), ex.Message); Assert.Contains("Path: $.UnsupportedDictionary", ex.Message); // The original exception contains the type. Assert.NotNull(ex.InnerException); Assert.Contains(typeof(int[,]).ToString(), ex.InnerException.Message); Assert.DoesNotContain("Path: ", ex.InnerException.Message); } [Fact] public static void UnsupportedTypeFromRoot() { Exception ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<int[,]>(@"[]")); Assert.Contains(typeof(int[,]).ToString(), ex.Message); // Root-level Types (not from a property) do not include the Path. Assert.DoesNotContain("Path: $", ex.Message); } [Theory] [InlineData(typeof(ClassWithBadCtor))] [InlineData(typeof(StructWithBadCtor))] public static void TypeWithBadCtorNoProps(Type type) { var instance = Activator.CreateInstance( type, BindingFlags.Instance | BindingFlags.Public, binder: null, args: new object[] { new SerializationInfo(typeof(Type), new FormatterConverter()), new StreamingContext(default) }, culture: null)!; Assert.Equal("{}", JsonSerializer.Serialize(instance, type)); // Each constructor parameter must bind to an object property or field. InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize("{}", type)); Assert.Contains(type.FullName, ex.ToString()); } [Theory] [InlineData(typeof(ClassWithBadCtor_WithProps))] [InlineData(typeof(StructWithBadCtor_WithProps))] public static void TypeWithBadCtorWithPropsInvalid(Type type) { var instance = Activator.CreateInstance( type, BindingFlags.Instance | BindingFlags.Public, binder: null, args: new object[] { new SerializationInfo(typeof(Type), new FormatterConverter()), new StreamingContext(default) }, culture: null)!; string serializationInfoName = typeof(SerializationInfo).FullName; // (De)serialization of SerializationInfo type is not supported. NotSupportedException ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(instance, type)); string exAsStr = ex.ToString(); Assert.Contains(serializationInfoName, exAsStr); Assert.Contains("$.Info", exAsStr); ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize(@"{""Info"":{}}", type)); exAsStr = ex.ToString(); Assert.Contains(serializationInfoName, exAsStr); Assert.Contains("$.Info", exAsStr); // Deserialization of null is okay since no data is read. object obj = JsonSerializer.Deserialize(@"{""Info"":null}", type); Assert.Null(type.GetProperty("Info").GetValue(obj)); // Deserialization of other non-null tokens is not okay. Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize(@"{""Info"":1}", type)); Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize(@"{""Info"":""""}", type)); } public class ClassWithBadCtor { public ClassWithBadCtor(SerializationInfo info, StreamingContext ctx) { } } public struct StructWithBadCtor { [JsonConstructor] public StructWithBadCtor(SerializationInfo info, StreamingContext ctx) { } } public class ClassWithBadCtor_WithProps { public SerializationInfo Info { get; set; } public StreamingContext Ctx { get; set; } public ClassWithBadCtor_WithProps(SerializationInfo info, StreamingContext ctx) => (Info, Ctx) = (info, ctx); } public struct StructWithBadCtor_WithProps { public SerializationInfo Info { get; set; } public StreamingContext Ctx { get; set; } [JsonConstructor] public StructWithBadCtor_WithProps(SerializationInfo info, StreamingContext ctx) => (Info, Ctx) = (info, ctx); } [Fact] public static void CustomConverterThrowingJsonException_Serialization_ShouldNotOverwriteMetadata() { JsonException ex = Assert.Throws<JsonException>(() => JsonSerializer.Serialize(new { Value = new PocoUsingCustomConverterThrowingJsonException() })); Assert.Equal(PocoConverterThrowingCustomJsonException.ExceptionMessage, ex.Message); Assert.Equal(PocoConverterThrowingCustomJsonException.ExceptionPath, ex.Path); } [Fact] public static void CustomConverterThrowingJsonException_Deserialization_ShouldNotOverwriteMetadata() { JsonException ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<PocoUsingCustomConverterThrowingJsonException[]>(@"[{}]")); Assert.Equal(PocoConverterThrowingCustomJsonException.ExceptionMessage, ex.Message); Assert.Equal(PocoConverterThrowingCustomJsonException.ExceptionPath, ex.Path); } [JsonConverter(typeof(PocoConverterThrowingCustomJsonException))] public class PocoUsingCustomConverterThrowingJsonException { } public class PocoConverterThrowingCustomJsonException : JsonConverter<PocoUsingCustomConverterThrowingJsonException> { public const string ExceptionMessage = "Custom JsonException mesage"; public const string ExceptionPath = "$.CustomPath"; public override PocoUsingCustomConverterThrowingJsonException? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new JsonException(ExceptionMessage, ExceptionPath, 0, 0); public override void Write(Utf8JsonWriter writer, PocoUsingCustomConverterThrowingJsonException value, JsonSerializerOptions options) => throw new JsonException(ExceptionMessage, ExceptionPath, 0, 0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization; using System.Text.Encodings.Web; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class ExceptionTests { [Fact] public static void RootThrownFromReaderFails() { try { int i2 = JsonSerializer.Deserialize<int>("12bad"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal(0, e.LineNumber); Assert.Equal(2, e.BytePositionInLine); Assert.Equal("$", e.Path); Assert.Contains("Path: $ | LineNumber: 0 | BytePositionInLine: 2.", e.Message); // Verify Path is not repeated. Assert.True(e.Message.IndexOf("Path:") == e.Message.LastIndexOf("Path:")); } } [Fact] public static void TypeMismatchIDictionaryExceptionThrown() { try { JsonSerializer.Deserialize<IDictionary<string, string>>(@"{""Key"":1}"); Assert.True(false, "Type Mismatch JsonException was not thrown."); } catch (JsonException e) { Assert.Equal(0, e.LineNumber); Assert.Equal(8, e.BytePositionInLine); Assert.Contains("LineNumber: 0 | BytePositionInLine: 8.", e.Message); Assert.Contains("$.Key", e.Path); // Verify Path is not repeated. Assert.True(e.Message.IndexOf("Path:") == e.Message.LastIndexOf("Path:")); } } [Fact] public static void TypeMismatchIDictionaryExceptionWithCustomEscaperThrown() { var options = new JsonSerializerOptions(); options.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; JsonException e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, int>>("{\"Key\u0467\":1", options)); Assert.Equal(0, e.LineNumber); Assert.Equal(10, e.BytePositionInLine); Assert.Contains("LineNumber: 0 | BytePositionInLine: 10.", e.Message); Assert.Contains("$.Key\u0467", e.Path); // Verify Path is not repeated. Assert.True(e.Message.IndexOf("Path:") == e.Message.LastIndexOf("Path:")); } [Fact] public static void ThrownFromReaderFails() { string json = Encoding.UTF8.GetString(BasicCompany.s_data); json = json.Replace(@"""zip"" : 98052", @"""zip"" : bad"); try { JsonSerializer.Deserialize<BasicCompany>(json); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal(18, e.LineNumber); Assert.Equal(8, e.BytePositionInLine); Assert.Equal("$.mainSite.zip", e.Path); Assert.Contains("Path: $.mainSite.zip | LineNumber: 18 | BytePositionInLine: 8.", e.Message); // Verify Path is not repeated. Assert.True(e.Message.IndexOf("Path:") == e.Message.LastIndexOf("Path:")); Assert.NotNull(e.InnerException); JsonException inner = (JsonException)e.InnerException; Assert.Equal(18, inner.LineNumber); Assert.Equal(8, inner.BytePositionInLine); } } [Fact] public static void PathForDictionaryFails() { try { JsonSerializer.Deserialize<Dictionary<string, int>>(@"{""Key1"":1, ""Key2"":bad}"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Key2", e.Path); } try { JsonSerializer.Deserialize<Dictionary<string, int>>(@"{""Key1"":1, ""Key2"":"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Key2", e.Path); } try { JsonSerializer.Deserialize<Dictionary<string, int>>(@"{""Key1"":1, ""Key2"""); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { // Key2 is not yet a valid key name since there is no : delimiter. Assert.Equal("$.Key1", e.Path); } } [Fact] public static void DeserializePathForDictionaryFails() { const string Json = "{\"Key1\u0467\":1, \"Key2\u0467\":bad}"; const string JsonEscaped = "{\"Key1\\u0467\":1, \"Key2\\u0467\":bad}"; const string Expected = "$.Key2\u0467"; JsonException e; // Without custom escaper. e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, int>>(Json)); Assert.Equal(Expected, e.Path); e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, int>>(JsonEscaped)); Assert.Equal(Expected, e.Path); // Custom escaper should not change Path. var options = new JsonSerializerOptions(); options.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, int>>(Json, options)); Assert.Equal(Expected, e.Path); e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Dictionary<string, int>>(JsonEscaped, options)); Assert.Equal(Expected, e.Path); } private class ClassWithUnicodePropertyName { public int Property\u04671 { get; set; } // contains a trailing "1" } [Fact] public static void DeserializePathForObjectFails() { const string GoodJson = "{\"Property\u04671\":1}"; const string GoodJsonEscaped = "{\"Property\\u04671\":1}"; const string BadJson = "{\"Property\u04671\":bad}"; const string BadJsonEscaped = "{\"Property\\u04671\":bad}"; const string Expected = "$.Property\u04671"; ClassWithUnicodePropertyName obj; // Baseline. obj = JsonSerializer.Deserialize<ClassWithUnicodePropertyName>(GoodJson); Assert.Equal(1, obj.Property\u04671); obj = JsonSerializer.Deserialize<ClassWithUnicodePropertyName>(GoodJsonEscaped); Assert.Equal(1, obj.Property\u04671); JsonException e; // Exception. e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<ClassWithUnicodePropertyName>(BadJson)); Assert.Equal(Expected, e.Path); e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<ClassWithUnicodePropertyName>(BadJsonEscaped)); Assert.Equal(Expected, e.Path); } [Fact] public static void PathForArrayFails() { try { JsonSerializer.Deserialize<int[]>(@"[1, bad]"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$[1]", e.Path); } try { JsonSerializer.Deserialize<int[]>(@"[1,"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$[1]", e.Path); } try { JsonSerializer.Deserialize<int[]>(@"[1"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { // No delimiter. Assert.Equal("$[0]", e.Path); } try { JsonSerializer.Deserialize<int[]>(@"[1 /* comment starts but doesn't end"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { // The reader treats the space as a delimiter. Assert.Equal("$[1]", e.Path); } } [Fact] public static void PathForListFails() { try { JsonSerializer.Deserialize<List<int>>(@"[1, bad]"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$[1]", e.Path); } } [Fact] public static void PathFor2dArrayFails() { try { JsonSerializer.Deserialize<int[][]>(@"[[1, 2],[3,bad]]"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$[1][1]", e.Path); } } [Fact] public static void PathFor2dListFails() { try { JsonSerializer.Deserialize<List<List<int>>>(@"[[1, 2],[3,bad]]"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$[1][1]", e.Path); } } [Fact] public static void PathForChildPropertyFails() { try { JsonSerializer.Deserialize<RootClass>(@"{""Child"":{""MyInt"":bad]}"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Child.MyInt", e.Path); } } [Fact] public static void PathForChildListFails() { try { JsonSerializer.Deserialize<RootClass>(@"{""Child"":{""MyIntArray"":[1, bad]}"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Child.MyIntArray[1]", e.Path); } } [Fact] public static void PathForChildDictionaryFails() { try { JsonSerializer.Deserialize<RootClass>(@"{""Child"":{""MyDictionary"":{""Key"": bad]"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Child.MyDictionary.Key", e.Path); } } [Fact] public static void PathForSpecialCharacterFails() { try { JsonSerializer.Deserialize<RootClass>(@"{""Child"":{""MyDictionary"":{""Key1"":{""Children"":[{""MyDictionary"":{""K.e.y"":"""); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Child.MyDictionary.Key1.Children[0].MyDictionary['K.e.y']", e.Path); } } [Fact] public static void PathForSpecialCharacterNestedFails() { try { JsonSerializer.Deserialize<RootClass>(@"{""Child"":{""Children"":[{}, {""MyDictionary"":{""K.e.y"": {""MyInt"":bad"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.Child.Children[1].MyDictionary['K.e.y'].MyInt", e.Path); } } [Fact] public static void EscapingFails() { try { ClassWithUnicodeProperty obj = JsonSerializer.Deserialize<ClassWithUnicodeProperty>("{\"A\u0467\":bad}"); Assert.True(false, "Expected JsonException was not thrown."); } catch (JsonException e) { Assert.Equal("$.A\u0467", e.Path); } } [Fact] public static void CaseInsensitiveFails() { var options = new JsonSerializerOptions(); options.PropertyNameCaseInsensitive = true; // Baseline (no exception) { SimpleTestClass obj = JsonSerializer.Deserialize<SimpleTestClass>(@"{""myint32"":1}", options); Assert.Equal(1, obj.MyInt32); } { SimpleTestClass obj = JsonSerializer.Deserialize<SimpleTestClass>(@"{""MYINT32"":1}", options); Assert.Equal(1, obj.MyInt32); } try { JsonSerializer.Deserialize<SimpleTestClass>(@"{""myint32"":bad}", options); } catch (JsonException e) { // The Path should reflect the case even though it is different from the property. Assert.Equal("$.myint32", e.Path); } try { JsonSerializer.Deserialize<SimpleTestClass>(@"{""MYINT32"":bad}", options); } catch (JsonException e) { // Verify the previous json property name was not cached. Assert.Equal("$.MYINT32", e.Path); } } public class RootClass { public ChildClass Child { get; set; } } public class ChildClass { public int MyInt { get; set; } public int[] MyIntArray { get; set; } public Dictionary<string, ChildClass> MyDictionary { get; set; } public ChildClass[] Children { get; set; } } private class ClassWithPropertyToClassWithInvalidArray { public ClassWithInvalidArray Inner { get; set; } = new ClassWithInvalidArray(); } private class ClassWithInvalidArray { public int[,] UnsupportedArray { get; set; } } private class ClassWithInvalidDictionary { public Dictionary<string, int[,]> UnsupportedDictionary { get; set; } } [Fact] public static void ClassWithUnsupportedArray() { Exception ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<ClassWithInvalidArray>(@"{""UnsupportedArray"":[]}")); // The exception contains the type. Assert.Contains(typeof(int[,]).ToString(), ex.Message); ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(new ClassWithInvalidArray())); Assert.Contains(typeof(int[,]).ToString(), ex.Message); Assert.DoesNotContain("Path: ", ex.Message); } [Fact] public static void ClassWithUnsupportedArrayInProperty() { Exception ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<ClassWithPropertyToClassWithInvalidArray>(@"{""Inner"":{""UnsupportedArray"":[]}}")); // The exception contains the type and Path. Assert.Contains(typeof(int[,]).ToString(), ex.Message); Assert.Contains("Path: $.Inner | LineNumber: 0 | BytePositionInLine: 10.", ex.Message); ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(new ClassWithPropertyToClassWithInvalidArray())); Assert.Contains(typeof(int[,]).ToString(), ex.Message); Assert.Contains(typeof(ClassWithPropertyToClassWithInvalidArray).ToString(), ex.Message); Assert.Contains("Path: $.Inner.", ex.Message); // The original exception contains the type. Assert.NotNull(ex.InnerException); Assert.Contains(typeof(int[,]).ToString(), ex.InnerException.Message); Assert.DoesNotContain("Path: ", ex.InnerException.Message); } [Fact] public static void ClassWithUnsupportedDictionary() { Exception ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<ClassWithInvalidDictionary>(@"{""UnsupportedDictionary"":{}}")); Assert.Contains("System.Int32[,]", ex.Message); // The exception for element types does not contain the parent type and the property name // since the verification occurs later and is no longer bound to the parent type. Assert.DoesNotContain("ClassWithInvalidDictionary.UnsupportedDictionary", ex.Message); // The exception for element types includes Path. Assert.Contains("Path: $.UnsupportedDictionary", ex.Message); // Serializing works for unsupported types if the property is null; elements are not verified until serialization occurs. var obj = new ClassWithInvalidDictionary(); string json = JsonSerializer.Serialize(obj); Assert.Equal(@"{""UnsupportedDictionary"":null}", json); obj.UnsupportedDictionary = new Dictionary<string, int[,]>(); ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(obj)); // The exception contains the type and Path. Assert.Contains(typeof(int[,]).ToString(), ex.Message); Assert.Contains("Path: $.UnsupportedDictionary", ex.Message); // The original exception contains the type. Assert.NotNull(ex.InnerException); Assert.Contains(typeof(int[,]).ToString(), ex.InnerException.Message); Assert.DoesNotContain("Path: ", ex.InnerException.Message); } [Fact] public static void UnsupportedTypeFromRoot() { Exception ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<int[,]>(@"[]")); Assert.Contains(typeof(int[,]).ToString(), ex.Message); // Root-level Types (not from a property) do not include the Path. Assert.DoesNotContain("Path: $", ex.Message); } [Theory] [InlineData(typeof(ClassWithBadCtor))] [InlineData(typeof(StructWithBadCtor))] public static void TypeWithBadCtorNoProps(Type type) { var instance = Activator.CreateInstance( type, BindingFlags.Instance | BindingFlags.Public, binder: null, args: new object[] { new SerializationInfo(typeof(Type), new FormatterConverter()), new StreamingContext(default) }, culture: null)!; Assert.Equal("{}", JsonSerializer.Serialize(instance, type)); // Each constructor parameter must bind to an object property or field. InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize("{}", type)); Assert.Contains(type.FullName, ex.ToString()); } [Theory] [InlineData(typeof(ClassWithBadCtor_WithProps))] [InlineData(typeof(StructWithBadCtor_WithProps))] public static void TypeWithBadCtorWithPropsInvalid(Type type) { var instance = Activator.CreateInstance( type, BindingFlags.Instance | BindingFlags.Public, binder: null, args: new object[] { new SerializationInfo(typeof(Type), new FormatterConverter()), new StreamingContext(default) }, culture: null)!; string serializationInfoName = typeof(SerializationInfo).FullName; // (De)serialization of SerializationInfo type is not supported. NotSupportedException ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Serialize(instance, type)); string exAsStr = ex.ToString(); Assert.Contains(serializationInfoName, exAsStr); Assert.Contains("$.Info", exAsStr); ex = Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize(@"{""Info"":{}}", type)); exAsStr = ex.ToString(); Assert.Contains(serializationInfoName, exAsStr); Assert.Contains("$.Info", exAsStr); // Deserialization of null is okay since no data is read. object obj = JsonSerializer.Deserialize(@"{""Info"":null}", type); Assert.Null(type.GetProperty("Info").GetValue(obj)); // Deserialization of other non-null tokens is not okay. Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize(@"{""Info"":1}", type)); Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize(@"{""Info"":""""}", type)); } public class ClassWithBadCtor { public ClassWithBadCtor(SerializationInfo info, StreamingContext ctx) { } } public struct StructWithBadCtor { [JsonConstructor] public StructWithBadCtor(SerializationInfo info, StreamingContext ctx) { } } public class ClassWithBadCtor_WithProps { public SerializationInfo Info { get; set; } public StreamingContext Ctx { get; set; } public ClassWithBadCtor_WithProps(SerializationInfo info, StreamingContext ctx) => (Info, Ctx) = (info, ctx); } public struct StructWithBadCtor_WithProps { public SerializationInfo Info { get; set; } public StreamingContext Ctx { get; set; } [JsonConstructor] public StructWithBadCtor_WithProps(SerializationInfo info, StreamingContext ctx) => (Info, Ctx) = (info, ctx); } [Fact] public static void CustomConverterThrowingJsonException_Serialization_ShouldNotOverwriteMetadata() { JsonException ex = Assert.Throws<JsonException>(() => JsonSerializer.Serialize(new { Value = new PocoUsingCustomConverterThrowingJsonException() })); Assert.Equal(PocoConverterThrowingCustomJsonException.ExceptionMessage, ex.Message); Assert.Equal(PocoConverterThrowingCustomJsonException.ExceptionPath, ex.Path); } [Fact] public static void CustomConverterThrowingJsonException_Deserialization_ShouldNotOverwriteMetadata() { JsonException ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<PocoUsingCustomConverterThrowingJsonException[]>(@"[{}]")); Assert.Equal(PocoConverterThrowingCustomJsonException.ExceptionMessage, ex.Message); Assert.Equal(PocoConverterThrowingCustomJsonException.ExceptionPath, ex.Path); } [JsonConverter(typeof(PocoConverterThrowingCustomJsonException))] public class PocoUsingCustomConverterThrowingJsonException { } public class PocoConverterThrowingCustomJsonException : JsonConverter<PocoUsingCustomConverterThrowingJsonException> { public const string ExceptionMessage = "Custom JsonException mesage"; public const string ExceptionPath = "$.CustomPath"; public override PocoUsingCustomConverterThrowingJsonException? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new JsonException(ExceptionMessage, ExceptionPath, 0, 0); public override void Write(Utf8JsonWriter writer, PocoUsingCustomConverterThrowingJsonException value, JsonSerializerOptions options) => throw new JsonException(ExceptionMessage, ExceptionPath, 0, 0); } } }
1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace System.Reflection.Emit { public partial class ILGenerator { internal ILGenerator() { // Prevent generating a default constructor } public virtual int ILOffset { get { return default; } } public virtual void BeginCatchBlock(Type exceptionType) { } public virtual void BeginExceptFilterBlock() { } public virtual Label BeginExceptionBlock() { return default; } public virtual void BeginFaultBlock() { } public virtual void BeginFinallyBlock() { } public virtual void BeginScope() { } public virtual LocalBuilder DeclareLocal(Type localType) { return default; } public virtual LocalBuilder DeclareLocal(Type localType, bool pinned) { return default; } public virtual Label DefineLabel() { return default; } public virtual void Emit(OpCode opcode) { } public virtual void Emit(OpCode opcode, byte arg) { } public virtual void Emit(OpCode opcode, double arg) { } public virtual void Emit(OpCode opcode, short arg) { } public virtual void Emit(OpCode opcode, int arg) { } public virtual void Emit(OpCode opcode, long arg) { } public virtual void Emit(OpCode opcode, ConstructorInfo con) { } public virtual void Emit(OpCode opcode, Label label) { } public virtual void Emit(OpCode opcode, Label[] labels) { } public virtual void Emit(OpCode opcode, LocalBuilder local) { } public virtual void Emit(OpCode opcode, SignatureHelper signature) { } public virtual void Emit(OpCode opcode, FieldInfo field) { } public virtual void Emit(OpCode opcode, MethodInfo meth) { } [CLSCompliantAttribute(false)] public void Emit(OpCode opcode, sbyte arg) { } public virtual void Emit(OpCode opcode, float arg) { } public virtual void Emit(OpCode opcode, string str) { } public virtual void Emit(OpCode opcode, Type cls) { } public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) { } public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { } public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) { } public virtual void EmitWriteLine(LocalBuilder localBuilder) { } public virtual void EmitWriteLine(FieldInfo fld) { } public virtual void EmitWriteLine(string value) { } public virtual void EndExceptionBlock() { } public virtual void EndScope() { } public virtual void MarkLabel(Label loc) { } public virtual void ThrowException([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type excType) { } public virtual void UsingNamespace(string usingNamespace) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace System.Reflection.Emit { public partial class ILGenerator { internal ILGenerator() { // Prevent generating a default constructor } public virtual int ILOffset { get { return default; } } public virtual void BeginCatchBlock(Type exceptionType) { } public virtual void BeginExceptFilterBlock() { } public virtual Label BeginExceptionBlock() { return default; } public virtual void BeginFaultBlock() { } public virtual void BeginFinallyBlock() { } public virtual void BeginScope() { } public virtual LocalBuilder DeclareLocal(Type localType) { return default; } public virtual LocalBuilder DeclareLocal(Type localType, bool pinned) { return default; } public virtual Label DefineLabel() { return default; } public virtual void Emit(OpCode opcode) { } public virtual void Emit(OpCode opcode, byte arg) { } public virtual void Emit(OpCode opcode, double arg) { } public virtual void Emit(OpCode opcode, short arg) { } public virtual void Emit(OpCode opcode, int arg) { } public virtual void Emit(OpCode opcode, long arg) { } public virtual void Emit(OpCode opcode, ConstructorInfo con) { } public virtual void Emit(OpCode opcode, Label label) { } public virtual void Emit(OpCode opcode, Label[] labels) { } public virtual void Emit(OpCode opcode, LocalBuilder local) { } public virtual void Emit(OpCode opcode, SignatureHelper signature) { } public virtual void Emit(OpCode opcode, FieldInfo field) { } public virtual void Emit(OpCode opcode, MethodInfo meth) { } [CLSCompliantAttribute(false)] public void Emit(OpCode opcode, sbyte arg) { } public virtual void Emit(OpCode opcode, float arg) { } public virtual void Emit(OpCode opcode, string str) { } public virtual void Emit(OpCode opcode, Type cls) { } public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) { } public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { } public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) { } public virtual void EmitWriteLine(LocalBuilder localBuilder) { } public virtual void EmitWriteLine(FieldInfo fld) { } public virtual void EmitWriteLine(string value) { } public virtual void EndExceptionBlock() { } public virtual void EndScope() { } public virtual void MarkLabel(Label loc) { } public virtual void ThrowException([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type excType) { } public virtual void UsingNamespace(string usingNamespace) { } } }
-1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/libraries/System.Globalization.Calendars/tests/ThaiBuddhistCalendar/ThaiBuddhistCalendarGetEra.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class ThaiBuddhistCalendarGetEra { private static readonly RandomDataGenerator s_randomDataGenerator = new RandomDataGenerator(); public static IEnumerable<object[]> GetEra_TestData() { yield return new object[] { DateTime.MinValue }; yield return new object[] { DateTime.MaxValue }; yield return new object[] { new DateTime(2000, 2, 29) }; yield return new object[] { s_randomDataGenerator.GetDateTime(-55) }; } [Theory] [MemberData(nameof(GetEra_TestData))] public void GetEra(DateTime time) { Assert.Equal(1, new ThaiBuddhistCalendar().GetEra(time)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class ThaiBuddhistCalendarGetEra { private static readonly RandomDataGenerator s_randomDataGenerator = new RandomDataGenerator(); public static IEnumerable<object[]> GetEra_TestData() { yield return new object[] { DateTime.MinValue }; yield return new object[] { DateTime.MaxValue }; yield return new object[] { new DateTime(2000, 2, 29) }; yield return new object[] { s_randomDataGenerator.GetDateTime(-55) }; } [Theory] [MemberData(nameof(GetEra_TestData))] public void GetEra(DateTime time) { Assert.Equal(1, new ThaiBuddhistCalendar().GetEra(time)); } } }
-1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/tests/JIT/Regression/CLR-x86-JIT/V1.2-M01/b00735/b00735.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; struct AA { static void f() { bool flag = false; if (flag) { while (flag) { while (flag) { } } } do { } while (flag); } static int Main() { f(); return 100; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; struct AA { static void f() { bool flag = false; if (flag) { while (flag) { while (flag) { } } } do { } while (flag); } static int Main() { f(); return 100; } }
-1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssembly/MethodBody0.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System; namespace ApplyUpdateReferencedAssembly { public class MethodBodyUnchangedAssembly { public static string StaticMethod1 () { Console.WriteLine("original"); return "ok"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System; namespace ApplyUpdateReferencedAssembly { public class MethodBodyUnchangedAssembly { public static string StaticMethod1 () { Console.WriteLine("original"); return "ok"; } } }
-1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/mono/sample/mbr/console/TestClass_v1.cs
using System; using System.Runtime.CompilerServices; public class TestClass { [MethodImpl(MethodImplOptions.NoInlining)] public static string TargetMethod () { string s = "NEW STRING"; Console.WriteLine (s); return s; } }
using System; using System.Runtime.CompilerServices; public class TestClass { [MethodImpl(MethodImplOptions.NoInlining)] public static string TargetMethod () { string s = "NEW STRING"; Console.WriteLine (s); return s; } }
-1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/tests/JIT/HardwareIntrinsics/X86/Sse2/ConvertToVector128Double.Vector128Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ConvertToVector128DoubleVector128Int32() { var test = new SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32 { private struct TestStruct { public Vector128<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32 testClass) { var result = Sse2.ConvertToVector128Double(_fld); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Double, Int32> _dataTable; static SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<Double, Int32>(_data, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ConvertToVector128Double( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ConvertToVector128Double( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ConvertToVector128Double( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Double), new Type[] { typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Double), new Type[] { typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Double), new Type[] { typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ConvertToVector128Double( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse2.ConvertToVector128Double(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ConvertToVector128Double(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ConvertToVector128Double(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32(); var result = Sse2.ConvertToVector128Double(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ConvertToVector128Double(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ConvertToVector128Double(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i % 2]) != BitConverter.DoubleToInt64Bits(firstOp[i % 2])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ConvertToVector128Double)}<Double>(Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ConvertToVector128DoubleVector128Int32() { var test = new SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32 { private struct TestStruct { public Vector128<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32 testClass) { var result = Sse2.ConvertToVector128Double(_fld); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Double, Int32> _dataTable; static SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<Double, Int32>(_data, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ConvertToVector128Double( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ConvertToVector128Double( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ConvertToVector128Double( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Double), new Type[] { typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Double), new Type[] { typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Double), new Type[] { typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ConvertToVector128Double( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse2.ConvertToVector128Double(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ConvertToVector128Double(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ConvertToVector128Double(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpConvTest__ConvertToVector128DoubleVector128Int32(); var result = Sse2.ConvertToVector128Double(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ConvertToVector128Double(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ConvertToVector128Double(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i % 2]) != BitConverter.DoubleToInt64Bits(firstOp[i % 2])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ConvertToVector128Double)}<Double>(Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/libraries/System.Diagnostics.EventLog/tests/System/Diagnostics/Reader/EventLogWatcherTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.Eventing.Reader; using System.Threading; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.Diagnostics.Tests { public class EventLogWatcherTests { private static AutoResetEvent signal; private const string message = "EventRecordWrittenTestMessage"; private int eventCounter; [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void Ctor_Default() { using (var eventLogWatcher = new EventLogWatcher("Application")) { Assert.False(eventLogWatcher.Enabled); eventLogWatcher.Enabled = true; Assert.True(eventLogWatcher.Enabled); eventLogWatcher.Enabled = false; Assert.False(eventLogWatcher.Enabled); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void Ctor_UsingBookmark() { EventBookmark bookmark = GetBookmark(); Assert.Throws<ArgumentNullException>(() => new EventLogWatcher(null, bookmark, true)); Assert.Throws<InvalidOperationException>(() => new EventLogWatcher(new EventLogQuery("Application", PathType.LogName, "*[System]") { ReverseDirection = true }, bookmark, true)); var query = new EventLogQuery("Application", PathType.LogName, "*[System]"); using (var eventLogWatcher = new EventLogWatcher(query, bookmark)) { Assert.False(eventLogWatcher.Enabled); eventLogWatcher.Enabled = true; Assert.True(eventLogWatcher.Enabled); eventLogWatcher.Enabled = false; Assert.False(eventLogWatcher.Enabled); } } private EventBookmark GetBookmark() { EventBookmark bookmark; EventLogQuery eventLogQuery = new EventLogQuery("Application", PathType.LogName, "*[System]"); using (var eventLog = new EventLogReader(eventLogQuery)) using (var record = eventLog.ReadEvent()) { Assert.NotNull(record); bookmark = record.Bookmark; Assert.NotNull(record.Bookmark); } return bookmark; } private void RaisingEvent(string log, string methodName, bool waitOnEvent = true) { signal = new AutoResetEvent(false); eventCounter = 0; string source = "Source_" + methodName; try { EventLog.CreateEventSource(source, log); var query = new EventLogQuery(log, PathType.LogName); using (EventLog eventLog = new EventLog()) using (EventLogWatcher eventLogWatcher = new EventLogWatcher(query)) { eventLog.Source = source; eventLogWatcher.EventRecordWritten += (s, e) => { eventCounter += 1; Assert.True(e.EventException != null || e.EventRecord != null); signal.Set(); }; Helpers.Retry(() => eventLogWatcher.Enabled = waitOnEvent); Helpers.Retry(() => eventLog.WriteEntry(message, EventLogEntryType.Information)); if (waitOnEvent) { Assert.True(signal.WaitOne(6000)); } } } finally { EventLog.DeleteEventSource(source); Helpers.RetrySilently(() => EventLog.Delete(log)); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Unreliable Win32 API call [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void RecordWrittenEventRaised() { RaisingEvent("EnableEvent", nameof(RecordWrittenEventRaised)); Assert.NotEqual(0, eventCounter); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Unreliable Win32 API call [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void RecordWrittenEventRaiseDisable() { RaisingEvent("DisableEvent", nameof(RecordWrittenEventRaiseDisable), waitOnEvent: false); Assert.Equal(0, eventCounter); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.Eventing.Reader; using System.Threading; using Xunit; using Microsoft.DotNet.XUnitExtensions; namespace System.Diagnostics.Tests { public class EventLogWatcherTests { private static AutoResetEvent signal; private const string message = "EventRecordWrittenTestMessage"; private int eventCounter; [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void Ctor_Default() { using (var eventLogWatcher = new EventLogWatcher("Application")) { Assert.False(eventLogWatcher.Enabled); eventLogWatcher.Enabled = true; Assert.True(eventLogWatcher.Enabled); eventLogWatcher.Enabled = false; Assert.False(eventLogWatcher.Enabled); } } [ConditionalFact(typeof(Helpers), nameof(Helpers.SupportsEventLogs))] public void Ctor_UsingBookmark() { EventBookmark bookmark = GetBookmark(); Assert.Throws<ArgumentNullException>(() => new EventLogWatcher(null, bookmark, true)); Assert.Throws<InvalidOperationException>(() => new EventLogWatcher(new EventLogQuery("Application", PathType.LogName, "*[System]") { ReverseDirection = true }, bookmark, true)); var query = new EventLogQuery("Application", PathType.LogName, "*[System]"); using (var eventLogWatcher = new EventLogWatcher(query, bookmark)) { Assert.False(eventLogWatcher.Enabled); eventLogWatcher.Enabled = true; Assert.True(eventLogWatcher.Enabled); eventLogWatcher.Enabled = false; Assert.False(eventLogWatcher.Enabled); } } private EventBookmark GetBookmark() { EventBookmark bookmark; EventLogQuery eventLogQuery = new EventLogQuery("Application", PathType.LogName, "*[System]"); using (var eventLog = new EventLogReader(eventLogQuery)) using (var record = eventLog.ReadEvent()) { Assert.NotNull(record); bookmark = record.Bookmark; Assert.NotNull(record.Bookmark); } return bookmark; } private void RaisingEvent(string log, string methodName, bool waitOnEvent = true) { signal = new AutoResetEvent(false); eventCounter = 0; string source = "Source_" + methodName; try { EventLog.CreateEventSource(source, log); var query = new EventLogQuery(log, PathType.LogName); using (EventLog eventLog = new EventLog()) using (EventLogWatcher eventLogWatcher = new EventLogWatcher(query)) { eventLog.Source = source; eventLogWatcher.EventRecordWritten += (s, e) => { eventCounter += 1; Assert.True(e.EventException != null || e.EventRecord != null); signal.Set(); }; Helpers.Retry(() => eventLogWatcher.Enabled = waitOnEvent); Helpers.Retry(() => eventLog.WriteEntry(message, EventLogEntryType.Information)); if (waitOnEvent) { Assert.True(signal.WaitOne(6000)); } } } finally { EventLog.DeleteEventSource(source); Helpers.RetrySilently(() => EventLog.Delete(log)); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Unreliable Win32 API call [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void RecordWrittenEventRaised() { RaisingEvent("EnableEvent", nameof(RecordWrittenEventRaised)); Assert.NotEqual(0, eventCounter); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Unreliable Win32 API call [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))] public void RecordWrittenEventRaiseDisable() { RaisingEvent("DisableEvent", nameof(RecordWrittenEventRaiseDisable), waitOnEvent: false); Assert.Equal(0, eventCounter); } } }
-1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/CustomAttributes/CustomAttributeHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.InteropServices; namespace System.Reflection.TypeLoading { internal static class CustomAttributeHelpers { /// <summary> /// Helper for creating a CustomAttributeNamedArgument. /// </summary> public static CustomAttributeNamedArgument ToCustomAttributeNamedArgument(this Type attributeType, string name, Type? argumentType, object? value) { MemberInfo[] members = attributeType.GetMember(name, MemberTypes.Field | MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance); if (members.Length == 0) throw new MissingMemberException(attributeType.FullName, name); if (members.Length > 1) throw new AmbiguousMatchException(); return new CustomAttributeNamedArgument(members[0], new CustomAttributeTypedArgument(argumentType!, value)); } /// <summary> /// Clones a cached CustomAttributeTypedArgument list into a freshly allocated one suitable for direct return through an api. /// </summary> public static ReadOnlyCollection<CustomAttributeTypedArgument> CloneForApiReturn(this IList<CustomAttributeTypedArgument> cats) { int count = cats.Count; CustomAttributeTypedArgument[] clones = new CustomAttributeTypedArgument[count]; for (int i = 0; i < count; i++) { clones[i] = cats[i].CloneForApiReturn(); } return clones.ToReadOnlyCollection(); } /// <summary> /// Clones a cached CustomAttributeNamedArgument list into a freshly allocated one suitable for direct return through an api. /// </summary> public static ReadOnlyCollection<CustomAttributeNamedArgument> CloneForApiReturn(this IList<CustomAttributeNamedArgument> cans) { int count = cans.Count; CustomAttributeNamedArgument[] clones = new CustomAttributeNamedArgument[count]; for (int i = 0; i < count; i++) { clones[i] = cans[i].CloneForApiReturn(); } return clones.ToReadOnlyCollection(); } /// <summary> /// Clones a cached CustomAttributeTypedArgument into a freshly allocated one suitable for direct return through an api. /// </summary> private static CustomAttributeTypedArgument CloneForApiReturn(this CustomAttributeTypedArgument cat) { Type type = cat.ArgumentType; object? value = cat.Value; if (!(value is IList<CustomAttributeTypedArgument> cats)) return cat; int count = cats.Count; CustomAttributeTypedArgument[] cads = new CustomAttributeTypedArgument[count]; for (int i = 0; i < count; i++) { cads[i] = cats[i].CloneForApiReturn(); } return new CustomAttributeTypedArgument(type, cads.ToReadOnlyCollection()); } /// <summary> /// Clones a cached CustomAttributeNamedArgument into a freshly allocated one suitable for direct return through an api. /// </summary> private static CustomAttributeNamedArgument CloneForApiReturn(this CustomAttributeNamedArgument can) { return new CustomAttributeNamedArgument(can.MemberInfo, can.TypedValue.CloneForApiReturn()); } /// <summary> /// Convert MarshalAsAttribute data into CustomAttributeData form. Returns null if the core assembly cannot be loaded or if the necessary /// types aren't in the core assembly. /// </summary> public static CustomAttributeData? TryComputeMarshalAsCustomAttributeData(Func<MarshalAsAttribute> marshalAsAttributeComputer, MetadataLoadContext loader) { // Make sure all the necessary framework types exist in this MetadataLoadContext's core assembly. If one doesn't, skip. CoreTypes ct = loader.GetAllFoundCoreTypes(); if (ct[CoreType.String] == null || ct[CoreType.Boolean] == null || ct[CoreType.UnmanagedType] == null || ct[CoreType.VarEnum] == null || ct[CoreType.Type] == null || ct[CoreType.Int16] == null || ct[CoreType.Int32] == null) return null; ConstructorInfo? ci = loader.TryGetMarshalAsCtor(); if (ci == null) return null; Func<CustomAttributeArguments> argumentsPromise = () => { // The expensive work goes in here. It will not execute unless someone invokes the Constructor/NamedArguments properties on // the CustomAttributeData. MarshalAsAttribute ma = marshalAsAttributeComputer(); Type attributeType = ci.DeclaringType!; CustomAttributeTypedArgument[] cats = { new CustomAttributeTypedArgument(ct[CoreType.UnmanagedType]!, (int)(ma.Value)) }; List<CustomAttributeNamedArgument> cans = new List<CustomAttributeNamedArgument>(); cans.AddRange(new CustomAttributeNamedArgument[] { attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.ArraySubType), ct[CoreType.UnmanagedType], (int)ma.ArraySubType), attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.IidParameterIndex), ct[CoreType.Int32], ma.IidParameterIndex), attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.SafeArraySubType), ct[CoreType.VarEnum], (int)ma.SafeArraySubType), attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.SizeConst), ct[CoreType.Int32], ma.SizeConst), attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.SizeParamIndex), ct[CoreType.Int16], ma.SizeParamIndex), }); if (ma.SafeArrayUserDefinedSubType != null) { cans.Add(attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.SafeArrayUserDefinedSubType), ct[CoreType.Type], ma.SafeArrayUserDefinedSubType)); } if (ma.MarshalType != null) { cans.Add(attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.MarshalType), ct[CoreType.String], ma.MarshalType)); } if (ma.MarshalTypeRef != null) { cans.Add(attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.MarshalTypeRef), ct[CoreType.Type], ma.MarshalTypeRef)); } if (ma.MarshalCookie != null) { cans.Add(attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.MarshalCookie), ct[CoreType.String], ma.MarshalCookie)); } return new CustomAttributeArguments(cats, cans); }; return new RoPseudoCustomAttributeData(ci, argumentsPromise); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.InteropServices; namespace System.Reflection.TypeLoading { internal static class CustomAttributeHelpers { /// <summary> /// Helper for creating a CustomAttributeNamedArgument. /// </summary> public static CustomAttributeNamedArgument ToCustomAttributeNamedArgument(this Type attributeType, string name, Type? argumentType, object? value) { MemberInfo[] members = attributeType.GetMember(name, MemberTypes.Field | MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance); if (members.Length == 0) throw new MissingMemberException(attributeType.FullName, name); if (members.Length > 1) throw new AmbiguousMatchException(); return new CustomAttributeNamedArgument(members[0], new CustomAttributeTypedArgument(argumentType!, value)); } /// <summary> /// Clones a cached CustomAttributeTypedArgument list into a freshly allocated one suitable for direct return through an api. /// </summary> public static ReadOnlyCollection<CustomAttributeTypedArgument> CloneForApiReturn(this IList<CustomAttributeTypedArgument> cats) { int count = cats.Count; CustomAttributeTypedArgument[] clones = new CustomAttributeTypedArgument[count]; for (int i = 0; i < count; i++) { clones[i] = cats[i].CloneForApiReturn(); } return clones.ToReadOnlyCollection(); } /// <summary> /// Clones a cached CustomAttributeNamedArgument list into a freshly allocated one suitable for direct return through an api. /// </summary> public static ReadOnlyCollection<CustomAttributeNamedArgument> CloneForApiReturn(this IList<CustomAttributeNamedArgument> cans) { int count = cans.Count; CustomAttributeNamedArgument[] clones = new CustomAttributeNamedArgument[count]; for (int i = 0; i < count; i++) { clones[i] = cans[i].CloneForApiReturn(); } return clones.ToReadOnlyCollection(); } /// <summary> /// Clones a cached CustomAttributeTypedArgument into a freshly allocated one suitable for direct return through an api. /// </summary> private static CustomAttributeTypedArgument CloneForApiReturn(this CustomAttributeTypedArgument cat) { Type type = cat.ArgumentType; object? value = cat.Value; if (!(value is IList<CustomAttributeTypedArgument> cats)) return cat; int count = cats.Count; CustomAttributeTypedArgument[] cads = new CustomAttributeTypedArgument[count]; for (int i = 0; i < count; i++) { cads[i] = cats[i].CloneForApiReturn(); } return new CustomAttributeTypedArgument(type, cads.ToReadOnlyCollection()); } /// <summary> /// Clones a cached CustomAttributeNamedArgument into a freshly allocated one suitable for direct return through an api. /// </summary> private static CustomAttributeNamedArgument CloneForApiReturn(this CustomAttributeNamedArgument can) { return new CustomAttributeNamedArgument(can.MemberInfo, can.TypedValue.CloneForApiReturn()); } /// <summary> /// Convert MarshalAsAttribute data into CustomAttributeData form. Returns null if the core assembly cannot be loaded or if the necessary /// types aren't in the core assembly. /// </summary> public static CustomAttributeData? TryComputeMarshalAsCustomAttributeData(Func<MarshalAsAttribute> marshalAsAttributeComputer, MetadataLoadContext loader) { // Make sure all the necessary framework types exist in this MetadataLoadContext's core assembly. If one doesn't, skip. CoreTypes ct = loader.GetAllFoundCoreTypes(); if (ct[CoreType.String] == null || ct[CoreType.Boolean] == null || ct[CoreType.UnmanagedType] == null || ct[CoreType.VarEnum] == null || ct[CoreType.Type] == null || ct[CoreType.Int16] == null || ct[CoreType.Int32] == null) return null; ConstructorInfo? ci = loader.TryGetMarshalAsCtor(); if (ci == null) return null; Func<CustomAttributeArguments> argumentsPromise = () => { // The expensive work goes in here. It will not execute unless someone invokes the Constructor/NamedArguments properties on // the CustomAttributeData. MarshalAsAttribute ma = marshalAsAttributeComputer(); Type attributeType = ci.DeclaringType!; CustomAttributeTypedArgument[] cats = { new CustomAttributeTypedArgument(ct[CoreType.UnmanagedType]!, (int)(ma.Value)) }; List<CustomAttributeNamedArgument> cans = new List<CustomAttributeNamedArgument>(); cans.AddRange(new CustomAttributeNamedArgument[] { attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.ArraySubType), ct[CoreType.UnmanagedType], (int)ma.ArraySubType), attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.IidParameterIndex), ct[CoreType.Int32], ma.IidParameterIndex), attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.SafeArraySubType), ct[CoreType.VarEnum], (int)ma.SafeArraySubType), attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.SizeConst), ct[CoreType.Int32], ma.SizeConst), attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.SizeParamIndex), ct[CoreType.Int16], ma.SizeParamIndex), }); if (ma.SafeArrayUserDefinedSubType != null) { cans.Add(attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.SafeArrayUserDefinedSubType), ct[CoreType.Type], ma.SafeArrayUserDefinedSubType)); } if (ma.MarshalType != null) { cans.Add(attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.MarshalType), ct[CoreType.String], ma.MarshalType)); } if (ma.MarshalTypeRef != null) { cans.Add(attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.MarshalTypeRef), ct[CoreType.Type], ma.MarshalTypeRef)); } if (ma.MarshalCookie != null) { cans.Add(attributeType.ToCustomAttributeNamedArgument(nameof(MarshalAsAttribute.MarshalCookie), ct[CoreType.String], ma.MarshalCookie)); } return new CustomAttributeArguments(cats, cans); }; return new RoPseudoCustomAttributeData(ci, argumentsPromise); } } }
-1
dotnet/runtime
66,169
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's
Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
eiriktsarpalis
2022-03-03T22:59:21Z
2022-03-04T16:48:09Z
11b79618faf1023ba4ea26b4037f495f81070d79
1d82d48e8c8150bfb549f095d6dafb599ff9f229
Make ReadStack.JsonTypeInfo derivation logic consistent with WriteStack's. Simplifies the derivation logic for the `ReadStack.JsonTypeInfo` property, making it consistent with `WriteStack.JsonTypeInfo`. Backported change from the polymorphism prototype.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ShiftLogicalRoundedSaturateScalar.Vector64.Int16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftLogicalRoundedSaturateScalar_Vector64_Int16() { var test = new SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16 testClass) { var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16(); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.ShiftLogicalRoundedSaturate(left[0], right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar)}<Int16>(Vector64<Int16>, Vector64<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftLogicalRoundedSaturateScalar_Vector64_Int16() { var test = new SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16 testClass) { var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16(); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__ShiftLogicalRoundedSaturateScalar_Vector64_Int16(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.ShiftLogicalRoundedSaturate(left[0], right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ShiftLogicalRoundedSaturateScalar)}<Int16>(Vector64<Int16>, Vector64<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1