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,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/eh/interactions/ehso.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="ehSO.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="ehSO.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/Interop/ICustomMarshaler/ConflictingNames/MultipleALCs.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> <GCStressIncompatible>true</GCStressIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="RunInALC.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="CMakeLists.txt" /> <ProjectReference Include="CustomMarshaler.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> <GCStressIncompatible>true</GCStressIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="RunInALC.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="CMakeLists.txt" /> <ProjectReference Include="CustomMarshaler.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/baseservices/threading/regressions/13662/13662-a.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <!-- Under heavy load, some of the TimerCallback functions don't complete before the test exits, preventing unload --> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="13662-a.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <!-- Under heavy load, some of the TimerCallback functions don't complete before the test exits, preventing unload --> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="13662-a.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/opt/Loops/SearchLoopTail.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="throwinfinally_50.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="throwinfinally_50.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/interface/box-unbox-interface018.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="box-unbox-interface018.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-unbox-interface018.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/fp/exgen/5w1d-03_cs_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>None</DebugType> <Optimize>True</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="5w1d-03.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>None</DebugType> <Optimize>True</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="5w1d-03.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/Interop/ObjectiveC/ObjectiveCMarshalAPI/ObjectiveCMarshalAPI.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <!-- Test unsupported outside of OSX --> <CLRTestTargetUnsupported Condition="'$(TargetsOSX)' != 'true'">true</CLRTestTargetUnsupported> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="Program.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="./CMakeLists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <!-- Test unsupported outside of OSX --> <CLRTestTargetUnsupported Condition="'$(TargetsOSX)' != 'true'">true</CLRTestTargetUnsupported> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="Program.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="./CMakeLists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/GC/Scenarios/GCSimulator/GCSimulator_80.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 3 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 5 -dp 0.4 -dw 0.4</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 3 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 5 -dp 0.4 -dw 0.4</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/cctor/xassem/xprecise1_cs_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> <RequiresProcessIsolation>true</RequiresProcessIsolation> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="xprecise1.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="testlib.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> <RequiresProcessIsolation>true</RequiresProcessIsolation> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="xprecise1.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="testlib.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/explicit/basic/refarg_o_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="refarg_o.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="refarg_o.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/divrem/div/r8div_cs_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="r8div.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="r8div.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Directed/cmov/Int_Xor_Op_cs_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="Int_Xor_Op.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="Int_Xor_Op.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Directed/coverage/oldtests/lclfldadd_cs_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="lclfldadd.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="lclfldadd.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // the simplest dead EH region that will not also have dead nonlocal exit .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly extern mscorlib { .ver 0:0:0:0 } .assembly extern eh_common{} .assembly 'severaldeadehregions' { .ver 0:0:0:0 } .imagebase 0x00400000 .subsystem 0x00000003 .file alignment 512 .corflags 0x00000001 .class public auto ansi Test_severaldeadehregions extends [mscorlib] System.Object { .method public static int32 main() { .entrypoint .maxstack 400 .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut ldloc.s expectedOut ldstr "In try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut ldstr "Done!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 .try { ldstr "In try" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) br skip .try { L: ldstr "In inner try, unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave done try_start: ldstr "In try" call void [System.Console]System.Console::WriteLine(string) leave done .try { ldstr "In try" call void [System.Console]System.Console::WriteLine(string) leave done } fault { ldstr "In fault" call void [System.Console]System.Console::WriteLine(string) endfault } filter_begin: pop ldstr "In filter" call void [System.Console]System.Console::WriteLine(string) ldc.i4.1 endfilter handler_begin: pop ldstr "In handler" call void [System.Console]System.Console::WriteLine(string) leave.s done handler_end: .try try_start to filter_begin filter filter_begin handler handler_begin to handler_end leave.s done } finally { endfinally .try { ldstr "In finally, unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) L2: br.s L2 } catch [mscorlib]System.Exception { leave.s L3 } L3: endfinally } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } skip: leave.s done } catch [mscorlib]System.Object { ldstr "In catch, unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } done: ldstr "Done!" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) ldloc.s testLog callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // the simplest dead EH region that will not also have dead nonlocal exit .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly extern mscorlib { .ver 0:0:0:0 } .assembly extern eh_common{} .assembly 'severaldeadehregions' { .ver 0:0:0:0 } .imagebase 0x00400000 .subsystem 0x00000003 .file alignment 512 .corflags 0x00000001 .class public auto ansi Test_severaldeadehregions extends [mscorlib] System.Object { .method public static int32 main() { .entrypoint .maxstack 400 .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut ldloc.s expectedOut ldstr "In try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut ldstr "Done!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 .try { ldstr "In try" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) br skip .try { L: ldstr "In inner try, unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave done try_start: ldstr "In try" call void [System.Console]System.Console::WriteLine(string) leave done .try { ldstr "In try" call void [System.Console]System.Console::WriteLine(string) leave done } fault { ldstr "In fault" call void [System.Console]System.Console::WriteLine(string) endfault } filter_begin: pop ldstr "In filter" call void [System.Console]System.Console::WriteLine(string) ldc.i4.1 endfilter handler_begin: pop ldstr "In handler" call void [System.Console]System.Console::WriteLine(string) leave.s done handler_end: .try try_start to filter_begin filter filter_begin handler handler_begin to handler_end leave.s done } finally { endfinally .try { ldstr "In finally, unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) L2: br.s L2 } catch [mscorlib]System.Exception { leave.s L3 } L3: endfinally } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } .try { ldstr "Unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } catch [mscorlib]System.Exception { leave.s done } skip: leave.s done } catch [mscorlib]System.Object { ldstr "In catch, unreached" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) leave.s done } done: ldstr "Done!" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) ldloc.s testLog callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./docs/design/coreclr/jit/images/ThreeClassesDevirtFull.JPG
JFIFExifMM*; JiV >Andy Ayers5757 2018:09:20 12:23:002018:09:20 12:23:00Andy Ayers http://ns.adobe.com/xap/1.0/<?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?> <x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:dc="http://purl.org/dc/elements/1.1/"/><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:xmp="http://ns.adobe.com/xap/1.0/"><xmp:CreateDate>2018-09-20T12:23:00.567</xmp:CreateDate></rdf:Description><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:creator><rdf:Seq xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:li>Andy Ayers</rdf:li></rdf:Seq> </dc:creator></rdf:Description></rdf:RDF></x:xmpmeta> <?xpacket end='w'?>C   '!%"."%()+,+ /3/*2'*+*C  ***************************************************" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJS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((((((((((((((((((((((((((((((((((((((((((((((((((((((((((u i$5(0xxϱ+ZQ|vbiIY!h"u}MМ Ud^ |CFmx?eEWFeaG~-X^A58{}N*ԱKr:sOU|\*7kxaXV_O0=SBѻWxcMq(1ПF^g{mZ%͌< 4jRJ2J˪kJqm?=r_]@z̃a5֛M=!q |ѯb=r={kC {Y`dUѲl~AkΖ\tz9mH w: E7"_ozE WKqF5/VQEhfQEQEQEQEQEF?붮'7{!oI2*}WvQE2B(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( <QRy7J0Q{cb7-Wr֒7Qqߑ+ܪ+X/d&A 55=J o:38[ QN%ԣ~b}{Hw<N>l'⟆WZdRwՏC?s/ c︊euמcVrq}.ƤϞOkT[^q/pϺ Ѭ ȡׄ-kVgʶGw3QH(((((vxCxD$d{|?gRjf hΤRjv4QEhdQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQE<=bV B'F7nGsk+ +*J~t#*ݚMɕ PRm/]*2rViU E7"_cTdAEUQEQEQEQEQED]@We\w7RFJG5}cc+c(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((M?l3_rWq\gXRRIRGt.#Ra-Kh|8? iH%l"^҄7((((((_hkJ쫉T$g+ѓH~:QVdQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQE|`%|#jT~ޜ%waBE]X=kƾx\9<jVWPXTߩ~QEAAEPEPEPEPEP\Oo~C޻j|_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WK3_ 8g09q8(VҴ]7>)l [MS".Ý*^Ex+|p_!xb3\g,2 %{PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEP
JFIFExifMM*; JiV >Andy Ayers5757 2018:09:20 12:23:002018:09:20 12:23:00Andy Ayers http://ns.adobe.com/xap/1.0/<?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?> <x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:dc="http://purl.org/dc/elements/1.1/"/><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:xmp="http://ns.adobe.com/xap/1.0/"><xmp:CreateDate>2018-09-20T12:23:00.567</xmp:CreateDate></rdf:Description><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:creator><rdf:Seq xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:li>Andy Ayers</rdf:li></rdf:Seq> </dc:creator></rdf:Description></rdf:RDF></x:xmpmeta> <?xpacket end='w'?>C   '!%"."%()+,+ /3/*2'*+*C  ***************************************************" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz ?F(((((((((((((((((((((((((((((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r:sOU|\*7kxaXV_O0=SBѻWxcMq(1ПF^g{mZ%͌< 4jRJ2J˪kJqm?=r_]@z̃a5֛M=!q |ѯb=r={kC {Y`dUѲl~AkΖ\tz9mH w: E7"_ozE WKqF5/VQEhfQEQEQEQEQEF?붮'7{!oI2*}WvQE2B(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( <QRy7J0Q{cb7-Wr֒7Qqߑ+ܪ+X/d&A 55=J o:38[ QN%ԣ~b}{Hw<N>l'⟆WZdRwՏC?s/ c︊euמcVrq}.ƤϞOkT[^q/pϺ Ѭ ȡׄ-kVgʶGw3QH(((((vxCxD$d{|?gRjf hΤRjv4QEhdQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQE<=bV B'F7nGsk+ +*J~t#*ݚMɕ PRm/]*2rViU E7"_cTdAEUQEQEQEQEQED]@We\w7RFJG5}cc+c(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((M?l3_rWq\gXRRIRGt.#Ra-Kh|8? iH%l"^҄7((((((_hkJ쫉T$g+ѓH~:QVdQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQEQE|`%|#jT~ޜ%waBE]X=kƾx\9<jVWPXTߩ~QEAAEPEPEPEPEP\Oo~C޻j|_#/G2~gmES$(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((+"~0ȡk_䮬=Lk GS4EjWPXTߩ>QEAAEPEPEP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EPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEP
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Regression/JitBlue/Runtime_36468/Runtime_36468.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType /> <Optimize>True</Optimize> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType /> <Optimize>True</Optimize> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** ** ** Purpose: implementation of the FormattableStringFactory ** class. ** ===========================================================*/ namespace System.Runtime.CompilerServices { /// <summary> /// A factory type used by compilers to create instances of the type <see cref="FormattableString"/>. /// </summary> public static class FormattableStringFactory { /// <summary> /// Create a <see cref="FormattableString"/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> public static FormattableString Create(string format!!, params object?[] arguments!!) => new ConcreteFormattableString(format, arguments); private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object?[] _arguments; internal ConcreteFormattableString(string format, object?[] arguments) { _format = format; _arguments = arguments; } public override string Format => _format; public override object?[] GetArguments() { return _arguments; } public override int ArgumentCount => _arguments.Length; public override object? GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider? formatProvider) { return string.Format(formatProvider, _format, _arguments); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================ ** ** ** ** Purpose: implementation of the FormattableStringFactory ** class. ** ===========================================================*/ namespace System.Runtime.CompilerServices { /// <summary> /// A factory type used by compilers to create instances of the type <see cref="FormattableString"/>. /// </summary> public static class FormattableStringFactory { /// <summary> /// Create a <see cref="FormattableString"/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> public static FormattableString Create(string format!!, params object?[] arguments!!) => new ConcreteFormattableString(format, arguments); private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object?[] _arguments; internal ConcreteFormattableString(string format, object?[] arguments) { _format = format; _arguments = arguments; } public override string Format => _format; public override object?[] GetArguments() { return _arguments; } public override int ArgumentCount => _arguments.Length; public override object? GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider? formatProvider) { return string.Format(formatProvider, _format, _arguments); } } } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/op_Multiply.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; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_MultiplySingle() { var test = new VectorBinaryOpTest__op_MultiplySingle(); // 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__op_MultiplySingle { 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(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); 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<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, 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<Single> _fld1; public Vector64<Single> _fld2; 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<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_MultiplySingle testClass) { var result = _fld1 * _fld2; 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<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector64<Single> _clsVar1; private static Vector64<Single> _clsVar2; private Vector64<Single> _fld1; private Vector64<Single> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_MultiplySingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public VectorBinaryOpTest__op_MultiplySingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<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(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) * Unsafe.Read<Vector64<Single>>(_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(Vector64<Single>).GetMethod("op_Multiply", new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _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<Vector64<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr); var result = op1 * op2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__op_MultiplySingle(); var result = 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 = _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 = 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(Vector64<Single> op1, Vector64<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; 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.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (float)(left[0] * right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (float)(left[i] * right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_Multiply<Single>(Vector64<Single>, Vector64<Single>): {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 op_MultiplySingle() { var test = new VectorBinaryOpTest__op_MultiplySingle(); // 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__op_MultiplySingle { 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(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); 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<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, 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<Single> _fld1; public Vector64<Single> _fld2; 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<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_MultiplySingle testClass) { var result = _fld1 * _fld2; 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<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector64<Single> _clsVar1; private static Vector64<Single> _clsVar2; private Vector64<Single> _fld1; private Vector64<Single> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_MultiplySingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public VectorBinaryOpTest__op_MultiplySingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<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(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) * Unsafe.Read<Vector64<Single>>(_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(Vector64<Single>).GetMethod("op_Multiply", new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _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<Vector64<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr); var result = op1 * op2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__op_MultiplySingle(); var result = 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 = _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 = 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(Vector64<Single> op1, Vector64<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; 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.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (float)(left[0] * right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (float)(left[i] * right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_Multiply<Single>(Vector64<Single>, Vector64<Single>): {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,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/opt/OSR/osrcontainstry.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; // OSR method contains try class OSRContainsTry { [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int I(ref int p) => p; [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int F(int from, int to) { int result = 0; for (int i = from; i < to; i++) { try { result = I(ref result) + i; } catch (Exception e) { } } return result; } public static int Main() { Console.WriteLine($"starting sum"); int result = F(0, 1_000_000); Console.WriteLine($"done, sum is {result}"); return result == 1783293664 ? 100 : -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.Runtime.CompilerServices; // OSR method contains try class OSRContainsTry { [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int I(ref int p) => p; [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int F(int from, int to) { int result = 0; for (int i = from; i < to; i++) { try { result = I(ref result) + i; } catch (Exception e) { } } return result; } public static int Main() { Console.WriteLine($"starting sum"); int result = F(0, 1_000_000); Console.WriteLine($"done, sum is {result}"); return result == 1783293664 ? 100 : -1; } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/HardwareIntrinsics/X86/Bmi1.X64/BitFieldExtract.UInt64.3Op.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 BitFieldExtractUInt643Op() { var test = new ScalarTernOpTest__BitFieldExtractUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.ReadUnaligned test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.ReadUnaligned test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.ReadUnaligned 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(); } 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 ScalarTernOpTest__BitFieldExtractUInt64 { private struct TestStruct { public UInt64 _fld1; public Byte _fld2; public Byte _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld1 = 0x1E00000000000000; testStruct._fld2 = 57; testStruct._fld3 = 4; return testStruct; } public void RunStructFldScenario(ScalarTernOpTest__BitFieldExtractUInt64 testClass) { var result = Bmi1.X64.BitFieldExtract(_fld1, _fld2, _fld3); testClass.ValidateResult(_fld1, _fld2, _fld3, result); } } private static UInt64 _data1; private static Byte _data2; private static Byte _data3; private static UInt64 _clsVar1; private static Byte _clsVar2; private static Byte _clsVar3; private UInt64 _fld1; private Byte _fld2; private Byte _fld3; static ScalarTernOpTest__BitFieldExtractUInt64() { _clsVar1 = 0x1E00000000000000; _clsVar2 = 57; _clsVar3 = 4; } public ScalarTernOpTest__BitFieldExtractUInt64() { Succeeded = true; _fld1 = 0x1E00000000000000; _fld2 = 57; _fld3 = 4; _data1 = 0x1E00000000000000; _data2 = 57; _data3 = 4; } public bool IsSupported => Bmi1.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Bmi1.X64.BitFieldExtract( Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)), Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data2)), Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data3)) ); ValidateResult(_data1, _data2, _data3, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.BitFieldExtract), new Type[] { typeof(UInt64), typeof(Byte), typeof(Byte) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)), Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data2)), Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data3)) }); ValidateResult(_data1, _data2, _data3, (UInt64)result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Bmi1.X64.BitFieldExtract( _clsVar1, _clsVar2, _clsVar3 ); ValidateResult(_clsVar1, _clsVar2, _clsVar3, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data1 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)); var data2 = Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data2)); var data3 = Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data3)); var result = Bmi1.X64.BitFieldExtract(data1, data2, data3); ValidateResult(data1, data2, data3, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarTernOpTest__BitFieldExtractUInt64(); var result = Bmi1.X64.BitFieldExtract(test._fld1, test._fld2, test._fld3); ValidateResult(test._fld1, test._fld2, test._fld3, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Bmi1.X64.BitFieldExtract(_fld1, _fld2, _fld3); ValidateResult(_fld1, _fld2, _fld3, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Bmi1.X64.BitFieldExtract(test._fld1, test._fld2, test._fld3); ValidateResult(test._fld1, test._fld2, test._fld3, result); } 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(UInt64 op1, Byte op2, Byte op3, UInt64 result, [CallerMemberName] string method = "") { var isUnexpectedResult = false; ulong expectedResult = 15; isUnexpectedResult = (expectedResult != result); if (isUnexpectedResult) { TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.BitFieldExtract)}<UInt64>(UInt64, Byte, Byte): BitFieldExtract failed:"); TestLibrary.TestFramework.LogInformation($" op1: {op1}"); TestLibrary.TestFramework.LogInformation($" op2: {op2}"); TestLibrary.TestFramework.LogInformation($" op3: {op3}"); 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; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void BitFieldExtractUInt643Op() { var test = new ScalarTernOpTest__BitFieldExtractUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.ReadUnaligned test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.ReadUnaligned test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.ReadUnaligned 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(); } 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 ScalarTernOpTest__BitFieldExtractUInt64 { private struct TestStruct { public UInt64 _fld1; public Byte _fld2; public Byte _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld1 = 0x1E00000000000000; testStruct._fld2 = 57; testStruct._fld3 = 4; return testStruct; } public void RunStructFldScenario(ScalarTernOpTest__BitFieldExtractUInt64 testClass) { var result = Bmi1.X64.BitFieldExtract(_fld1, _fld2, _fld3); testClass.ValidateResult(_fld1, _fld2, _fld3, result); } } private static UInt64 _data1; private static Byte _data2; private static Byte _data3; private static UInt64 _clsVar1; private static Byte _clsVar2; private static Byte _clsVar3; private UInt64 _fld1; private Byte _fld2; private Byte _fld3; static ScalarTernOpTest__BitFieldExtractUInt64() { _clsVar1 = 0x1E00000000000000; _clsVar2 = 57; _clsVar3 = 4; } public ScalarTernOpTest__BitFieldExtractUInt64() { Succeeded = true; _fld1 = 0x1E00000000000000; _fld2 = 57; _fld3 = 4; _data1 = 0x1E00000000000000; _data2 = 57; _data3 = 4; } public bool IsSupported => Bmi1.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Bmi1.X64.BitFieldExtract( Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)), Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data2)), Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data3)) ); ValidateResult(_data1, _data2, _data3, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.BitFieldExtract), new Type[] { typeof(UInt64), typeof(Byte), typeof(Byte) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)), Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data2)), Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data3)) }); ValidateResult(_data1, _data2, _data3, (UInt64)result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Bmi1.X64.BitFieldExtract( _clsVar1, _clsVar2, _clsVar3 ); ValidateResult(_clsVar1, _clsVar2, _clsVar3, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data1 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)); var data2 = Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data2)); var data3 = Unsafe.ReadUnaligned<Byte>(ref Unsafe.As<Byte, byte>(ref _data3)); var result = Bmi1.X64.BitFieldExtract(data1, data2, data3); ValidateResult(data1, data2, data3, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarTernOpTest__BitFieldExtractUInt64(); var result = Bmi1.X64.BitFieldExtract(test._fld1, test._fld2, test._fld3); ValidateResult(test._fld1, test._fld2, test._fld3, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Bmi1.X64.BitFieldExtract(_fld1, _fld2, _fld3); ValidateResult(_fld1, _fld2, _fld3, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Bmi1.X64.BitFieldExtract(test._fld1, test._fld2, test._fld3); ValidateResult(test._fld1, test._fld2, test._fld3, result); } 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(UInt64 op1, Byte op2, Byte op3, UInt64 result, [CallerMemberName] string method = "") { var isUnexpectedResult = false; ulong expectedResult = 15; isUnexpectedResult = (expectedResult != result); if (isUnexpectedResult) { TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.BitFieldExtract)}<UInt64>(UInt64, Byte, Byte): BitFieldExtract failed:"); TestLibrary.TestFramework.LogInformation($" op1: {op1}"); TestLibrary.TestFramework.LogInformation($" op2: {op2}"); TestLibrary.TestFramework.LogInformation($" op3: {op3}"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/coreclr/vm/dynamicmethod.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // #ifndef _DYNAMICMETHOD_H_ #define _DYNAMICMETHOD_H_ #include "jitinterface.h" #include "methodtable.h" #include <daccess.h> //--------------------------------------------------------------------------------------- // // This links together a set of news and release in one object. // The idea is to have a predefined size allocated up front and used by different calls to new. // All the allocation will be released at the same time releaseing an instance of this class // Here is how the object is laid out // | ptr_to_next_chunk | size_left_in_chunk | data | ... | data // This is not a particularly efficient allocator but it works well for a small number of allocation // needed while jitting a method // class ChunkAllocator { private: #define CHUNK_SIZE 64 BYTE *m_pData; public: ChunkAllocator() : m_pData(NULL) {} ~ChunkAllocator(); void* New(size_t size); void Delete(); }; //--------------------------------------------------------------------------------------- // class DynamicResolver { public: // Keep in sync with dynamicIlGenerator.cs enum SecurityControlFlags { Default = 0, SkipVisibilityChecks = 0x1, RestrictedSkipVisibilityChecks = 0x2, HasCreationContext = 0x4, CanSkipCSEvaluation = 0x8, }; // set up and clean up for jitting virtual void FreeCompileTimeState() = 0; virtual void GetJitContext(SecurityControlFlags * securityControlFlags, TypeHandle *typeOwner) = 0; virtual ChunkAllocator* GetJitMetaHeap() = 0; // // code info data virtual BYTE * GetCodeInfo( unsigned * pCodeSize, unsigned * pStackSize, CorInfoOptions * pOptions, unsigned * pEHSize) = 0; virtual SigPointer GetLocalSig() = 0; #ifdef FEATURE_PGO virtual PgoManager* volatile* GetDynamicPgoManagerPointer() { return NULL; } PgoManager* GetDynamicPgoManager() { return NULL; } #endif // // jit interface api virtual OBJECTHANDLE ConstructStringLiteral(mdToken metaTok) = 0; virtual BOOL IsValidStringRef(mdToken metaTok) = 0; virtual int GetStringLiteralLength(mdToken metaTok) = 0; virtual void ResolveToken(mdToken token, TypeHandle * pTH, MethodDesc ** ppMD, FieldDesc ** ppFD) = 0; virtual SigPointer ResolveSignature(mdToken token) = 0; virtual SigPointer ResolveSignatureForVarArg(mdToken token) = 0; virtual void GetEHInfo(unsigned EHnumber, CORINFO_EH_CLAUSE* clause) = 0; virtual MethodDesc * GetDynamicMethod() = 0; }; // class DynamicResolver //--------------------------------------------------------------------------------------- // class StringLiteralEntry; //--------------------------------------------------------------------------------------- // struct DynamicStringLiteral { DynamicStringLiteral * m_pNext; StringLiteralEntry * m_pEntry; }; //--------------------------------------------------------------------------------------- // // LCGMethodResolver // // a jit resolver for managed dynamic methods // class LCGMethodResolver : public DynamicResolver { friend class DynamicMethodDesc; friend class DynamicMethodTable; // review this to see whether the EEJitManageris the only thing to worry about friend class ExecutionManager; friend class EEJitManager; friend class HostCodeHeap; friend struct ExecutionManager::JumpStubCache; public: void Destroy(); void FreeCompileTimeState(); void GetJitContext(SecurityControlFlags * securityControlFlags, TypeHandle * typeOwner); ChunkAllocator* GetJitMetaHeap(); BYTE* GetCodeInfo(unsigned *pCodeSize, unsigned *pStackSize, CorInfoOptions *pOptions, unsigned* pEHSize); SigPointer GetLocalSig(); OBJECTHANDLE ConstructStringLiteral(mdToken metaTok); BOOL IsValidStringRef(mdToken metaTok); int GetStringLiteralLength(mdToken metaTok); void ResolveToken(mdToken token, TypeHandle * pTH, MethodDesc ** ppMD, FieldDesc ** ppFD); SigPointer ResolveSignature(mdToken token); SigPointer ResolveSignatureForVarArg(mdToken token); void GetEHInfo(unsigned EHnumber, CORINFO_EH_CLAUSE* clause); MethodDesc* GetDynamicMethod() { LIMITED_METHOD_CONTRACT; return m_pDynamicMethod; } OBJECTREF GetManagedResolver(); void SetManagedResolver(OBJECTHANDLE obj) { LIMITED_METHOD_CONTRACT; m_managedResolver = obj; } void * GetRecordCodePointer() { LIMITED_METHOD_CONTRACT; return m_recordCodePointer; } STRINGREF GetStringLiteral(mdToken token); STRINGREF * GetOrInternString(STRINGREF *pString); void AddToUsedIndCellList(BYTE * indcell); #ifdef FEATURE_PGO PgoManager* volatile* GetDynamicPgoManagerPointer() { return &m_pgoManager; } PgoManager* GetDynamicPgoManager() { return m_pgoManager; } #endif private: void RecycleIndCells(); void Reset(); struct IndCellList { BYTE * indcell; IndCellList * pNext; }; DynamicMethodDesc* m_pDynamicMethod; OBJECTHANDLE m_managedResolver; BYTE *m_Code; DWORD m_CodeSize; SigPointer m_LocalSig; unsigned short m_StackSize; CorInfoOptions m_Options; unsigned m_EHSize; DynamicMethodTable *m_DynamicMethodTable; DynamicMethodDesc *m_next; void *m_recordCodePointer; ChunkAllocator m_jitMetaHeap; ChunkAllocator m_jitTempData; DynamicStringLiteral* m_DynamicStringLiterals; IndCellList * m_UsedIndCellList; // list to keep track of all the indirection cells used by the jitted code ExecutionManager::JumpStubCache * m_pJumpStubCache; #ifdef FEATURE_PGO Volatile<PgoManager*> m_pgoManager; #endif // FEATURE_PGO }; // class LCGMethodResolver //--------------------------------------------------------------------------------------- // // a DynamicMethodTable is used by the light code generation to lazily allocate methods. // The methods in this MethodTable are not known up front and their signature is defined // at runtime // class DynamicMethodTable { public: #ifndef DACCESS_COMPILE static void CreateDynamicMethodTable(DynamicMethodTable **ppLocation, Module *pModule, AppDomain *pDomain); #endif private: CrstExplicitInit m_Crst; DynamicMethodDesc *m_DynamicMethodList; MethodTable *m_pMethodTable; Module *m_Module; AppDomain *m_pDomain; DynamicMethodTable() {WRAPPER_NO_CONTRACT;} class LockHolder : public CrstHolder { public: LockHolder(DynamicMethodTable *pDynMT) : CrstHolder(&pDynMT->m_Crst) { WRAPPER_NO_CONTRACT; } }; friend class LockHolder; #ifndef DACCESS_COMPILE void MakeMethodTable(AllocMemTracker *pamTracker); void AddMethodsToList(); public: void Destroy(); DynamicMethodDesc* GetDynamicMethod(BYTE *psig, DWORD sigSize, PTR_CUTF8 name); void LinkMethod(DynamicMethodDesc *pMethod); #endif #ifdef _DEBUG public: DWORD m_Used; #endif }; // class DynamicMethodTable //--------------------------------------------------------------------------------------- // #define HOST_CODEHEAP_SIZE_ALIGN 64 //--------------------------------------------------------------------------------------- // // Implementation of the CodeHeap for DynamicMethods. // This CodeHeap uses the host interface VirtualAlloc/Free and allows // for reclamation of generated code // (Check the base class - CodeHeap in codeman.h - for comments on the functions) // class HostCodeHeap : CodeHeap { #ifdef DACCESS_COMPILE friend class ClrDataAccess; #else friend class EEJitManager; #endif VPTR_VTABLE_CLASS(HostCodeHeap, CodeHeap) private: // pointer back to jit manager info PTR_HeapList m_pHeapList; PTR_EEJitManager m_pJitManager; // basic allocation data PTR_BYTE m_pBaseAddr; PTR_BYTE m_pLastAvailableCommittedAddr; size_t m_TotalBytesAvailable; size_t m_ApproximateLargestBlock; // Heap ref count DWORD m_AllocationCount; // data to track free list and pointers into this heap // - on an used block this struct has got a pointer back to the CodeHeap, size and start of aligned allocation // - on an unused block (free block) this tracks the size of the block and the pointer to the next non contiguos free block struct TrackAllocation { union { HostCodeHeap *pHeap; TrackAllocation *pNext; }; size_t size; }; TrackAllocation *m_pFreeList; // used for cleanup. Keep track of the next potential heap to release. Normally NULL HostCodeHeap *m_pNextHeapToRelease; LoaderAllocator*m_pAllocator; public: static HeapList* CreateCodeHeap(CodeHeapRequestInfo *pInfo, EEJitManager *pJitManager); private: HostCodeHeap(EEJitManager *pJitManager); HeapList* InitializeHeapList(CodeHeapRequestInfo *pInfo); TrackAllocation* AllocFromFreeList(size_t header, size_t size, DWORD alignment, size_t reserveForJumpStubs); void AddToFreeList(TrackAllocation *pBlockToInsert, TrackAllocation *pBlockToInsertRW); TrackAllocation* AllocMemory_NoThrow(size_t header, size_t size, DWORD alignment, size_t reserveForJumpStubs); public: // Space for header is reserved immediately before. It is not included in size. virtual void* AllocMemForCode_NoThrow(size_t header, size_t size, DWORD alignment, size_t reserveForJumpStubs) DAC_EMPTY_RET(NULL); virtual ~HostCodeHeap() DAC_EMPTY(); LoaderAllocator* GetAllocator() { return m_pAllocator; } #ifdef DACCESS_COMPILE virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags); #endif static TrackAllocation * GetTrackAllocation(TADDR codeStart); static HostCodeHeap* GetCodeHeap(TADDR codeStart); void DestroyCodeHeap(); protected: friend class DynamicMethodDesc; friend class LCGMethodResolver; void FreeMemForCode(void * codeStart); #if defined(FEATURE_JIT_PITCHING) public: PTR_EEJitManager GetJitManager() { return m_pJitManager; } #endif }; // class HostCodeHeap //--------------------------------------------------------------------------------------- // #include "ilstubresolver.h" inline MethodDesc* GetMethod(CORINFO_METHOD_HANDLE methodHandle) { LIMITED_METHOD_CONTRACT; return (MethodDesc*) methodHandle; } #ifndef DACCESS_COMPILE #define CORINFO_MODULE_HANDLE_TYPE_MASK 1 enum CORINFO_MODULE_HANDLE_TYPES { CORINFO_NORMAL_MODULE = 0, CORINFO_DYNAMIC_MODULE, }; inline bool IsDynamicScope(CORINFO_MODULE_HANDLE module) { LIMITED_METHOD_CONTRACT; return (CORINFO_DYNAMIC_MODULE == (((size_t)module) & CORINFO_MODULE_HANDLE_TYPE_MASK)); } inline CORINFO_MODULE_HANDLE MakeDynamicScope(DynamicResolver* pResolver) { LIMITED_METHOD_CONTRACT; CONSISTENCY_CHECK(0 == (((size_t)pResolver) & CORINFO_MODULE_HANDLE_TYPE_MASK)); return (CORINFO_MODULE_HANDLE)(((size_t)pResolver) | CORINFO_DYNAMIC_MODULE); } inline DynamicResolver* GetDynamicResolver(CORINFO_MODULE_HANDLE module) { LIMITED_METHOD_CONTRACT; CONSISTENCY_CHECK(IsDynamicScope(module)); return (DynamicResolver*)(((size_t)module) & ~((size_t)CORINFO_MODULE_HANDLE_TYPE_MASK)); } inline Module* GetModule(CORINFO_MODULE_HANDLE scope) { WRAPPER_NO_CONTRACT; if (IsDynamicScope(scope)) { return GetDynamicResolver(scope)->GetDynamicMethod()->GetModule(); } else { return((Module*)scope); } } inline CORINFO_MODULE_HANDLE GetScopeHandle(Module* module) { LIMITED_METHOD_CONTRACT; return(CORINFO_MODULE_HANDLE(module)); } inline bool IsDynamicMethodHandle(CORINFO_METHOD_HANDLE method) { LIMITED_METHOD_CONTRACT; CONSISTENCY_CHECK(NULL != GetMethod(method)); return GetMethod(method)->IsDynamicMethod(); } #endif // DACCESS_COMPILE #endif // _DYNAMICMETHOD_H_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // #ifndef _DYNAMICMETHOD_H_ #define _DYNAMICMETHOD_H_ #include "jitinterface.h" #include "methodtable.h" #include <daccess.h> //--------------------------------------------------------------------------------------- // // This links together a set of news and release in one object. // The idea is to have a predefined size allocated up front and used by different calls to new. // All the allocation will be released at the same time releaseing an instance of this class // Here is how the object is laid out // | ptr_to_next_chunk | size_left_in_chunk | data | ... | data // This is not a particularly efficient allocator but it works well for a small number of allocation // needed while jitting a method // class ChunkAllocator { private: #define CHUNK_SIZE 64 BYTE *m_pData; public: ChunkAllocator() : m_pData(NULL) {} ~ChunkAllocator(); void* New(size_t size); void Delete(); }; //--------------------------------------------------------------------------------------- // class DynamicResolver { public: // Keep in sync with dynamicIlGenerator.cs enum SecurityControlFlags { Default = 0, SkipVisibilityChecks = 0x1, RestrictedSkipVisibilityChecks = 0x2, HasCreationContext = 0x4, CanSkipCSEvaluation = 0x8, }; // set up and clean up for jitting virtual void FreeCompileTimeState() = 0; virtual void GetJitContext(SecurityControlFlags * securityControlFlags, TypeHandle *typeOwner) = 0; virtual ChunkAllocator* GetJitMetaHeap() = 0; // // code info data virtual BYTE * GetCodeInfo( unsigned * pCodeSize, unsigned * pStackSize, CorInfoOptions * pOptions, unsigned * pEHSize) = 0; virtual SigPointer GetLocalSig() = 0; #ifdef FEATURE_PGO virtual PgoManager* volatile* GetDynamicPgoManagerPointer() { return NULL; } PgoManager* GetDynamicPgoManager() { return NULL; } #endif // // jit interface api virtual OBJECTHANDLE ConstructStringLiteral(mdToken metaTok) = 0; virtual BOOL IsValidStringRef(mdToken metaTok) = 0; virtual int GetStringLiteralLength(mdToken metaTok) = 0; virtual void ResolveToken(mdToken token, TypeHandle * pTH, MethodDesc ** ppMD, FieldDesc ** ppFD) = 0; virtual SigPointer ResolveSignature(mdToken token) = 0; virtual SigPointer ResolveSignatureForVarArg(mdToken token) = 0; virtual void GetEHInfo(unsigned EHnumber, CORINFO_EH_CLAUSE* clause) = 0; virtual MethodDesc * GetDynamicMethod() = 0; }; // class DynamicResolver //--------------------------------------------------------------------------------------- // class StringLiteralEntry; //--------------------------------------------------------------------------------------- // struct DynamicStringLiteral { DynamicStringLiteral * m_pNext; StringLiteralEntry * m_pEntry; }; //--------------------------------------------------------------------------------------- // // LCGMethodResolver // // a jit resolver for managed dynamic methods // class LCGMethodResolver : public DynamicResolver { friend class DynamicMethodDesc; friend class DynamicMethodTable; // review this to see whether the EEJitManageris the only thing to worry about friend class ExecutionManager; friend class EEJitManager; friend class HostCodeHeap; friend struct ExecutionManager::JumpStubCache; public: void Destroy(); void FreeCompileTimeState(); void GetJitContext(SecurityControlFlags * securityControlFlags, TypeHandle * typeOwner); ChunkAllocator* GetJitMetaHeap(); BYTE* GetCodeInfo(unsigned *pCodeSize, unsigned *pStackSize, CorInfoOptions *pOptions, unsigned* pEHSize); SigPointer GetLocalSig(); OBJECTHANDLE ConstructStringLiteral(mdToken metaTok); BOOL IsValidStringRef(mdToken metaTok); int GetStringLiteralLength(mdToken metaTok); void ResolveToken(mdToken token, TypeHandle * pTH, MethodDesc ** ppMD, FieldDesc ** ppFD); SigPointer ResolveSignature(mdToken token); SigPointer ResolveSignatureForVarArg(mdToken token); void GetEHInfo(unsigned EHnumber, CORINFO_EH_CLAUSE* clause); MethodDesc* GetDynamicMethod() { LIMITED_METHOD_CONTRACT; return m_pDynamicMethod; } OBJECTREF GetManagedResolver(); void SetManagedResolver(OBJECTHANDLE obj) { LIMITED_METHOD_CONTRACT; m_managedResolver = obj; } void * GetRecordCodePointer() { LIMITED_METHOD_CONTRACT; return m_recordCodePointer; } STRINGREF GetStringLiteral(mdToken token); STRINGREF * GetOrInternString(STRINGREF *pString); void AddToUsedIndCellList(BYTE * indcell); #ifdef FEATURE_PGO PgoManager* volatile* GetDynamicPgoManagerPointer() { return &m_pgoManager; } PgoManager* GetDynamicPgoManager() { return m_pgoManager; } #endif private: void RecycleIndCells(); void Reset(); struct IndCellList { BYTE * indcell; IndCellList * pNext; }; DynamicMethodDesc* m_pDynamicMethod; OBJECTHANDLE m_managedResolver; BYTE *m_Code; DWORD m_CodeSize; SigPointer m_LocalSig; unsigned short m_StackSize; CorInfoOptions m_Options; unsigned m_EHSize; DynamicMethodTable *m_DynamicMethodTable; DynamicMethodDesc *m_next; void *m_recordCodePointer; ChunkAllocator m_jitMetaHeap; ChunkAllocator m_jitTempData; DynamicStringLiteral* m_DynamicStringLiterals; IndCellList * m_UsedIndCellList; // list to keep track of all the indirection cells used by the jitted code ExecutionManager::JumpStubCache * m_pJumpStubCache; #ifdef FEATURE_PGO Volatile<PgoManager*> m_pgoManager; #endif // FEATURE_PGO }; // class LCGMethodResolver //--------------------------------------------------------------------------------------- // // a DynamicMethodTable is used by the light code generation to lazily allocate methods. // The methods in this MethodTable are not known up front and their signature is defined // at runtime // class DynamicMethodTable { public: #ifndef DACCESS_COMPILE static void CreateDynamicMethodTable(DynamicMethodTable **ppLocation, Module *pModule, AppDomain *pDomain); #endif private: CrstExplicitInit m_Crst; DynamicMethodDesc *m_DynamicMethodList; MethodTable *m_pMethodTable; Module *m_Module; AppDomain *m_pDomain; DynamicMethodTable() {WRAPPER_NO_CONTRACT;} class LockHolder : public CrstHolder { public: LockHolder(DynamicMethodTable *pDynMT) : CrstHolder(&pDynMT->m_Crst) { WRAPPER_NO_CONTRACT; } }; friend class LockHolder; #ifndef DACCESS_COMPILE void MakeMethodTable(AllocMemTracker *pamTracker); void AddMethodsToList(); public: void Destroy(); DynamicMethodDesc* GetDynamicMethod(BYTE *psig, DWORD sigSize, PTR_CUTF8 name); void LinkMethod(DynamicMethodDesc *pMethod); #endif #ifdef _DEBUG public: DWORD m_Used; #endif }; // class DynamicMethodTable //--------------------------------------------------------------------------------------- // #define HOST_CODEHEAP_SIZE_ALIGN 64 //--------------------------------------------------------------------------------------- // // Implementation of the CodeHeap for DynamicMethods. // This CodeHeap uses the host interface VirtualAlloc/Free and allows // for reclamation of generated code // (Check the base class - CodeHeap in codeman.h - for comments on the functions) // class HostCodeHeap : CodeHeap { #ifdef DACCESS_COMPILE friend class ClrDataAccess; #else friend class EEJitManager; #endif VPTR_VTABLE_CLASS(HostCodeHeap, CodeHeap) private: // pointer back to jit manager info PTR_HeapList m_pHeapList; PTR_EEJitManager m_pJitManager; // basic allocation data PTR_BYTE m_pBaseAddr; PTR_BYTE m_pLastAvailableCommittedAddr; size_t m_TotalBytesAvailable; size_t m_ApproximateLargestBlock; // Heap ref count DWORD m_AllocationCount; // data to track free list and pointers into this heap // - on an used block this struct has got a pointer back to the CodeHeap, size and start of aligned allocation // - on an unused block (free block) this tracks the size of the block and the pointer to the next non contiguos free block struct TrackAllocation { union { HostCodeHeap *pHeap; TrackAllocation *pNext; }; size_t size; }; TrackAllocation *m_pFreeList; // used for cleanup. Keep track of the next potential heap to release. Normally NULL HostCodeHeap *m_pNextHeapToRelease; LoaderAllocator*m_pAllocator; public: static HeapList* CreateCodeHeap(CodeHeapRequestInfo *pInfo, EEJitManager *pJitManager); private: HostCodeHeap(EEJitManager *pJitManager); HeapList* InitializeHeapList(CodeHeapRequestInfo *pInfo); TrackAllocation* AllocFromFreeList(size_t header, size_t size, DWORD alignment, size_t reserveForJumpStubs); void AddToFreeList(TrackAllocation *pBlockToInsert, TrackAllocation *pBlockToInsertRW); TrackAllocation* AllocMemory_NoThrow(size_t header, size_t size, DWORD alignment, size_t reserveForJumpStubs); public: // Space for header is reserved immediately before. It is not included in size. virtual void* AllocMemForCode_NoThrow(size_t header, size_t size, DWORD alignment, size_t reserveForJumpStubs) DAC_EMPTY_RET(NULL); virtual ~HostCodeHeap() DAC_EMPTY(); LoaderAllocator* GetAllocator() { return m_pAllocator; } #ifdef DACCESS_COMPILE virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags); #endif static TrackAllocation * GetTrackAllocation(TADDR codeStart); static HostCodeHeap* GetCodeHeap(TADDR codeStart); void DestroyCodeHeap(); protected: friend class DynamicMethodDesc; friend class LCGMethodResolver; void FreeMemForCode(void * codeStart); #if defined(FEATURE_JIT_PITCHING) public: PTR_EEJitManager GetJitManager() { return m_pJitManager; } #endif }; // class HostCodeHeap //--------------------------------------------------------------------------------------- // #include "ilstubresolver.h" inline MethodDesc* GetMethod(CORINFO_METHOD_HANDLE methodHandle) { LIMITED_METHOD_CONTRACT; return (MethodDesc*) methodHandle; } #ifndef DACCESS_COMPILE #define CORINFO_MODULE_HANDLE_TYPE_MASK 1 enum CORINFO_MODULE_HANDLE_TYPES { CORINFO_NORMAL_MODULE = 0, CORINFO_DYNAMIC_MODULE, }; inline bool IsDynamicScope(CORINFO_MODULE_HANDLE module) { LIMITED_METHOD_CONTRACT; return (CORINFO_DYNAMIC_MODULE == (((size_t)module) & CORINFO_MODULE_HANDLE_TYPE_MASK)); } inline CORINFO_MODULE_HANDLE MakeDynamicScope(DynamicResolver* pResolver) { LIMITED_METHOD_CONTRACT; CONSISTENCY_CHECK(0 == (((size_t)pResolver) & CORINFO_MODULE_HANDLE_TYPE_MASK)); return (CORINFO_MODULE_HANDLE)(((size_t)pResolver) | CORINFO_DYNAMIC_MODULE); } inline DynamicResolver* GetDynamicResolver(CORINFO_MODULE_HANDLE module) { LIMITED_METHOD_CONTRACT; CONSISTENCY_CHECK(IsDynamicScope(module)); return (DynamicResolver*)(((size_t)module) & ~((size_t)CORINFO_MODULE_HANDLE_TYPE_MASK)); } inline Module* GetModule(CORINFO_MODULE_HANDLE scope) { WRAPPER_NO_CONTRACT; if (IsDynamicScope(scope)) { return GetDynamicResolver(scope)->GetDynamicMethod()->GetModule(); } else { return((Module*)scope); } } inline CORINFO_MODULE_HANDLE GetScopeHandle(Module* module) { LIMITED_METHOD_CONTRACT; return(CORINFO_MODULE_HANDLE(module)); } inline bool IsDynamicMethodHandle(CORINFO_METHOD_HANDLE method) { LIMITED_METHOD_CONTRACT; CONSISTENCY_CHECK(NULL != GetMethod(method)); return GetMethod(method)->IsDynamicMethod(); } #endif // DACCESS_COMPILE #endif // _DYNAMICMETHOD_H_
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/TestData/include_v10_c.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" > <xsd:include schemaLocation="include_v10_a.xsd"/> <xsd:include schemaLocation="include_v10_b.xsd"/> <xsd:complexType name="ct-C"> <xsd:sequence minOccurs="1"> <xsd:element name="c1" type="xsd:int" /> <xsd:element name="c2" type="xsd:int" /> </xsd:sequence> </xsd:complexType> <xsd:element name="e3" type="ct-C" /> <xsd:element name="c-e2" type="ct-B" /> <xsd:element name="c-e1" type="ct-A" /> </xsd:schema>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" > <xsd:include schemaLocation="include_v10_a.xsd"/> <xsd:include schemaLocation="include_v10_b.xsd"/> <xsd:complexType name="ct-C"> <xsd:sequence minOccurs="1"> <xsd:element name="c1" type="xsd:int" /> <xsd:element name="c2" type="xsd:int" /> </xsd:sequence> </xsd:complexType> <xsd:element name="e3" type="ct-C" /> <xsd:element name="c-e2" type="ct-B" /> <xsd:element name="c-e1" type="ct-A" /> </xsd:schema>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/Loader/classloader/generics/Layout/Specific/Positive009.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; [StructLayout(LayoutKind.Sequential, Pack=8)] public struct GenStruct<T> { T t; T Dummy(T t) { this.t = t; return t;} } [StructLayout(LayoutKind.Explicit, Pack=8)] public class NonGen { [FieldOffset(0)] GenStruct<int> genStruct; [FieldOffset(0)] int u; GenStruct<int> Dummy(GenStruct<int> t) { this.genStruct = t; return t;} int Dummy(int u) { this.u= u; return u;} } public class GenTest { private NonGen InternalTest() { return new NonGen(); } private void IndirectTest() { InternalTest(); } public bool Test_Positive009() { try { IndirectTest(); return true; } catch(Exception E) { Console.WriteLine("Test caught unexpected Exception " + E); return false; } } } public class Test_Positive009 { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Eval(new GenTest().Test_Positive009()); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 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.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Pack=8)] public struct GenStruct<T> { T t; T Dummy(T t) { this.t = t; return t;} } [StructLayout(LayoutKind.Explicit, Pack=8)] public class NonGen { [FieldOffset(0)] GenStruct<int> genStruct; [FieldOffset(0)] int u; GenStruct<int> Dummy(GenStruct<int> t) { this.genStruct = t; return t;} int Dummy(int u) { this.u= u; return u;} } public class GenTest { private NonGen InternalTest() { return new NonGen(); } private void IndirectTest() { InternalTest(); } public bool Test_Positive009() { try { IndirectTest(); return true; } catch(Exception E) { Console.WriteLine("Test caught unexpected Exception " + E); return false; } } } public class Test_Positive009 { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Eval(new GenTest().Test_Positive009()); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/coreclr/inc/cortypeinfo.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This describes information about the COM+ primitive types // // Note: This file gets parsed by the Mono IL Linker (https://github.com/mono/linker/) which may throw an exception during parsing. // Specifically, this (https://github.com/mono/linker/blob/master/corebuild/integration/ILLink.Tasks/CreateRuntimeRootDescriptorFile.cs) will try to // parse this header, and it may throw an exception while doing that. If you edit this file and get a build failure on msbuild.exe D:\repos\coreclr\build.proj // you might want to check out the parser linked above. // #define NO_SIZE ((BYTE)-1) // TYPEINFO(type (CorElementType), namespace, class, size, gcType, isArray,isPrim, isFloat,isModifier,isGenVariable) TYPEINFO(ELEMENT_TYPE_END, NULL, NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x00 TYPEINFO(ELEMENT_TYPE_VOID, "System", "Void", 0, TYPE_GC_NONE, false, true, false, false, false) // 0x01 TYPEINFO(ELEMENT_TYPE_BOOLEAN, "System", "Boolean", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x02 TYPEINFO(ELEMENT_TYPE_CHAR, "System", "Char", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x03 TYPEINFO(ELEMENT_TYPE_I1, "System", "SByte", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x04 TYPEINFO(ELEMENT_TYPE_U1, "System", "Byte", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x05 TYPEINFO(ELEMENT_TYPE_I2, "System", "Int16", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x06 TYPEINFO(ELEMENT_TYPE_U2, "System", "UInt16", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x07 TYPEINFO(ELEMENT_TYPE_I4, "System", "Int32", 4, TYPE_GC_NONE, false, true, false, false, false) // 0x08 TYPEINFO(ELEMENT_TYPE_U4, "System", "UInt32", 4, TYPE_GC_NONE, false, true, false, false, false) // 0x09 TYPEINFO(ELEMENT_TYPE_I8, "System", "Int64", 8, TYPE_GC_NONE, false, true, false, false, false) // 0x0a TYPEINFO(ELEMENT_TYPE_U8, "System", "UInt64", 8, TYPE_GC_NONE, false, true, false, false, false) // 0x0b TYPEINFO(ELEMENT_TYPE_R4, "System", "Single", 4, TYPE_GC_NONE, false, true, true, false, false) // 0x0c TYPEINFO(ELEMENT_TYPE_R8, "System", "Double", 8, TYPE_GC_NONE, false, true, true, false, false) // 0x0d TYPEINFO(ELEMENT_TYPE_STRING, "System", "String", TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x0e TYPEINFO(ELEMENT_TYPE_PTR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_NONE, false, false, false, true, false) // 0x0f TYPEINFO(ELEMENT_TYPE_BYREF, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_BYREF, false, false, false, true, false) // 0x10 TYPEINFO(ELEMENT_TYPE_VALUETYPE, NULL, NULL, NO_SIZE, TYPE_GC_OTHER, false, false, false, false, false) // 0x11 TYPEINFO(ELEMENT_TYPE_CLASS, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x12 TYPEINFO(ELEMENT_TYPE_VAR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, true) // 0x13 TYPEINFO(ELEMENT_TYPE_ARRAY, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, true, false, false, true, false) // 0x14 TYPEINFO(ELEMENT_TYPE_GENERICINST, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, false) // 0x15 TYPEINFO(ELEMENT_TYPE_TYPEDBYREF, "System", "TypedReference",2*TARGET_POINTER_SIZE,TYPE_GC_BYREF, false, false, false, false, false) // 0x16 TYPEINFO(ELEMENT_TYPE_VALUEARRAY_UNSUPPORTED, NULL,NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x17 (unsupported, not in the ECMA spec) TYPEINFO(ELEMENT_TYPE_I, "System", "IntPtr", TARGET_POINTER_SIZE, TYPE_GC_NONE, false, true, false, false, false) // 0x18 TYPEINFO(ELEMENT_TYPE_U, "System", "UIntPtr", TARGET_POINTER_SIZE, TYPE_GC_NONE, false, true, false, false, false) // 0x19 TYPEINFO(ELEMENT_TYPE_R_UNSUPPORTED,NULL, NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x1a (unsupported, not in the ECMA spec) TYPEINFO(ELEMENT_TYPE_FNPTR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x1b TYPEINFO(ELEMENT_TYPE_OBJECT, "System", "Object", TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x1c TYPEINFO(ELEMENT_TYPE_SZARRAY, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, true, false, false, true, false) // 0x1d TYPEINFO(ELEMENT_TYPE_MVAR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, true) // x01e TYPEINFO(ELEMENT_TYPE_CMOD_REQD, NULL, NULL, 0, TYPE_GC_NONE, false, false, false, false, false) // 0x1f TYPEINFO(ELEMENT_TYPE_CMOD_OPT, NULL, NULL, 0, TYPE_GC_NONE, false, false, false, false, false) // 0x20 TYPEINFO(ELEMENT_TYPE_INTERNAL, NULL, NULL, 0, TYPE_GC_OTHER, false, false, false, false, false) // 0x21
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This describes information about the COM+ primitive types // // Note: This file gets parsed by the Mono IL Linker (https://github.com/mono/linker/) which may throw an exception during parsing. // Specifically, this (https://github.com/mono/linker/blob/master/corebuild/integration/ILLink.Tasks/CreateRuntimeRootDescriptorFile.cs) will try to // parse this header, and it may throw an exception while doing that. If you edit this file and get a build failure on msbuild.exe D:\repos\coreclr\build.proj // you might want to check out the parser linked above. // #define NO_SIZE ((BYTE)-1) // TYPEINFO(type (CorElementType), namespace, class, size, gcType, isArray,isPrim, isFloat,isModifier,isGenVariable) TYPEINFO(ELEMENT_TYPE_END, NULL, NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x00 TYPEINFO(ELEMENT_TYPE_VOID, "System", "Void", 0, TYPE_GC_NONE, false, true, false, false, false) // 0x01 TYPEINFO(ELEMENT_TYPE_BOOLEAN, "System", "Boolean", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x02 TYPEINFO(ELEMENT_TYPE_CHAR, "System", "Char", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x03 TYPEINFO(ELEMENT_TYPE_I1, "System", "SByte", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x04 TYPEINFO(ELEMENT_TYPE_U1, "System", "Byte", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x05 TYPEINFO(ELEMENT_TYPE_I2, "System", "Int16", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x06 TYPEINFO(ELEMENT_TYPE_U2, "System", "UInt16", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x07 TYPEINFO(ELEMENT_TYPE_I4, "System", "Int32", 4, TYPE_GC_NONE, false, true, false, false, false) // 0x08 TYPEINFO(ELEMENT_TYPE_U4, "System", "UInt32", 4, TYPE_GC_NONE, false, true, false, false, false) // 0x09 TYPEINFO(ELEMENT_TYPE_I8, "System", "Int64", 8, TYPE_GC_NONE, false, true, false, false, false) // 0x0a TYPEINFO(ELEMENT_TYPE_U8, "System", "UInt64", 8, TYPE_GC_NONE, false, true, false, false, false) // 0x0b TYPEINFO(ELEMENT_TYPE_R4, "System", "Single", 4, TYPE_GC_NONE, false, true, true, false, false) // 0x0c TYPEINFO(ELEMENT_TYPE_R8, "System", "Double", 8, TYPE_GC_NONE, false, true, true, false, false) // 0x0d TYPEINFO(ELEMENT_TYPE_STRING, "System", "String", TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x0e TYPEINFO(ELEMENT_TYPE_PTR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_NONE, false, false, false, true, false) // 0x0f TYPEINFO(ELEMENT_TYPE_BYREF, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_BYREF, false, false, false, true, false) // 0x10 TYPEINFO(ELEMENT_TYPE_VALUETYPE, NULL, NULL, NO_SIZE, TYPE_GC_OTHER, false, false, false, false, false) // 0x11 TYPEINFO(ELEMENT_TYPE_CLASS, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x12 TYPEINFO(ELEMENT_TYPE_VAR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, true) // 0x13 TYPEINFO(ELEMENT_TYPE_ARRAY, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, true, false, false, true, false) // 0x14 TYPEINFO(ELEMENT_TYPE_GENERICINST, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, false) // 0x15 TYPEINFO(ELEMENT_TYPE_TYPEDBYREF, "System", "TypedReference",2*TARGET_POINTER_SIZE,TYPE_GC_BYREF, false, false, false, false, false) // 0x16 TYPEINFO(ELEMENT_TYPE_VALUEARRAY_UNSUPPORTED, NULL,NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x17 (unsupported, not in the ECMA spec) TYPEINFO(ELEMENT_TYPE_I, "System", "IntPtr", TARGET_POINTER_SIZE, TYPE_GC_NONE, false, true, false, false, false) // 0x18 TYPEINFO(ELEMENT_TYPE_U, "System", "UIntPtr", TARGET_POINTER_SIZE, TYPE_GC_NONE, false, true, false, false, false) // 0x19 TYPEINFO(ELEMENT_TYPE_R_UNSUPPORTED,NULL, NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x1a (unsupported, not in the ECMA spec) TYPEINFO(ELEMENT_TYPE_FNPTR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x1b TYPEINFO(ELEMENT_TYPE_OBJECT, "System", "Object", TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x1c TYPEINFO(ELEMENT_TYPE_SZARRAY, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, true, false, false, true, false) // 0x1d TYPEINFO(ELEMENT_TYPE_MVAR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, true) // x01e TYPEINFO(ELEMENT_TYPE_CMOD_REQD, NULL, NULL, 0, TYPE_GC_NONE, false, false, false, false, false) // 0x1f TYPEINFO(ELEMENT_TYPE_CMOD_OPT, NULL, NULL, 0, TYPE_GC_NONE, false, false, false, false, false) // 0x20 TYPEINFO(ELEMENT_TYPE_INTERNAL, NULL, NULL, 0, TYPE_GC_OTHER, false, false, false, false, false) // 0x21
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/GCPointerMapTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.TypeSystem; using Xunit; namespace TypeSystemTests { public partial class GCPointerMapTests { TestTypeSystemContext _context; ModuleDesc _testModule; public GCPointerMapTests() { _context = new TestTypeSystemContext(TargetArchitecture.X86); var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly"); _context.SetSystemModule(systemModule); _testModule = systemModule; } [Fact] public void TestInstanceMap() { MetadataType classWithArrayFields = _testModule.GetType("GCPointerMap", "ClassWithArrayFields"); MetadataType classWithStringField = _testModule.GetType("GCPointerMap", "ClassWithStringField"); MetadataType mixedStruct = _testModule.GetType("GCPointerMap", "MixedStruct"); MetadataType structWithSameGCLayoutAsMixedStruct = _testModule.GetType("GCPointerMap", "StructWithSameGCLayoutAsMixedStruct"); MetadataType doubleMixedStructLayout = _testModule.GetType("GCPointerMap", "DoubleMixedStructLayout"); MetadataType explicitlyFarPointer = _testModule.GetType("GCPointerMap", "ExplicitlyFarPointer"); MetadataType struct32GcPointers = _testModule.GetType("GCPointerMap", "Struct32GcPointers"); { var map = GCPointerMap.FromInstanceLayout(classWithArrayFields); Assert.Equal(3, map.Size); Assert.Equal("011", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(classWithStringField); Assert.Equal(4, map.Size); Assert.Equal("0010", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(mixedStruct); Assert.Equal(5, map.Size); Assert.Equal("01001", map.ToString()); } { var map1 = GCPointerMap.FromInstanceLayout(mixedStruct); var map2 = GCPointerMap.FromInstanceLayout(structWithSameGCLayoutAsMixedStruct); Assert.Equal(map1.Size, map2.Size); Assert.Equal(map1.ToString(), map2.ToString()); } { var map = GCPointerMap.FromInstanceLayout(doubleMixedStructLayout); Assert.Equal(10, map.Size); Assert.Equal("0100101001", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(explicitlyFarPointer); Assert.Equal(117, map.Size); Assert.Equal("100000000000000000000000000000000000000000000000000000000000000010000000000000001000000000000000000000000000000001001", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(struct32GcPointers); Assert.Equal(32, map.Size); Assert.Equal("11111111111111111111111111111111", map.ToString()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.TypeSystem; using Xunit; namespace TypeSystemTests { public partial class GCPointerMapTests { TestTypeSystemContext _context; ModuleDesc _testModule; public GCPointerMapTests() { _context = new TestTypeSystemContext(TargetArchitecture.X86); var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly"); _context.SetSystemModule(systemModule); _testModule = systemModule; } [Fact] public void TestInstanceMap() { MetadataType classWithArrayFields = _testModule.GetType("GCPointerMap", "ClassWithArrayFields"); MetadataType classWithStringField = _testModule.GetType("GCPointerMap", "ClassWithStringField"); MetadataType mixedStruct = _testModule.GetType("GCPointerMap", "MixedStruct"); MetadataType structWithSameGCLayoutAsMixedStruct = _testModule.GetType("GCPointerMap", "StructWithSameGCLayoutAsMixedStruct"); MetadataType doubleMixedStructLayout = _testModule.GetType("GCPointerMap", "DoubleMixedStructLayout"); MetadataType explicitlyFarPointer = _testModule.GetType("GCPointerMap", "ExplicitlyFarPointer"); MetadataType struct32GcPointers = _testModule.GetType("GCPointerMap", "Struct32GcPointers"); { var map = GCPointerMap.FromInstanceLayout(classWithArrayFields); Assert.Equal(3, map.Size); Assert.Equal("011", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(classWithStringField); Assert.Equal(4, map.Size); Assert.Equal("0010", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(mixedStruct); Assert.Equal(5, map.Size); Assert.Equal("01001", map.ToString()); } { var map1 = GCPointerMap.FromInstanceLayout(mixedStruct); var map2 = GCPointerMap.FromInstanceLayout(structWithSameGCLayoutAsMixedStruct); Assert.Equal(map1.Size, map2.Size); Assert.Equal(map1.ToString(), map2.ToString()); } { var map = GCPointerMap.FromInstanceLayout(doubleMixedStructLayout); Assert.Equal(10, map.Size); Assert.Equal("0100101001", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(explicitlyFarPointer); Assert.Equal(117, map.Size); Assert.Equal("100000000000000000000000000000000000000000000000000000000000000010000000000000001000000000000000000000000000000001001", map.ToString()); } { var map = GCPointerMap.FromInstanceLayout(struct32GcPointers); Assert.Equal(32, map.Size); Assert.Equal("11111111111111111111111111111111", map.ToString()); } } } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/explicit/basic/refarg_f8_il_d.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="refarg_f8.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="refarg_f8.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/apicompat/ApiCompatBaseline.PreviousNetCoreApp.txt
Compat issues with assembly mscorlib: CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DeriveBytes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DES' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSA' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Int32)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Security.Cryptography.DSAParameters)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.PKCS1MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RandomNumberGenerator.Create(System.String)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RC2' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.RC2.Create()' changed from '[UnsupportedOSPlatformAttribute("android")]' in the contract to '[UnsupportedOSPlatformAttribute("android")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Rijndael' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSA' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAEncryptionPadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSASignaturePadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.SignatureDescription' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.TripleDES' in the contract but not the implementation. Compat issues with assembly netstandard: CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MaxWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MinWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(System.Span<System.Byte>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(System.Span<T>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(T[])' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(T[], System.Int32)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Equals(System.Numerics.Vector<T>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Equals(System.Object)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.GetHashCode()' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Item.get(System.Int32)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString()' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString(System.String)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString(System.String, System.IFormatProvider)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.TryCopyTo(System.Span<System.Byte>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.TryCopyTo(System.Span<T>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DeriveBytes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DES' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSA' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Int32)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Security.Cryptography.DSAParameters)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECCurve' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDiffieHellman' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDsa' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECParameters' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.PKCS1MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RandomNumberGenerator.Create(System.String)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RC2' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.RC2.Create()' changed from '[UnsupportedOSPlatformAttribute("android")]' in the contract to '[UnsupportedOSPlatformAttribute("android")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Rijndael' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSA' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAEncryptionPadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSASignaturePadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.SignatureDescription' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.TripleDES' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.X509Certificates.PublicKey.GetDSAPublicKey()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. Compat issues with assembly System: CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MaxWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MinWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.X509Certificates.PublicKey.GetDSAPublicKey()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. Compat issues with assembly System.Core: CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECCurve' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDiffieHellman' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDsa' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECParameters' in the contract but not the implementation. Compat issues with assembly System.Diagnostics.Process: CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MaxWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MinWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. Compat issues with assembly System.Numerics.Vectors: CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(System.Span<System.Byte>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(System.Span<T>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(T[])' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(T[], System.Int32)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Equals(System.Numerics.Vector<T>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Equals(System.Object)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.GetHashCode()' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Item.get(System.Int32)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString()' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString(System.String)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString(System.String, System.IFormatProvider)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.TryCopyTo(System.Span<System.Byte>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.TryCopyTo(System.Span<T>)' in the contract but not the implementation. Compat issues with assembly System.Runtime.Intrinsics: MembersMustExist : Member 'public System.Runtime.Intrinsics.Vector128<U> System.Runtime.Intrinsics.Vector128.As<T, U>(System.Runtime.Intrinsics.Vector128<T>)' does not exist in the implementation but it does exist in the contract. MembersMustExist : Member 'public System.Runtime.Intrinsics.Vector256<U> System.Runtime.Intrinsics.Vector256.As<T, U>(System.Runtime.Intrinsics.Vector256<T>)' does not exist in the implementation but it does exist in the contract. MembersMustExist : Member 'public System.Runtime.Intrinsics.Vector64<U> System.Runtime.Intrinsics.Vector64.As<T, U>(System.Runtime.Intrinsics.Vector64<T>)' does not exist in the implementation but it does exist in the contract. Compat issues with assembly System.Security.Cryptography.Algorithms: CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DeriveBytes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DES' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSA' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Int32)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Security.Cryptography.DSAParameters)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECCurve' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDiffieHellman' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDsa' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECParameters' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.PKCS1MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RandomNumberGenerator.Create(System.String)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RC2' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.RC2.Create()' changed from '[UnsupportedOSPlatformAttribute("android")]' in the contract to '[UnsupportedOSPlatformAttribute("android")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Rijndael' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSA' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAEncryptionPadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSASignaturePadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.SignatureDescription' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.TripleDES' in the contract but not the implementation. Compat issues with assembly System.Security.Cryptography.X509Certificates: CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.X509Certificates.PublicKey.GetDSAPublicKey()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. Total Issues: 135
Compat issues with assembly mscorlib: CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DeriveBytes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DES' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSA' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Int32)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Security.Cryptography.DSAParameters)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.PKCS1MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RandomNumberGenerator.Create(System.String)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RC2' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.RC2.Create()' changed from '[UnsupportedOSPlatformAttribute("android")]' in the contract to '[UnsupportedOSPlatformAttribute("android")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Rijndael' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSA' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAEncryptionPadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSASignaturePadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.SignatureDescription' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.TripleDES' in the contract but not the implementation. Compat issues with assembly netstandard: CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MaxWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MinWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(System.Span<System.Byte>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(System.Span<T>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(T[])' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(T[], System.Int32)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Equals(System.Numerics.Vector<T>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Equals(System.Object)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.GetHashCode()' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Item.get(System.Int32)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString()' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString(System.String)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString(System.String, System.IFormatProvider)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.TryCopyTo(System.Span<System.Byte>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.TryCopyTo(System.Span<T>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DeriveBytes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DES' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSA' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Int32)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Security.Cryptography.DSAParameters)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECCurve' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDiffieHellman' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDsa' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECParameters' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.PKCS1MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RandomNumberGenerator.Create(System.String)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RC2' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.RC2.Create()' changed from '[UnsupportedOSPlatformAttribute("android")]' in the contract to '[UnsupportedOSPlatformAttribute("android")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Rijndael' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSA' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAEncryptionPadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSASignaturePadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.SignatureDescription' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.TripleDES' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.X509Certificates.PublicKey.GetDSAPublicKey()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. Compat issues with assembly System: CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MaxWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MinWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.X509Certificates.PublicKey.GetDSAPublicKey()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. Compat issues with assembly System.Core: CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECCurve' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDiffieHellman' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDsa' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECParameters' in the contract but not the implementation. Compat issues with assembly System.Diagnostics.Process: CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MaxWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.SupportedOSPlatformAttribute' on 'System.Diagnostics.Process.MinWorkingSet.set(System.IntPtr)' changed from '[SupportedOSPlatformAttribute("freebsd")]' in the contract to '[SupportedOSPlatformAttribute("freebsd")]' in the implementation. Compat issues with assembly System.Numerics.Vectors: CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(System.Span<System.Byte>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(System.Span<T>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(T[])' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.CopyTo(T[], System.Int32)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Equals(System.Numerics.Vector<T>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Equals(System.Object)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.GetHashCode()' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.Item.get(System.Int32)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString()' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString(System.String)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.ToString(System.String, System.IFormatProvider)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.TryCopyTo(System.Span<System.Byte>)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector<T>.TryCopyTo(System.Span<T>)' in the contract but not the implementation. Compat issues with assembly System.Runtime.Intrinsics: MembersMustExist : Member 'public System.Runtime.Intrinsics.Vector128<U> System.Runtime.Intrinsics.Vector128.As<T, U>(System.Runtime.Intrinsics.Vector128<T>)' does not exist in the implementation but it does exist in the contract. MembersMustExist : Member 'public System.Runtime.Intrinsics.Vector256<U> System.Runtime.Intrinsics.Vector256.As<T, U>(System.Runtime.Intrinsics.Vector256<T>)' does not exist in the implementation but it does exist in the contract. MembersMustExist : Member 'public System.Runtime.Intrinsics.Vector64<U> System.Runtime.Intrinsics.Vector64.As<T, U>(System.Runtime.Intrinsics.Vector64<T>)' does not exist in the implementation but it does exist in the contract. Compat issues with assembly System.Security.Cryptography.Algorithms: CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricSignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DeriveBytes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DES' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSA' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Int32)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.DSA.Create(System.Security.Cryptography.DSAParameters)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.DSASignatureFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECCurve' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDiffieHellman' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECDsa' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.ECParameters' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.PKCS1MaskGenerationMethod' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RandomNumberGenerator.Create(System.String)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RC2' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.RC2.Create()' changed from '[UnsupportedOSPlatformAttribute("android")]' in the contract to '[UnsupportedOSPlatformAttribute("android")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Rijndael' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSA' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAEncryptionPadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAOAEPKeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSAPKCS1KeyExchangeFormatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.RSASignaturePadding' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.SignatureDescription' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.TripleDES' in the contract but not the implementation. Compat issues with assembly System.Security.Cryptography.X509Certificates: CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.X509Certificates.PublicKey.GetDSAPublicKey()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. Total Issues: 135
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./docs/design/features/host-testing.md
# Testing of host components The hosting layer of .NET Core consists of several native libraries and executables (entirely written in C++). The full end to end features sometimes require code in the `coreclr` repo, but testing of that is outside of the scope of this document. For description of the various hosting components, please see [host-components](host-components.md). Testing these comes with certain challenges which this document tries to address. ## Existing tests Almost all tests for the hosting components are currently basically End-to-End tests which execute the entire product (with very limited amount of "mocking"). ### End-to-End tests This is almost all tests in the `HostActivation` test project currently. The tests prepare folders on the disk which emulate the product installation by having * The muxer `dotnet` or `apphost` * The `hostfxr` in the right place * Shared frameworks (or for self contained apps in the app directory) For the most part all these are real components. The shared frameworks contain a real `Microsoft.NETCore.App` copy, only higher level frameworks are "mocked" by creating only the necessary files. Almost all tests then execute a test application using this test product installation and observe the behavior of the app. This is done by * Having the app output information to standard output * Turning on host tracing and looking for certain text in the tracing output * Exit code of the app Pros: * True End-to-End tests which test real product binaries in the real-world conditions (mostly) * Tests are written in C# - so natural integration with test infra, VS UI and so on Cons: * All tests are out-of-proc which makes debugging product complicated * Tests perform large setup work and copy/write lot of files on disk - tests are slow for this reason. * Tests run the entire product, not just the host. This includes starting the runtime, JITing and so on. Vast majority of tests don't actually use that and effectively ignore the part of running an actual app code - makes the tests slow. Going forward we would keep these tests and add new ones to provide true End-to-End coverage. ### Native API tests Small portion of the tests actually call specific exports on `hostfxr` or `hostpolicy` directly to test these. All these tests are in the `HostActivation` project under the `NativeHostApis` test class. These tests use a special test application (managed) which invokes the selected exports through PInvokes and performs the testing. The `HostActivation` test only prepares this app and executes it, looking for pieces of its output to verify the outcome. Ideally we would migrate these over time to the proposed Component tests infra. Pros: * Testing real product binaries * Tests are written in C#, but in a separate project - no direct test infra integration or VS UI support. This is worked around by effectively having "wrappers" for these tests. * Direct calls to exports in a controlled environment without running the whole product (mostly) Cons: * Still runs out-of-proc making debugging harder ## Test proposal ### Unit tests Add the ability to write true unit tests. So tests are written in C++ which can directly call methods/classes from the product. These tests would be compiled as native executables. For simplicity of the build system, they would live in the product source tree (`src` folder) and would be compiled during the product build. They would combine the test source files with product source files into one executable. The intent is to keep them in a separate subdirectory with clear separation from the product, just the build would be used by both. For integration purposes there would be managed wrappers in the `HostActivation` test project which would just call the native executable and check the exit code. As this is the simplest way to integrate these tests into all our test infrastructure. Unit tests should be used to test self-contained bits of functionality. So for example helper classes and such. First unit test is being introduced in this PR: [dotnet/core-setup#4953](https://github.com/dotnet/core-setup/pull/4953). Pros: * Can test C++ code directly * Can create very isolated environment for the tested code * Debugging is relatively easy since the test run in a standalone native process Cons: * Test must be written in C++ * Not testing shipping binaries ### Component tests Testing larger functionality blocks is probably easier by testing entire components. These tests would call entry points on the host components directly (so `hostfxr` and `hostpolicy` mostly) and observe the resulting behavior. The tests would **not** try to emulate real product installation. Instead they would rely on mocks. The core of this proposed test approach is * The tested component (`hostfxr` for example) is loaded directly into the test process - so it would be running on some toolset version of .NET Core and not the tested version of .NET Core - but that should not matter as all of that should be abstracted out. * Mock file system access and other OS services which would otherwise require complex setup * Mock dependent libraries (so for example `coreclr`) as necessary Product changes would be required to allow for mocking OS services. This would be achieved by having test-only exports/env variables which would turn on the mocking. For example file system mocking would be done by abstracting file system access through and interface and having an export which would let the test provide custom implementation of that interface. There are two way to do this: * Test-only build of the product component, which would have additional exports to enable mocking. * Pros: * Hides all the test related features from the real product * Allows for usage of conditional compilation to completely exclude some of this functionality from the product. * Cons: * Not testing real product binaries * Add test-only entry-points to the product. Either as new exports on the libraries or by having a "plugin" mechanism (env. variable which specifies a path to a library to load and call some export on). * Pros: * Allows testing real product binaries * Only one compilation * Cons: * Product binaries have publicly accessible test entry points. These would not be documented as being part of the product, but they would still be accessible. * Product binaries always contain all test-related code (no conditional compilation) Pros: * Tests are written in C#. This has several large advantages: * Easier to write * Full integration with test infra * VS UI support for running selected tests * Mocking file system and other OS services requires relatively complex data structures which are much easier to work with in C# than in C++ * Mocks can still be written in C# (COM-style interfaces for example) for the most part * Debugging should be easier as everything runs in-proc (although it does require mixed mode debugging for full experience) Cons: * Potentially not testing shipping binaries * Requires larger testing infrastructure (all the mocks)
# Testing of host components The hosting layer of .NET Core consists of several native libraries and executables (entirely written in C++). The full end to end features sometimes require code in the `coreclr` repo, but testing of that is outside of the scope of this document. For description of the various hosting components, please see [host-components](host-components.md). Testing these comes with certain challenges which this document tries to address. ## Existing tests Almost all tests for the hosting components are currently basically End-to-End tests which execute the entire product (with very limited amount of "mocking"). ### End-to-End tests This is almost all tests in the `HostActivation` test project currently. The tests prepare folders on the disk which emulate the product installation by having * The muxer `dotnet` or `apphost` * The `hostfxr` in the right place * Shared frameworks (or for self contained apps in the app directory) For the most part all these are real components. The shared frameworks contain a real `Microsoft.NETCore.App` copy, only higher level frameworks are "mocked" by creating only the necessary files. Almost all tests then execute a test application using this test product installation and observe the behavior of the app. This is done by * Having the app output information to standard output * Turning on host tracing and looking for certain text in the tracing output * Exit code of the app Pros: * True End-to-End tests which test real product binaries in the real-world conditions (mostly) * Tests are written in C# - so natural integration with test infra, VS UI and so on Cons: * All tests are out-of-proc which makes debugging product complicated * Tests perform large setup work and copy/write lot of files on disk - tests are slow for this reason. * Tests run the entire product, not just the host. This includes starting the runtime, JITing and so on. Vast majority of tests don't actually use that and effectively ignore the part of running an actual app code - makes the tests slow. Going forward we would keep these tests and add new ones to provide true End-to-End coverage. ### Native API tests Small portion of the tests actually call specific exports on `hostfxr` or `hostpolicy` directly to test these. All these tests are in the `HostActivation` project under the `NativeHostApis` test class. These tests use a special test application (managed) which invokes the selected exports through PInvokes and performs the testing. The `HostActivation` test only prepares this app and executes it, looking for pieces of its output to verify the outcome. Ideally we would migrate these over time to the proposed Component tests infra. Pros: * Testing real product binaries * Tests are written in C#, but in a separate project - no direct test infra integration or VS UI support. This is worked around by effectively having "wrappers" for these tests. * Direct calls to exports in a controlled environment without running the whole product (mostly) Cons: * Still runs out-of-proc making debugging harder ## Test proposal ### Unit tests Add the ability to write true unit tests. So tests are written in C++ which can directly call methods/classes from the product. These tests would be compiled as native executables. For simplicity of the build system, they would live in the product source tree (`src` folder) and would be compiled during the product build. They would combine the test source files with product source files into one executable. The intent is to keep them in a separate subdirectory with clear separation from the product, just the build would be used by both. For integration purposes there would be managed wrappers in the `HostActivation` test project which would just call the native executable and check the exit code. As this is the simplest way to integrate these tests into all our test infrastructure. Unit tests should be used to test self-contained bits of functionality. So for example helper classes and such. First unit test is being introduced in this PR: [dotnet/core-setup#4953](https://github.com/dotnet/core-setup/pull/4953). Pros: * Can test C++ code directly * Can create very isolated environment for the tested code * Debugging is relatively easy since the test run in a standalone native process Cons: * Test must be written in C++ * Not testing shipping binaries ### Component tests Testing larger functionality blocks is probably easier by testing entire components. These tests would call entry points on the host components directly (so `hostfxr` and `hostpolicy` mostly) and observe the resulting behavior. The tests would **not** try to emulate real product installation. Instead they would rely on mocks. The core of this proposed test approach is * The tested component (`hostfxr` for example) is loaded directly into the test process - so it would be running on some toolset version of .NET Core and not the tested version of .NET Core - but that should not matter as all of that should be abstracted out. * Mock file system access and other OS services which would otherwise require complex setup * Mock dependent libraries (so for example `coreclr`) as necessary Product changes would be required to allow for mocking OS services. This would be achieved by having test-only exports/env variables which would turn on the mocking. For example file system mocking would be done by abstracting file system access through and interface and having an export which would let the test provide custom implementation of that interface. There are two way to do this: * Test-only build of the product component, which would have additional exports to enable mocking. * Pros: * Hides all the test related features from the real product * Allows for usage of conditional compilation to completely exclude some of this functionality from the product. * Cons: * Not testing real product binaries * Add test-only entry-points to the product. Either as new exports on the libraries or by having a "plugin" mechanism (env. variable which specifies a path to a library to load and call some export on). * Pros: * Allows testing real product binaries * Only one compilation * Cons: * Product binaries have publicly accessible test entry points. These would not be documented as being part of the product, but they would still be accessible. * Product binaries always contain all test-related code (no conditional compilation) Pros: * Tests are written in C#. This has several large advantages: * Easier to write * Full integration with test infra * VS UI support for running selected tests * Mocking file system and other OS services requires relatively complex data structures which are much easier to work with in C# than in C++ * Mocks can still be written in C# (COM-style interfaces for example) for the most part * Debugging should be easier as everything runs in-proc (although it does require mixed mode debugging for full experience) Cons: * Potentially not testing shipping binaries * Requires larger testing infrastructure (all the mocks)
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/GetAndWithElement.Byte.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\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 GetAndWithElementByte7() { var test = new VectorGetAndWithElement__GetAndWithElementByte7(); // 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__GetAndWithElementByte7 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 7, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Byte[] values = new Byte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetByte(); } Vector256<Byte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); bool succeeded = !expectedOutOfRangeException; try { Byte result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Byte insertedValue = TestLibrary.Generator.GetByte(); try { Vector256<Byte> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 7, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Byte[] values = new Byte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetByte(); } Vector256<Byte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(Byte)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Byte)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Byte insertedValue = TestLibrary.Generator.GetByte(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(Byte)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<Byte>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(7 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(7 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(7 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(7 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Byte result, Byte[] values, [CallerMemberName] string method = "") { if (result != values[7]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement(7): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<Byte> result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "") { Byte[] resultElements = new Byte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Byte[] result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 7) && (result[i] != values[i])) { succeeded = false; break; } } if (result[7] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement(7): {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 GetAndWithElementByte7() { var test = new VectorGetAndWithElement__GetAndWithElementByte7(); // 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__GetAndWithElementByte7 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 7, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Byte[] values = new Byte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetByte(); } Vector256<Byte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); bool succeeded = !expectedOutOfRangeException; try { Byte result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Byte insertedValue = TestLibrary.Generator.GetByte(); try { Vector256<Byte> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 7, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Byte[] values = new Byte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetByte(); } Vector256<Byte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(Byte)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Byte)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Byte insertedValue = TestLibrary.Generator.GetByte(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(Byte)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<Byte>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(7 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(7 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(7 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(7 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Byte result, Byte[] values, [CallerMemberName] string method = "") { if (result != values[7]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<Byte.GetElement(7): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<Byte> result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "") { Byte[] resultElements = new Byte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Byte[] result, Byte[] values, Byte insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 7) && (result[i] != values[i])) { succeeded = false; break; } } if (result[7] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<Byte.WithElement(7): {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,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Regression/JitBlue/GitHub_9692/GitHub_9692.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType /> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType /> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/native/corehost/ijwhost/pedecoder.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef PEDECODER_H #define PEDECODER_H #include "pal.h" struct IMAGE_COR_VTABLEFIXUP; // A subsection of the PEDecoder from CoreCLR that has only the methods we need. class PEDecoder { public: PEDecoder(void* mappedBase) :m_base((std::uintptr_t)mappedBase) { } bool HasCorHeader() const { return HasDirectoryEntry(IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR); } bool HasManagedEntryPoint() const; bool HasNativeEntryPoint() const; void* GetNativeEntryPoint() const; IMAGE_COR_VTABLEFIXUP* GetVTableFixups(size_t* numFixupRecords) const; HINSTANCE GetBase() const { return (HINSTANCE)m_base; } std::uintptr_t GetRvaData(std::uint32_t rva) const { if (rva == 0) { return (std::uintptr_t)nullptr; } return m_base + rva; } private: bool HasDirectoryEntry(int entry) const { return FindNTHeaders()->OptionalHeader.DataDirectory[entry].VirtualAddress != 0; } IMAGE_NT_HEADERS* FindNTHeaders() const { return reinterpret_cast<IMAGE_NT_HEADERS*>(m_base + (reinterpret_cast<IMAGE_DOS_HEADER*>(m_base)->e_lfanew)); } IMAGE_COR20_HEADER *GetCorHeader() const { return FindCorHeader(); } inline IMAGE_COR20_HEADER *FindCorHeader() const { return reinterpret_cast<IMAGE_COR20_HEADER*>(GetDirectoryEntryData(IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR)); } IMAGE_DATA_DIRECTORY *GetDirectoryEntry(int entry) const { return reinterpret_cast<IMAGE_DATA_DIRECTORY*>( reinterpret_cast<std::uintptr_t>(FindNTHeaders()) + offsetof(IMAGE_NT_HEADERS, OptionalHeader.DataDirectory) + entry * sizeof(IMAGE_DATA_DIRECTORY)); } std::uintptr_t GetDirectoryEntryData(int entry, size_t* pSize = nullptr) const { IMAGE_DATA_DIRECTORY *pDir = GetDirectoryEntry(entry); if (pSize != nullptr) *pSize = (std::int32_t)(pDir->Size); return GetDirectoryData(pDir); } std::uintptr_t PEDecoder::GetDirectoryData(IMAGE_DATA_DIRECTORY *pDir) const { return GetRvaData(pDir->VirtualAddress); } std::uintptr_t m_base; }; #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef PEDECODER_H #define PEDECODER_H #include "pal.h" struct IMAGE_COR_VTABLEFIXUP; // A subsection of the PEDecoder from CoreCLR that has only the methods we need. class PEDecoder { public: PEDecoder(void* mappedBase) :m_base((std::uintptr_t)mappedBase) { } bool HasCorHeader() const { return HasDirectoryEntry(IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR); } bool HasManagedEntryPoint() const; bool HasNativeEntryPoint() const; void* GetNativeEntryPoint() const; IMAGE_COR_VTABLEFIXUP* GetVTableFixups(size_t* numFixupRecords) const; HINSTANCE GetBase() const { return (HINSTANCE)m_base; } std::uintptr_t GetRvaData(std::uint32_t rva) const { if (rva == 0) { return (std::uintptr_t)nullptr; } return m_base + rva; } private: bool HasDirectoryEntry(int entry) const { return FindNTHeaders()->OptionalHeader.DataDirectory[entry].VirtualAddress != 0; } IMAGE_NT_HEADERS* FindNTHeaders() const { return reinterpret_cast<IMAGE_NT_HEADERS*>(m_base + (reinterpret_cast<IMAGE_DOS_HEADER*>(m_base)->e_lfanew)); } IMAGE_COR20_HEADER *GetCorHeader() const { return FindCorHeader(); } inline IMAGE_COR20_HEADER *FindCorHeader() const { return reinterpret_cast<IMAGE_COR20_HEADER*>(GetDirectoryEntryData(IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR)); } IMAGE_DATA_DIRECTORY *GetDirectoryEntry(int entry) const { return reinterpret_cast<IMAGE_DATA_DIRECTORY*>( reinterpret_cast<std::uintptr_t>(FindNTHeaders()) + offsetof(IMAGE_NT_HEADERS, OptionalHeader.DataDirectory) + entry * sizeof(IMAGE_DATA_DIRECTORY)); } std::uintptr_t GetDirectoryEntryData(int entry, size_t* pSize = nullptr) const { IMAGE_DATA_DIRECTORY *pDir = GetDirectoryEntry(entry); if (pSize != nullptr) *pSize = (std::int32_t)(pDir->Size); return GetDirectoryData(pDir); } std::uintptr_t PEDecoder::GetDirectoryData(IMAGE_DATA_DIRECTORY *pDir) const { return GetRvaData(pDir->VirtualAddress); } std::uintptr_t m_base; }; #endif
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParseException.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.Runtime.Serialization; namespace System.Text.RegularExpressions { /// <summary> /// An exception as a result of a parse error in a regular expression <see cref="RegularExpressions"/>, with /// detailed information in the <see cref="Error"/> and <see cref="Offset"/> properties. /// </summary> [Serializable] #if REGEXGENERATOR internal #else public #endif sealed class RegexParseException : ArgumentException { /// <summary>Gets the error that happened during parsing.</summary> public RegexParseError Error { get; } /// <summary>Gets the zero-based character offset in the regular expression pattern where the parse error occurs.</summary> public int Offset { get; } internal RegexParseException(RegexParseError error, int offset, string message) : base(message) { Error = error; Offset = offset; } internal RegexParseException(string pattern, RegexParseError error, int offset) : base(MakeMessage(pattern, error, offset)) { Error = error; Offset = offset; } /// <summary> /// Construct a <see cref="RegexParseException"/> that creates a default message based on the given <see cref="RegexParseError"/> value. /// </summary> /// <param name="pattern">The pattern of the regular expression.</param> /// <param name="error">The <see cref="RegexParseError"/> value detailing the type of parse error.</param> /// <param name="offset">The zero-based offset in the regular expression where the parse error occurs.</param> private static string MakeMessage(string pattern, RegexParseError error, int offset) { string message; switch (error) { case RegexParseError.Unknown: message = SR.Format(SR.MakeException, pattern, offset, SR.Generic); break; case RegexParseError.AlternationHasTooManyConditions: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasTooManyConditions); break; case RegexParseError.AlternationHasMalformedCondition: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasMalformedCondition); break; case RegexParseError.InvalidUnicodePropertyEscape: message = SR.Format(SR.MakeException, pattern, offset, SR.InvalidUnicodePropertyEscape); break; case RegexParseError.MalformedUnicodePropertyEscape: message = SR.Format(SR.MakeException, pattern, offset, SR.MalformedUnicodePropertyEscape); break; case RegexParseError.UnrecognizedEscape: message = SR.Format(SR.MakeException, pattern, offset, SR.UnrecognizedEscape); break; case RegexParseError.UnrecognizedControlCharacter: message = SR.Format(SR.MakeException, pattern, offset, SR.UnrecognizedControlCharacter); break; case RegexParseError.MissingControlCharacter: message = SR.Format(SR.MakeException, pattern, offset, SR.MissingControlCharacter); break; case RegexParseError.InsufficientOrInvalidHexDigits: message = SR.Format(SR.MakeException, pattern, offset, SR.InsufficientOrInvalidHexDigits); break; case RegexParseError.QuantifierOrCaptureGroupOutOfRange: message = SR.Format(SR.MakeException, pattern, offset, SR.QuantifierOrCaptureGroupOutOfRange); break; case RegexParseError.UndefinedNamedReference: message = SR.Format(SR.MakeException, pattern, offset, SR.UndefinedNamedReferenceNoPlaceholder); break; case RegexParseError.UndefinedNumberedReference: message = SR.Format(SR.MakeException, pattern, offset, SR.UndefinedNumberedReferenceNoPlaceholder); break; case RegexParseError.MalformedNamedReference: message = SR.Format(SR.MakeException, pattern, offset, SR.MalformedNamedReference); break; case RegexParseError.UnescapedEndingBackslash: message = SR.Format(SR.MakeException, pattern, offset, SR.UnescapedEndingBackslash); break; case RegexParseError.UnterminatedComment: message = SR.Format(SR.MakeException, pattern, offset, SR.UnterminatedComment); break; case RegexParseError.InvalidGroupingConstruct: message = SR.Format(SR.MakeException, pattern, offset, SR.InvalidGroupingConstruct); break; case RegexParseError.AlternationHasNamedCapture: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasNamedCapture); break; case RegexParseError.AlternationHasComment: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasComment); break; case RegexParseError.AlternationHasMalformedReference: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasMalformedReferenceNoPlaceholder); break; case RegexParseError.AlternationHasUndefinedReference: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasUndefinedReferenceNoPlaceholder); break; case RegexParseError.CaptureGroupNameInvalid: message = SR.Format(SR.MakeException, pattern, offset, SR.CaptureGroupNameInvalid); break; case RegexParseError.CaptureGroupOfZero: message = SR.Format(SR.MakeException, pattern, offset, SR.CaptureGroupOfZero); break; case RegexParseError.UnterminatedBracket: message = SR.Format(SR.MakeException, pattern, offset, SR.UnterminatedBracket); break; case RegexParseError.ExclusionGroupNotLast: message = SR.Format(SR.MakeException, pattern, offset, SR.ExclusionGroupNotLast); break; case RegexParseError.ReversedCharacterRange: message = SR.Format(SR.MakeException, pattern, offset, SR.ReversedCharacterRange); break; case RegexParseError.ShorthandClassInCharacterRange: message = SR.Format(SR.MakeException, pattern, offset, SR.ShorthandClassInCharacterRangeNoPlaceholder); break; case RegexParseError.InsufficientClosingParentheses: message = SR.Format(SR.MakeException, pattern, offset, SR.InsufficientClosingParentheses); break; case RegexParseError.ReversedQuantifierRange: message = SR.Format(SR.MakeException, pattern, offset, SR.ReversedQuantifierRange); break; case RegexParseError.NestedQuantifiersNotParenthesized: message = SR.Format(SR.MakeException, pattern, offset, SR.NestedQuantifiersNotParenthesizedNoPlaceholder); break; case RegexParseError.QuantifierAfterNothing: message = SR.Format(SR.MakeException, pattern, offset, SR.QuantifierAfterNothing); break; case RegexParseError.InsufficientOpeningParentheses: message = SR.Format(SR.MakeException, pattern, offset, SR.InsufficientOpeningParentheses); break; case RegexParseError.UnrecognizedUnicodeProperty: message = SR.Format(SR.MakeException, pattern, offset, SR.UnrecognizedUnicodePropertyNoPlaceholder); break; default: message = SR.Format(SR.MakeException, pattern, offset, SR.Generic); break; } return message; } private RegexParseException(SerializationInfo info, StreamingContext context) { // It means someone modified the payload. throw new NotImplementedException(); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.SetType(typeof(ArgumentException)); // To maintain serialization support with .NET Framework. } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.Serialization; namespace System.Text.RegularExpressions { /// <summary> /// An exception as a result of a parse error in a regular expression <see cref="RegularExpressions"/>, with /// detailed information in the <see cref="Error"/> and <see cref="Offset"/> properties. /// </summary> [Serializable] #if REGEXGENERATOR internal #else public #endif sealed class RegexParseException : ArgumentException { /// <summary>Gets the error that happened during parsing.</summary> public RegexParseError Error { get; } /// <summary>Gets the zero-based character offset in the regular expression pattern where the parse error occurs.</summary> public int Offset { get; } internal RegexParseException(RegexParseError error, int offset, string message) : base(message) { Error = error; Offset = offset; } internal RegexParseException(string pattern, RegexParseError error, int offset) : base(MakeMessage(pattern, error, offset)) { Error = error; Offset = offset; } /// <summary> /// Construct a <see cref="RegexParseException"/> that creates a default message based on the given <see cref="RegexParseError"/> value. /// </summary> /// <param name="pattern">The pattern of the regular expression.</param> /// <param name="error">The <see cref="RegexParseError"/> value detailing the type of parse error.</param> /// <param name="offset">The zero-based offset in the regular expression where the parse error occurs.</param> private static string MakeMessage(string pattern, RegexParseError error, int offset) { string message; switch (error) { case RegexParseError.Unknown: message = SR.Format(SR.MakeException, pattern, offset, SR.Generic); break; case RegexParseError.AlternationHasTooManyConditions: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasTooManyConditions); break; case RegexParseError.AlternationHasMalformedCondition: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasMalformedCondition); break; case RegexParseError.InvalidUnicodePropertyEscape: message = SR.Format(SR.MakeException, pattern, offset, SR.InvalidUnicodePropertyEscape); break; case RegexParseError.MalformedUnicodePropertyEscape: message = SR.Format(SR.MakeException, pattern, offset, SR.MalformedUnicodePropertyEscape); break; case RegexParseError.UnrecognizedEscape: message = SR.Format(SR.MakeException, pattern, offset, SR.UnrecognizedEscape); break; case RegexParseError.UnrecognizedControlCharacter: message = SR.Format(SR.MakeException, pattern, offset, SR.UnrecognizedControlCharacter); break; case RegexParseError.MissingControlCharacter: message = SR.Format(SR.MakeException, pattern, offset, SR.MissingControlCharacter); break; case RegexParseError.InsufficientOrInvalidHexDigits: message = SR.Format(SR.MakeException, pattern, offset, SR.InsufficientOrInvalidHexDigits); break; case RegexParseError.QuantifierOrCaptureGroupOutOfRange: message = SR.Format(SR.MakeException, pattern, offset, SR.QuantifierOrCaptureGroupOutOfRange); break; case RegexParseError.UndefinedNamedReference: message = SR.Format(SR.MakeException, pattern, offset, SR.UndefinedNamedReferenceNoPlaceholder); break; case RegexParseError.UndefinedNumberedReference: message = SR.Format(SR.MakeException, pattern, offset, SR.UndefinedNumberedReferenceNoPlaceholder); break; case RegexParseError.MalformedNamedReference: message = SR.Format(SR.MakeException, pattern, offset, SR.MalformedNamedReference); break; case RegexParseError.UnescapedEndingBackslash: message = SR.Format(SR.MakeException, pattern, offset, SR.UnescapedEndingBackslash); break; case RegexParseError.UnterminatedComment: message = SR.Format(SR.MakeException, pattern, offset, SR.UnterminatedComment); break; case RegexParseError.InvalidGroupingConstruct: message = SR.Format(SR.MakeException, pattern, offset, SR.InvalidGroupingConstruct); break; case RegexParseError.AlternationHasNamedCapture: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasNamedCapture); break; case RegexParseError.AlternationHasComment: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasComment); break; case RegexParseError.AlternationHasMalformedReference: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasMalformedReferenceNoPlaceholder); break; case RegexParseError.AlternationHasUndefinedReference: message = SR.Format(SR.MakeException, pattern, offset, SR.AlternationHasUndefinedReferenceNoPlaceholder); break; case RegexParseError.CaptureGroupNameInvalid: message = SR.Format(SR.MakeException, pattern, offset, SR.CaptureGroupNameInvalid); break; case RegexParseError.CaptureGroupOfZero: message = SR.Format(SR.MakeException, pattern, offset, SR.CaptureGroupOfZero); break; case RegexParseError.UnterminatedBracket: message = SR.Format(SR.MakeException, pattern, offset, SR.UnterminatedBracket); break; case RegexParseError.ExclusionGroupNotLast: message = SR.Format(SR.MakeException, pattern, offset, SR.ExclusionGroupNotLast); break; case RegexParseError.ReversedCharacterRange: message = SR.Format(SR.MakeException, pattern, offset, SR.ReversedCharacterRange); break; case RegexParseError.ShorthandClassInCharacterRange: message = SR.Format(SR.MakeException, pattern, offset, SR.ShorthandClassInCharacterRangeNoPlaceholder); break; case RegexParseError.InsufficientClosingParentheses: message = SR.Format(SR.MakeException, pattern, offset, SR.InsufficientClosingParentheses); break; case RegexParseError.ReversedQuantifierRange: message = SR.Format(SR.MakeException, pattern, offset, SR.ReversedQuantifierRange); break; case RegexParseError.NestedQuantifiersNotParenthesized: message = SR.Format(SR.MakeException, pattern, offset, SR.NestedQuantifiersNotParenthesizedNoPlaceholder); break; case RegexParseError.QuantifierAfterNothing: message = SR.Format(SR.MakeException, pattern, offset, SR.QuantifierAfterNothing); break; case RegexParseError.InsufficientOpeningParentheses: message = SR.Format(SR.MakeException, pattern, offset, SR.InsufficientOpeningParentheses); break; case RegexParseError.UnrecognizedUnicodeProperty: message = SR.Format(SR.MakeException, pattern, offset, SR.UnrecognizedUnicodePropertyNoPlaceholder); break; default: message = SR.Format(SR.MakeException, pattern, offset, SR.Generic); break; } return message; } private RegexParseException(SerializationInfo info, StreamingContext context) { // It means someone modified the payload. throw new NotImplementedException(); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.SetType(typeof(ArgumentException)); // To maintain serialization support with .NET Framework. } } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.DirectoryServices.Protocols/ref/System.DirectoryServices.Protocols.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.DirectoryServices.Protocols { public partial class AddRequest : System.DirectoryServices.Protocols.DirectoryRequest { public AddRequest() { } public AddRequest(string distinguishedName, params System.DirectoryServices.Protocols.DirectoryAttribute[] attributes) { } public AddRequest(string distinguishedName, string objectClass) { } public System.DirectoryServices.Protocols.DirectoryAttributeCollection Attributes { get { throw null; } } public string DistinguishedName { get { throw null; } set { } } } public partial class AddResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal AddResponse() { } } public partial class AsqRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public AsqRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public AsqRequestControl(string attributeName) : base (default(string), default(byte[]), default(bool), default(bool)) { } public string AttributeName { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class AsqResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal AsqResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.ResultCode Result { get { throw null; } } } public enum AuthType { Anonymous = 0, Basic = 1, Negotiate = 2, Ntlm = 3, Digest = 4, Sicily = 5, Dpa = 6, Msn = 7, External = 8, Kerberos = 9, } public partial class BerConversionException : System.DirectoryServices.Protocols.DirectoryException { public BerConversionException() { } protected BerConversionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public BerConversionException(string message) { } public BerConversionException(string message, System.Exception inner) { } } public static partial class BerConverter { public static object[] Decode(string format, byte[] value) { throw null; } public static byte[] Encode(string format, params object[] value) { throw null; } } public partial class CompareRequest : System.DirectoryServices.Protocols.DirectoryRequest { public CompareRequest() { } public CompareRequest(string distinguishedName, System.DirectoryServices.Protocols.DirectoryAttribute assertion) { } public CompareRequest(string distinguishedName, string attributeName, byte[] value) { } public CompareRequest(string distinguishedName, string attributeName, string value) { } public CompareRequest(string distinguishedName, string attributeName, System.Uri value) { } public System.DirectoryServices.Protocols.DirectoryAttribute Assertion { get { throw null; } } public string DistinguishedName { get { throw null; } set { } } } public partial class CompareResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal CompareResponse() { } } public partial class CrossDomainMoveControl : System.DirectoryServices.Protocols.DirectoryControl { public CrossDomainMoveControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public CrossDomainMoveControl(string targetDomainController) : base (default(string), default(byte[]), default(bool), default(bool)) { } public string TargetDomainController { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class DeleteRequest : System.DirectoryServices.Protocols.DirectoryRequest { public DeleteRequest() { } public DeleteRequest(string distinguishedName) { } public string DistinguishedName { get { throw null; } set { } } } public partial class DeleteResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal DeleteResponse() { } } public enum DereferenceAlias { Never = 0, InSearching = 1, FindingBaseObject = 2, Always = 3, } public delegate void DereferenceConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection connectionToDereference); public partial class DirectoryAttribute : System.Collections.CollectionBase { public DirectoryAttribute() { } public DirectoryAttribute(string name, byte[] value) { } public DirectoryAttribute(string name, params object[] values) { } public DirectoryAttribute(string name, string value) { } public DirectoryAttribute(string name, System.Uri value) { } public object this[int index] { get { throw null; } set { } } public string Name { get { throw null; } set { } } public int Add(byte[] value) { throw null; } public int Add(string value) { throw null; } public int Add(System.Uri value) { throw null; } public void AddRange(object[] values) { } public bool Contains(object value) { throw null; } public void CopyTo(object[] array, int index) { } public object[] GetValues(System.Type valuesType) { throw null; } public int IndexOf(object value) { throw null; } public void Insert(int index, byte[] value) { } public void Insert(int index, string value) { } public void Insert(int index, System.Uri value) { } protected override void OnValidate(object value) { } public void Remove(object value) { } } public partial class DirectoryAttributeCollection : System.Collections.CollectionBase { public DirectoryAttributeCollection() { } public System.DirectoryServices.Protocols.DirectoryAttribute this[int index] { get { throw null; } set { } } public int Add(System.DirectoryServices.Protocols.DirectoryAttribute attribute) { throw null; } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeCollection attributeCollection) { } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttribute[] attributes) { } public bool Contains(System.DirectoryServices.Protocols.DirectoryAttribute value) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttribute[] array, int index) { } public int IndexOf(System.DirectoryServices.Protocols.DirectoryAttribute value) { throw null; } public void Insert(int index, System.DirectoryServices.Protocols.DirectoryAttribute value) { } protected override void OnValidate(object value) { } public void Remove(System.DirectoryServices.Protocols.DirectoryAttribute value) { } } public partial class DirectoryAttributeModification : System.DirectoryServices.Protocols.DirectoryAttribute { public DirectoryAttributeModification() { } public System.DirectoryServices.Protocols.DirectoryAttributeOperation Operation { get { throw null; } set { } } } public partial class DirectoryAttributeModificationCollection : System.Collections.CollectionBase { public DirectoryAttributeModificationCollection() { } public System.DirectoryServices.Protocols.DirectoryAttributeModification this[int index] { get { throw null; } set { } } public int Add(System.DirectoryServices.Protocols.DirectoryAttributeModification attribute) { throw null; } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeModificationCollection attributeCollection) { } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeModification[] attributes) { } public bool Contains(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttributeModification[] array, int index) { } public int IndexOf(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { throw null; } public void Insert(int index, System.DirectoryServices.Protocols.DirectoryAttributeModification value) { } protected override void OnValidate(object value) { } public void Remove(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { } } public enum DirectoryAttributeOperation { Add = 0, Delete = 1, Replace = 2, } public abstract partial class DirectoryConnection { protected DirectoryConnection() { } public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } } public virtual System.Net.NetworkCredential Credential { set { } } public virtual System.DirectoryServices.Protocols.DirectoryIdentifier Directory { get { throw null; } } public virtual System.TimeSpan Timeout { get { throw null; } set { } } public abstract System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request); } public partial class DirectoryControl { public DirectoryControl(string type, byte[] value, bool isCritical, bool serverSide) { } public bool IsCritical { get { throw null; } set { } } public bool ServerSide { get { throw null; } set { } } public string Type { get { throw null; } } public virtual byte[] GetValue() { throw null; } } public partial class DirectoryControlCollection : System.Collections.CollectionBase { public DirectoryControlCollection() { } public System.DirectoryServices.Protocols.DirectoryControl this[int index] { get { throw null; } set { } } public int Add(System.DirectoryServices.Protocols.DirectoryControl control) { throw null; } public void AddRange(System.DirectoryServices.Protocols.DirectoryControlCollection controlCollection) { } public void AddRange(System.DirectoryServices.Protocols.DirectoryControl[] controls) { } public bool Contains(System.DirectoryServices.Protocols.DirectoryControl value) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.DirectoryControl[] array, int index) { } public int IndexOf(System.DirectoryServices.Protocols.DirectoryControl value) { throw null; } public void Insert(int index, System.DirectoryServices.Protocols.DirectoryControl value) { } protected override void OnValidate(object value) { } public void Remove(System.DirectoryServices.Protocols.DirectoryControl value) { } } public partial class DirectoryException : System.Exception { public DirectoryException() { } protected DirectoryException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public DirectoryException(string message) { } public DirectoryException(string message, System.Exception inner) { } } public abstract partial class DirectoryIdentifier { protected DirectoryIdentifier() { } } public partial class DirectoryNotificationControl : System.DirectoryServices.Protocols.DirectoryControl { public DirectoryNotificationControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public abstract partial class DirectoryOperation { protected DirectoryOperation() { } } public partial class DirectoryOperationException : System.DirectoryServices.Protocols.DirectoryException, System.Runtime.Serialization.ISerializable { public DirectoryOperationException() { } public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response) { } public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message) { } public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message, System.Exception inner) { } protected DirectoryOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public DirectoryOperationException(string message) { } public DirectoryOperationException(string message, System.Exception inner) { } public System.DirectoryServices.Protocols.DirectoryResponse Response { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public abstract partial class DirectoryRequest : System.DirectoryServices.Protocols.DirectoryOperation { internal DirectoryRequest() { } public System.DirectoryServices.Protocols.DirectoryControlCollection Controls { get { throw null; } } public string RequestId { get { throw null; } set { } } } public abstract partial class DirectoryResponse : System.DirectoryServices.Protocols.DirectoryOperation { internal DirectoryResponse() { } public virtual System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } } public virtual string ErrorMessage { get { throw null; } } public virtual string MatchedDN { get { throw null; } } public virtual System.Uri[] Referral { get { throw null; } } public string RequestId { get { throw null; } } public virtual System.DirectoryServices.Protocols.ResultCode ResultCode { get { throw null; } } } [System.FlagsAttribute] public enum DirectorySynchronizationOptions : long { None = (long)0, ObjectSecurity = (long)1, ParentsFirst = (long)2048, PublicDataOnly = (long)8192, IncrementalValues = (long)2147483648, } public partial class DirSyncRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public DirSyncRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public DirSyncRequestControl(byte[] cookie) : base (default(string), default(byte[]), default(bool), default(bool)) { } public DirSyncRequestControl(byte[] cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions option) : base (default(string), default(byte[]), default(bool), default(bool)) { } public DirSyncRequestControl(byte[] cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions option, int attributeCount) : base (default(string), default(byte[]), default(bool), default(bool)) { } public int AttributeCount { get { throw null; } set { } } public byte[] Cookie { get { throw null; } set { } } public System.DirectoryServices.Protocols.DirectorySynchronizationOptions Option { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class DirSyncResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal DirSyncResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public byte[] Cookie { get { throw null; } } public bool MoreData { get { throw null; } } public int ResultSize { get { throw null; } } } public partial class DomainScopeControl : System.DirectoryServices.Protocols.DirectoryControl { public DomainScopeControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class DsmlAuthRequest : System.DirectoryServices.Protocols.DirectoryRequest { public DsmlAuthRequest() { } public DsmlAuthRequest(string principal) { } public string Principal { get { throw null; } set { } } } public partial class ExtendedDNControl : System.DirectoryServices.Protocols.DirectoryControl { public ExtendedDNControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public ExtendedDNControl(System.DirectoryServices.Protocols.ExtendedDNFlag flag) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.ExtendedDNFlag Flag { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public enum ExtendedDNFlag { HexString = 0, StandardString = 1, } public partial class ExtendedRequest : System.DirectoryServices.Protocols.DirectoryRequest { public ExtendedRequest() { } public ExtendedRequest(string requestName) { } public ExtendedRequest(string requestName, byte[] requestValue) { } public string RequestName { get { throw null; } set { } } public byte[] RequestValue { get { throw null; } set { } } } public partial class ExtendedResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal ExtendedResponse() { } public string ResponseName { get { throw null; } } public byte[] ResponseValue { get { throw null; } } } public partial class LazyCommitControl : System.DirectoryServices.Protocols.DirectoryControl { public LazyCommitControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class LdapConnection : System.DirectoryServices.Protocols.DirectoryConnection, System.IDisposable { public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier) { } public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential) { } public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential, System.DirectoryServices.Protocols.AuthType authType) { } public LdapConnection(string server) { } public System.DirectoryServices.Protocols.AuthType AuthType { get { throw null; } set { } } public bool AutoBind { get { throw null; } set { } } public override System.Net.NetworkCredential Credential { set { } } public System.DirectoryServices.Protocols.LdapSessionOptions SessionOptions { get { throw null; } } public override System.TimeSpan Timeout { get { throw null; } set { } } public void Abort(System.IAsyncResult asyncResult) { } public System.IAsyncResult BeginSendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.DirectoryServices.Protocols.PartialResultProcessing partialMode, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginSendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.TimeSpan requestTimeout, System.DirectoryServices.Protocols.PartialResultProcessing partialMode, System.AsyncCallback callback, object state) { throw null; } public void Bind() { } public void Bind(System.Net.NetworkCredential newCredential) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.DirectoryServices.Protocols.DirectoryResponse EndSendRequest(System.IAsyncResult asyncResult) { throw null; } ~LdapConnection() { } public System.DirectoryServices.Protocols.PartialResultsCollection GetPartialResults(System.IAsyncResult asyncResult) { throw null; } public override System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request) { throw null; } public System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.TimeSpan requestTimeout) { throw null; } } public partial class LdapDirectoryIdentifier : System.DirectoryServices.Protocols.DirectoryIdentifier { public LdapDirectoryIdentifier(string server) { } public LdapDirectoryIdentifier(string server, bool fullyQualifiedDnsHostName, bool connectionless) { } public LdapDirectoryIdentifier(string server, int portNumber) { } public LdapDirectoryIdentifier(string server, int portNumber, bool fullyQualifiedDnsHostName, bool connectionless) { } public LdapDirectoryIdentifier(string[] servers, bool fullyQualifiedDnsHostName, bool connectionless) { } public LdapDirectoryIdentifier(string[] servers, int portNumber, bool fullyQualifiedDnsHostName, bool connectionless) { } public bool Connectionless { get { throw null; } } public bool FullyQualifiedDnsHostName { get { throw null; } } public int PortNumber { get { throw null; } } public string[] Servers { get { throw null; } } } public partial class LdapException : System.DirectoryServices.Protocols.DirectoryException, System.Runtime.Serialization.ISerializable { public LdapException() { } public LdapException(int errorCode) { } public LdapException(int errorCode, string message) { } public LdapException(int errorCode, string message, System.Exception inner) { } public LdapException(int errorCode, string message, string serverErrorMessage) { } protected LdapException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public LdapException(string message) { } public LdapException(string message, System.Exception inner) { } public int ErrorCode { get { throw null; } } public System.DirectoryServices.Protocols.PartialResultsCollection PartialResults { get { throw null; } } public string ServerErrorMessage { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public partial class LdapSessionOptions { internal LdapSessionOptions() { } public bool AutoReconnect { get { throw null; } set { } } public string DomainName { get { throw null; } set { } } public string HostName { get { throw null; } set { } } public bool HostReachable { get { throw null; } } public System.DirectoryServices.Protocols.LocatorFlags LocatorFlag { get { throw null; } set { } } public System.TimeSpan PingKeepAliveTimeout { get { throw null; } set { } } public int PingLimit { get { throw null; } set { } } public System.TimeSpan PingWaitTimeout { get { throw null; } set { } } public int ProtocolVersion { get { throw null; } set { } } public System.DirectoryServices.Protocols.QueryClientCertificateCallback QueryClientCertificate { get { throw null; } set { } } public System.DirectoryServices.Protocols.ReferralCallback ReferralCallback { get { throw null; } set { } } public System.DirectoryServices.Protocols.ReferralChasingOptions ReferralChasing { get { throw null; } set { } } public int ReferralHopLimit { get { throw null; } set { } } public bool RootDseCache { get { throw null; } set { } } public string SaslMethod { get { throw null; } set { } } public bool Sealing { get { throw null; } set { } } public bool SecureSocketLayer { get { throw null; } set { } } public object SecurityContext { get { throw null; } } public System.TimeSpan SendTimeout { get { throw null; } set { } } public bool Signing { get { throw null; } set { } } public System.DirectoryServices.Protocols.SecurityPackageContextConnectionInformation SslInformation { get { throw null; } } public int SspiFlag { get { throw null; } set { } } public bool TcpKeepAlive { get { throw null; } set { } } public System.DirectoryServices.Protocols.VerifyServerCertificateCallback VerifyServerCertificate { get { throw null; } set { } } public void FastConcurrentBind() { } public void StartTransportLayerSecurity(System.DirectoryServices.Protocols.DirectoryControlCollection controls) { } public void StopTransportLayerSecurity() { } } [System.FlagsAttribute] public enum LocatorFlags : long { None = (long)0, ForceRediscovery = (long)1, DirectoryServicesRequired = (long)16, DirectoryServicesPreferred = (long)32, GCRequired = (long)64, PdcRequired = (long)128, IPRequired = (long)512, KdcRequired = (long)1024, TimeServerRequired = (long)2048, WriteableRequired = (long)4096, GoodTimeServerPreferred = (long)8192, AvoidSelf = (long)16384, OnlyLdapNeeded = (long)32768, IsFlatName = (long)65536, IsDnsName = (long)131072, ReturnDnsName = (long)1073741824, ReturnFlatName = (long)2147483648, } public partial class ModifyDNRequest : System.DirectoryServices.Protocols.DirectoryRequest { public ModifyDNRequest() { } public ModifyDNRequest(string distinguishedName, string newParentDistinguishedName, string newName) { } public bool DeleteOldRdn { get { throw null; } set { } } public string DistinguishedName { get { throw null; } set { } } public string NewName { get { throw null; } set { } } public string NewParentDistinguishedName { get { throw null; } set { } } } public partial class ModifyDNResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal ModifyDNResponse() { } } public partial class ModifyRequest : System.DirectoryServices.Protocols.DirectoryRequest { public ModifyRequest() { } public ModifyRequest(string distinguishedName, params System.DirectoryServices.Protocols.DirectoryAttributeModification[] modifications) { } public ModifyRequest(string distinguishedName, System.DirectoryServices.Protocols.DirectoryAttributeOperation operation, string attributeName, params object[] values) { } public string DistinguishedName { get { throw null; } set { } } public System.DirectoryServices.Protocols.DirectoryAttributeModificationCollection Modifications { get { throw null; } } } public partial class ModifyResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal ModifyResponse() { } } public delegate bool NotifyOfNewConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection referralFromConnection, string newDistinguishedName, System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.DirectoryServices.Protocols.LdapConnection newConnection, System.Net.NetworkCredential credential, long currentUserToken, int errorCodeFromBind); public partial class PageResultRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public PageResultRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public PageResultRequestControl(byte[] cookie) : base (default(string), default(byte[]), default(bool), default(bool)) { } public PageResultRequestControl(int pageSize) : base (default(string), default(byte[]), default(bool), default(bool)) { } public byte[] Cookie { get { throw null; } set { } } public int PageSize { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class PageResultResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal PageResultResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public byte[] Cookie { get { throw null; } } public int TotalCount { get { throw null; } } } public enum PartialResultProcessing { NoPartialResultSupport = 0, ReturnPartialResults = 1, ReturnPartialResultsAndNotifyCallback = 2, } public partial class PartialResultsCollection : System.Collections.ReadOnlyCollectionBase { internal PartialResultsCollection() { } public object this[int index] { get { throw null; } } public bool Contains(object value) { throw null; } public void CopyTo(object[] values, int index) { } public int IndexOf(object value) { throw null; } } public partial class PermissiveModifyControl : System.DirectoryServices.Protocols.DirectoryControl { public PermissiveModifyControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public delegate System.Security.Cryptography.X509Certificates.X509Certificate QueryClientCertificateCallback(System.DirectoryServices.Protocols.LdapConnection connection, byte[][] trustedCAs); public delegate System.DirectoryServices.Protocols.LdapConnection QueryForConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection referralFromConnection, string newDistinguishedName, System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential, long currentUserToken); [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public partial class QuotaControl : System.DirectoryServices.Protocols.DirectoryControl { public QuotaControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public QuotaControl(System.Security.Principal.SecurityIdentifier querySid) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.Security.Principal.SecurityIdentifier QuerySid { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public sealed partial class ReferralCallback { public ReferralCallback() { } public System.DirectoryServices.Protocols.DereferenceConnectionCallback DereferenceConnection { get { throw null; } set { } } public System.DirectoryServices.Protocols.NotifyOfNewConnectionCallback NotifyNewConnection { get { throw null; } set { } } public System.DirectoryServices.Protocols.QueryForConnectionCallback QueryForConnection { get { throw null; } set { } } } [System.FlagsAttribute] public enum ReferralChasingOptions { None = 0, Subordinate = 32, External = 64, All = 96, } public enum ResultCode { Success = 0, OperationsError = 1, ProtocolError = 2, TimeLimitExceeded = 3, SizeLimitExceeded = 4, CompareFalse = 5, CompareTrue = 6, AuthMethodNotSupported = 7, StrongAuthRequired = 8, ReferralV2 = 9, Referral = 10, AdminLimitExceeded = 11, UnavailableCriticalExtension = 12, ConfidentialityRequired = 13, SaslBindInProgress = 14, NoSuchAttribute = 16, UndefinedAttributeType = 17, InappropriateMatching = 18, ConstraintViolation = 19, AttributeOrValueExists = 20, InvalidAttributeSyntax = 21, NoSuchObject = 32, AliasProblem = 33, InvalidDNSyntax = 34, AliasDereferencingProblem = 36, InappropriateAuthentication = 48, InsufficientAccessRights = 50, Busy = 51, Unavailable = 52, UnwillingToPerform = 53, LoopDetect = 54, SortControlMissing = 60, OffsetRangeError = 61, NamingViolation = 64, ObjectClassViolation = 65, NotAllowedOnNonLeaf = 66, NotAllowedOnRdn = 67, EntryAlreadyExists = 68, ObjectClassModificationsProhibited = 69, ResultsTooLarge = 70, AffectsMultipleDsas = 71, VirtualListViewError = 76, Other = 80, } public enum SearchOption { DomainScope = 1, PhantomRoot = 2, } public partial class SearchOptionsControl : System.DirectoryServices.Protocols.DirectoryControl { public SearchOptionsControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption flags) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.SearchOption SearchOption { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class SearchRequest : System.DirectoryServices.Protocols.DirectoryRequest { public SearchRequest() { } public SearchRequest(string distinguishedName, string ldapFilter, System.DirectoryServices.Protocols.SearchScope searchScope, params string[] attributeList) { } public System.DirectoryServices.Protocols.DereferenceAlias Aliases { get { throw null; } set { } } public System.Collections.Specialized.StringCollection Attributes { get { throw null; } } public string DistinguishedName { get { throw null; } set { } } public object Filter { get { throw null; } set { } } public System.DirectoryServices.Protocols.SearchScope Scope { get { throw null; } set { } } public int SizeLimit { get { throw null; } set { } } public System.TimeSpan TimeLimit { get { throw null; } set { } } public bool TypesOnly { get { throw null; } set { } } } public partial class SearchResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal SearchResponse() { } public override System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } } public System.DirectoryServices.Protocols.SearchResultEntryCollection Entries { get { throw null; } } public override string ErrorMessage { get { throw null; } } public override string MatchedDN { get { throw null; } } public System.DirectoryServices.Protocols.SearchResultReferenceCollection References { get { throw null; } } public override System.Uri[] Referral { get { throw null; } } public override System.DirectoryServices.Protocols.ResultCode ResultCode { get { throw null; } } } public partial class SearchResultAttributeCollection : System.Collections.DictionaryBase { internal SearchResultAttributeCollection() { } public System.Collections.ICollection AttributeNames { get { throw null; } } public System.DirectoryServices.Protocols.DirectoryAttribute this[string attributeName] { get { throw null; } } public System.Collections.ICollection Values { get { throw null; } } public bool Contains(string attributeName) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttribute[] array, int index) { } } public partial class SearchResultEntry { internal SearchResultEntry() { } public System.DirectoryServices.Protocols.SearchResultAttributeCollection Attributes { get { throw null; } } public System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } } public string DistinguishedName { get { throw null; } } } public partial class SearchResultEntryCollection : System.Collections.ReadOnlyCollectionBase { internal SearchResultEntryCollection() { } public System.DirectoryServices.Protocols.SearchResultEntry this[int index] { get { throw null; } } public bool Contains(System.DirectoryServices.Protocols.SearchResultEntry value) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.SearchResultEntry[] values, int index) { } public int IndexOf(System.DirectoryServices.Protocols.SearchResultEntry value) { throw null; } } public partial class SearchResultReference { internal SearchResultReference() { } public System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } } public System.Uri[] Reference { get { throw null; } } } public partial class SearchResultReferenceCollection : System.Collections.ReadOnlyCollectionBase { internal SearchResultReferenceCollection() { } public System.DirectoryServices.Protocols.SearchResultReference this[int index] { get { throw null; } } public bool Contains(System.DirectoryServices.Protocols.SearchResultReference value) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.SearchResultReference[] values, int index) { } public int IndexOf(System.DirectoryServices.Protocols.SearchResultReference value) { throw null; } } public enum SearchScope { Base = 0, OneLevel = 1, Subtree = 2, } public partial class SecurityDescriptorFlagControl : System.DirectoryServices.Protocols.DirectoryControl { public SecurityDescriptorFlagControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public SecurityDescriptorFlagControl(System.DirectoryServices.Protocols.SecurityMasks masks) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.SecurityMasks SecurityMasks { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } [System.FlagsAttribute] public enum SecurityMasks { None = 0, Owner = 1, Group = 2, Dacl = 4, Sacl = 8, } public partial class SecurityPackageContextConnectionInformation { internal SecurityPackageContextConnectionInformation() { } public System.Security.Authentication.CipherAlgorithmType AlgorithmIdentifier { get { throw null; } } public int CipherStrength { get { throw null; } } public int ExchangeStrength { get { throw null; } } public System.Security.Authentication.HashAlgorithmType Hash { get { throw null; } } public int HashStrength { get { throw null; } } public int KeyExchangeAlgorithm { get { throw null; } } public System.DirectoryServices.Protocols.SecurityProtocol Protocol { get { throw null; } } } public enum SecurityProtocol { Pct1Server = 1, Pct1Client = 2, Ssl2Server = 4, Ssl2Client = 8, Ssl3Server = 16, Ssl3Client = 32, Tls1Server = 64, Tls1Client = 128, } public partial class ShowDeletedControl : System.DirectoryServices.Protocols.DirectoryControl { public ShowDeletedControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class SortKey { public SortKey() { } public SortKey(string attributeName, string matchingRule, bool reverseOrder) { } public string AttributeName { get { throw null; } set { } } public string MatchingRule { get { throw null; } set { } } public bool ReverseOrder { get { throw null; } set { } } } public partial class SortRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public SortRequestControl(params System.DirectoryServices.Protocols.SortKey[] sortKeys) : base (default(string), default(byte[]), default(bool), default(bool)) { } public SortRequestControl(string attributeName, bool reverseOrder) : base (default(string), default(byte[]), default(bool), default(bool)) { } public SortRequestControl(string attributeName, string matchingRule, bool reverseOrder) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.SortKey[] SortKeys { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class SortResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal SortResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public string AttributeName { get { throw null; } } public System.DirectoryServices.Protocols.ResultCode Result { get { throw null; } } } public partial class TlsOperationException : System.DirectoryServices.Protocols.DirectoryOperationException { public TlsOperationException() { } public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response) { } public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message) { } public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message, System.Exception inner) { } protected TlsOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TlsOperationException(string message) { } public TlsOperationException(string message, System.Exception inner) { } } public partial class TreeDeleteControl : System.DirectoryServices.Protocols.DirectoryControl { public TreeDeleteControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class VerifyNameControl : System.DirectoryServices.Protocols.DirectoryControl { public VerifyNameControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public VerifyNameControl(string serverName) : base (default(string), default(byte[]), default(bool), default(bool)) { } public VerifyNameControl(string serverName, int flag) : base (default(string), default(byte[]), default(bool), default(bool)) { } public int Flag { get { throw null; } set { } } public string ServerName { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public delegate bool VerifyServerCertificateCallback(System.DirectoryServices.Protocols.LdapConnection connection, System.Security.Cryptography.X509Certificates.X509Certificate certificate); public partial class VlvRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public VlvRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public VlvRequestControl(int beforeCount, int afterCount, byte[] target) : base (default(string), default(byte[]), default(bool), default(bool)) { } public VlvRequestControl(int beforeCount, int afterCount, int offset) : base (default(string), default(byte[]), default(bool), default(bool)) { } public VlvRequestControl(int beforeCount, int afterCount, string target) : base (default(string), default(byte[]), default(bool), default(bool)) { } public int AfterCount { get { throw null; } set { } } public int BeforeCount { get { throw null; } set { } } public byte[] ContextId { get { throw null; } set { } } public int EstimateCount { get { throw null; } set { } } public int Offset { get { throw null; } set { } } public byte[] Target { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class VlvResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal VlvResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public int ContentCount { get { throw null; } } public byte[] ContextId { get { throw null; } } public System.DirectoryServices.Protocols.ResultCode Result { get { throw null; } } public int TargetPosition { get { throw null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.DirectoryServices.Protocols { public partial class AddRequest : System.DirectoryServices.Protocols.DirectoryRequest { public AddRequest() { } public AddRequest(string distinguishedName, params System.DirectoryServices.Protocols.DirectoryAttribute[] attributes) { } public AddRequest(string distinguishedName, string objectClass) { } public System.DirectoryServices.Protocols.DirectoryAttributeCollection Attributes { get { throw null; } } public string DistinguishedName { get { throw null; } set { } } } public partial class AddResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal AddResponse() { } } public partial class AsqRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public AsqRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public AsqRequestControl(string attributeName) : base (default(string), default(byte[]), default(bool), default(bool)) { } public string AttributeName { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class AsqResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal AsqResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.ResultCode Result { get { throw null; } } } public enum AuthType { Anonymous = 0, Basic = 1, Negotiate = 2, Ntlm = 3, Digest = 4, Sicily = 5, Dpa = 6, Msn = 7, External = 8, Kerberos = 9, } public partial class BerConversionException : System.DirectoryServices.Protocols.DirectoryException { public BerConversionException() { } protected BerConversionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public BerConversionException(string message) { } public BerConversionException(string message, System.Exception inner) { } } public static partial class BerConverter { public static object[] Decode(string format, byte[] value) { throw null; } public static byte[] Encode(string format, params object[] value) { throw null; } } public partial class CompareRequest : System.DirectoryServices.Protocols.DirectoryRequest { public CompareRequest() { } public CompareRequest(string distinguishedName, System.DirectoryServices.Protocols.DirectoryAttribute assertion) { } public CompareRequest(string distinguishedName, string attributeName, byte[] value) { } public CompareRequest(string distinguishedName, string attributeName, string value) { } public CompareRequest(string distinguishedName, string attributeName, System.Uri value) { } public System.DirectoryServices.Protocols.DirectoryAttribute Assertion { get { throw null; } } public string DistinguishedName { get { throw null; } set { } } } public partial class CompareResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal CompareResponse() { } } public partial class CrossDomainMoveControl : System.DirectoryServices.Protocols.DirectoryControl { public CrossDomainMoveControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public CrossDomainMoveControl(string targetDomainController) : base (default(string), default(byte[]), default(bool), default(bool)) { } public string TargetDomainController { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class DeleteRequest : System.DirectoryServices.Protocols.DirectoryRequest { public DeleteRequest() { } public DeleteRequest(string distinguishedName) { } public string DistinguishedName { get { throw null; } set { } } } public partial class DeleteResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal DeleteResponse() { } } public enum DereferenceAlias { Never = 0, InSearching = 1, FindingBaseObject = 2, Always = 3, } public delegate void DereferenceConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection connectionToDereference); public partial class DirectoryAttribute : System.Collections.CollectionBase { public DirectoryAttribute() { } public DirectoryAttribute(string name, byte[] value) { } public DirectoryAttribute(string name, params object[] values) { } public DirectoryAttribute(string name, string value) { } public DirectoryAttribute(string name, System.Uri value) { } public object this[int index] { get { throw null; } set { } } public string Name { get { throw null; } set { } } public int Add(byte[] value) { throw null; } public int Add(string value) { throw null; } public int Add(System.Uri value) { throw null; } public void AddRange(object[] values) { } public bool Contains(object value) { throw null; } public void CopyTo(object[] array, int index) { } public object[] GetValues(System.Type valuesType) { throw null; } public int IndexOf(object value) { throw null; } public void Insert(int index, byte[] value) { } public void Insert(int index, string value) { } public void Insert(int index, System.Uri value) { } protected override void OnValidate(object value) { } public void Remove(object value) { } } public partial class DirectoryAttributeCollection : System.Collections.CollectionBase { public DirectoryAttributeCollection() { } public System.DirectoryServices.Protocols.DirectoryAttribute this[int index] { get { throw null; } set { } } public int Add(System.DirectoryServices.Protocols.DirectoryAttribute attribute) { throw null; } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeCollection attributeCollection) { } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttribute[] attributes) { } public bool Contains(System.DirectoryServices.Protocols.DirectoryAttribute value) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttribute[] array, int index) { } public int IndexOf(System.DirectoryServices.Protocols.DirectoryAttribute value) { throw null; } public void Insert(int index, System.DirectoryServices.Protocols.DirectoryAttribute value) { } protected override void OnValidate(object value) { } public void Remove(System.DirectoryServices.Protocols.DirectoryAttribute value) { } } public partial class DirectoryAttributeModification : System.DirectoryServices.Protocols.DirectoryAttribute { public DirectoryAttributeModification() { } public System.DirectoryServices.Protocols.DirectoryAttributeOperation Operation { get { throw null; } set { } } } public partial class DirectoryAttributeModificationCollection : System.Collections.CollectionBase { public DirectoryAttributeModificationCollection() { } public System.DirectoryServices.Protocols.DirectoryAttributeModification this[int index] { get { throw null; } set { } } public int Add(System.DirectoryServices.Protocols.DirectoryAttributeModification attribute) { throw null; } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeModificationCollection attributeCollection) { } public void AddRange(System.DirectoryServices.Protocols.DirectoryAttributeModification[] attributes) { } public bool Contains(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttributeModification[] array, int index) { } public int IndexOf(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { throw null; } public void Insert(int index, System.DirectoryServices.Protocols.DirectoryAttributeModification value) { } protected override void OnValidate(object value) { } public void Remove(System.DirectoryServices.Protocols.DirectoryAttributeModification value) { } } public enum DirectoryAttributeOperation { Add = 0, Delete = 1, Replace = 2, } public abstract partial class DirectoryConnection { protected DirectoryConnection() { } public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } } public virtual System.Net.NetworkCredential Credential { set { } } public virtual System.DirectoryServices.Protocols.DirectoryIdentifier Directory { get { throw null; } } public virtual System.TimeSpan Timeout { get { throw null; } set { } } public abstract System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request); } public partial class DirectoryControl { public DirectoryControl(string type, byte[] value, bool isCritical, bool serverSide) { } public bool IsCritical { get { throw null; } set { } } public bool ServerSide { get { throw null; } set { } } public string Type { get { throw null; } } public virtual byte[] GetValue() { throw null; } } public partial class DirectoryControlCollection : System.Collections.CollectionBase { public DirectoryControlCollection() { } public System.DirectoryServices.Protocols.DirectoryControl this[int index] { get { throw null; } set { } } public int Add(System.DirectoryServices.Protocols.DirectoryControl control) { throw null; } public void AddRange(System.DirectoryServices.Protocols.DirectoryControlCollection controlCollection) { } public void AddRange(System.DirectoryServices.Protocols.DirectoryControl[] controls) { } public bool Contains(System.DirectoryServices.Protocols.DirectoryControl value) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.DirectoryControl[] array, int index) { } public int IndexOf(System.DirectoryServices.Protocols.DirectoryControl value) { throw null; } public void Insert(int index, System.DirectoryServices.Protocols.DirectoryControl value) { } protected override void OnValidate(object value) { } public void Remove(System.DirectoryServices.Protocols.DirectoryControl value) { } } public partial class DirectoryException : System.Exception { public DirectoryException() { } protected DirectoryException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public DirectoryException(string message) { } public DirectoryException(string message, System.Exception inner) { } } public abstract partial class DirectoryIdentifier { protected DirectoryIdentifier() { } } public partial class DirectoryNotificationControl : System.DirectoryServices.Protocols.DirectoryControl { public DirectoryNotificationControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public abstract partial class DirectoryOperation { protected DirectoryOperation() { } } public partial class DirectoryOperationException : System.DirectoryServices.Protocols.DirectoryException, System.Runtime.Serialization.ISerializable { public DirectoryOperationException() { } public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response) { } public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message) { } public DirectoryOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message, System.Exception inner) { } protected DirectoryOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public DirectoryOperationException(string message) { } public DirectoryOperationException(string message, System.Exception inner) { } public System.DirectoryServices.Protocols.DirectoryResponse Response { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public abstract partial class DirectoryRequest : System.DirectoryServices.Protocols.DirectoryOperation { internal DirectoryRequest() { } public System.DirectoryServices.Protocols.DirectoryControlCollection Controls { get { throw null; } } public string RequestId { get { throw null; } set { } } } public abstract partial class DirectoryResponse : System.DirectoryServices.Protocols.DirectoryOperation { internal DirectoryResponse() { } public virtual System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } } public virtual string ErrorMessage { get { throw null; } } public virtual string MatchedDN { get { throw null; } } public virtual System.Uri[] Referral { get { throw null; } } public string RequestId { get { throw null; } } public virtual System.DirectoryServices.Protocols.ResultCode ResultCode { get { throw null; } } } [System.FlagsAttribute] public enum DirectorySynchronizationOptions : long { None = (long)0, ObjectSecurity = (long)1, ParentsFirst = (long)2048, PublicDataOnly = (long)8192, IncrementalValues = (long)2147483648, } public partial class DirSyncRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public DirSyncRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public DirSyncRequestControl(byte[] cookie) : base (default(string), default(byte[]), default(bool), default(bool)) { } public DirSyncRequestControl(byte[] cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions option) : base (default(string), default(byte[]), default(bool), default(bool)) { } public DirSyncRequestControl(byte[] cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions option, int attributeCount) : base (default(string), default(byte[]), default(bool), default(bool)) { } public int AttributeCount { get { throw null; } set { } } public byte[] Cookie { get { throw null; } set { } } public System.DirectoryServices.Protocols.DirectorySynchronizationOptions Option { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class DirSyncResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal DirSyncResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public byte[] Cookie { get { throw null; } } public bool MoreData { get { throw null; } } public int ResultSize { get { throw null; } } } public partial class DomainScopeControl : System.DirectoryServices.Protocols.DirectoryControl { public DomainScopeControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class DsmlAuthRequest : System.DirectoryServices.Protocols.DirectoryRequest { public DsmlAuthRequest() { } public DsmlAuthRequest(string principal) { } public string Principal { get { throw null; } set { } } } public partial class ExtendedDNControl : System.DirectoryServices.Protocols.DirectoryControl { public ExtendedDNControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public ExtendedDNControl(System.DirectoryServices.Protocols.ExtendedDNFlag flag) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.ExtendedDNFlag Flag { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public enum ExtendedDNFlag { HexString = 0, StandardString = 1, } public partial class ExtendedRequest : System.DirectoryServices.Protocols.DirectoryRequest { public ExtendedRequest() { } public ExtendedRequest(string requestName) { } public ExtendedRequest(string requestName, byte[] requestValue) { } public string RequestName { get { throw null; } set { } } public byte[] RequestValue { get { throw null; } set { } } } public partial class ExtendedResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal ExtendedResponse() { } public string ResponseName { get { throw null; } } public byte[] ResponseValue { get { throw null; } } } public partial class LazyCommitControl : System.DirectoryServices.Protocols.DirectoryControl { public LazyCommitControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class LdapConnection : System.DirectoryServices.Protocols.DirectoryConnection, System.IDisposable { public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier) { } public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential) { } public LdapConnection(System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential, System.DirectoryServices.Protocols.AuthType authType) { } public LdapConnection(string server) { } public System.DirectoryServices.Protocols.AuthType AuthType { get { throw null; } set { } } public bool AutoBind { get { throw null; } set { } } public override System.Net.NetworkCredential Credential { set { } } public System.DirectoryServices.Protocols.LdapSessionOptions SessionOptions { get { throw null; } } public override System.TimeSpan Timeout { get { throw null; } set { } } public void Abort(System.IAsyncResult asyncResult) { } public System.IAsyncResult BeginSendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.DirectoryServices.Protocols.PartialResultProcessing partialMode, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginSendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.TimeSpan requestTimeout, System.DirectoryServices.Protocols.PartialResultProcessing partialMode, System.AsyncCallback callback, object state) { throw null; } public void Bind() { } public void Bind(System.Net.NetworkCredential newCredential) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.DirectoryServices.Protocols.DirectoryResponse EndSendRequest(System.IAsyncResult asyncResult) { throw null; } ~LdapConnection() { } public System.DirectoryServices.Protocols.PartialResultsCollection GetPartialResults(System.IAsyncResult asyncResult) { throw null; } public override System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request) { throw null; } public System.DirectoryServices.Protocols.DirectoryResponse SendRequest(System.DirectoryServices.Protocols.DirectoryRequest request, System.TimeSpan requestTimeout) { throw null; } } public partial class LdapDirectoryIdentifier : System.DirectoryServices.Protocols.DirectoryIdentifier { public LdapDirectoryIdentifier(string server) { } public LdapDirectoryIdentifier(string server, bool fullyQualifiedDnsHostName, bool connectionless) { } public LdapDirectoryIdentifier(string server, int portNumber) { } public LdapDirectoryIdentifier(string server, int portNumber, bool fullyQualifiedDnsHostName, bool connectionless) { } public LdapDirectoryIdentifier(string[] servers, bool fullyQualifiedDnsHostName, bool connectionless) { } public LdapDirectoryIdentifier(string[] servers, int portNumber, bool fullyQualifiedDnsHostName, bool connectionless) { } public bool Connectionless { get { throw null; } } public bool FullyQualifiedDnsHostName { get { throw null; } } public int PortNumber { get { throw null; } } public string[] Servers { get { throw null; } } } public partial class LdapException : System.DirectoryServices.Protocols.DirectoryException, System.Runtime.Serialization.ISerializable { public LdapException() { } public LdapException(int errorCode) { } public LdapException(int errorCode, string message) { } public LdapException(int errorCode, string message, System.Exception inner) { } public LdapException(int errorCode, string message, string serverErrorMessage) { } protected LdapException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public LdapException(string message) { } public LdapException(string message, System.Exception inner) { } public int ErrorCode { get { throw null; } } public System.DirectoryServices.Protocols.PartialResultsCollection PartialResults { get { throw null; } } public string ServerErrorMessage { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public partial class LdapSessionOptions { internal LdapSessionOptions() { } public bool AutoReconnect { get { throw null; } set { } } public string DomainName { get { throw null; } set { } } public string HostName { get { throw null; } set { } } public bool HostReachable { get { throw null; } } public System.DirectoryServices.Protocols.LocatorFlags LocatorFlag { get { throw null; } set { } } public System.TimeSpan PingKeepAliveTimeout { get { throw null; } set { } } public int PingLimit { get { throw null; } set { } } public System.TimeSpan PingWaitTimeout { get { throw null; } set { } } public int ProtocolVersion { get { throw null; } set { } } public System.DirectoryServices.Protocols.QueryClientCertificateCallback QueryClientCertificate { get { throw null; } set { } } public System.DirectoryServices.Protocols.ReferralCallback ReferralCallback { get { throw null; } set { } } public System.DirectoryServices.Protocols.ReferralChasingOptions ReferralChasing { get { throw null; } set { } } public int ReferralHopLimit { get { throw null; } set { } } public bool RootDseCache { get { throw null; } set { } } public string SaslMethod { get { throw null; } set { } } public bool Sealing { get { throw null; } set { } } public bool SecureSocketLayer { get { throw null; } set { } } public object SecurityContext { get { throw null; } } public System.TimeSpan SendTimeout { get { throw null; } set { } } public bool Signing { get { throw null; } set { } } public System.DirectoryServices.Protocols.SecurityPackageContextConnectionInformation SslInformation { get { throw null; } } public int SspiFlag { get { throw null; } set { } } public bool TcpKeepAlive { get { throw null; } set { } } public System.DirectoryServices.Protocols.VerifyServerCertificateCallback VerifyServerCertificate { get { throw null; } set { } } public void FastConcurrentBind() { } public void StartTransportLayerSecurity(System.DirectoryServices.Protocols.DirectoryControlCollection controls) { } public void StopTransportLayerSecurity() { } } [System.FlagsAttribute] public enum LocatorFlags : long { None = (long)0, ForceRediscovery = (long)1, DirectoryServicesRequired = (long)16, DirectoryServicesPreferred = (long)32, GCRequired = (long)64, PdcRequired = (long)128, IPRequired = (long)512, KdcRequired = (long)1024, TimeServerRequired = (long)2048, WriteableRequired = (long)4096, GoodTimeServerPreferred = (long)8192, AvoidSelf = (long)16384, OnlyLdapNeeded = (long)32768, IsFlatName = (long)65536, IsDnsName = (long)131072, ReturnDnsName = (long)1073741824, ReturnFlatName = (long)2147483648, } public partial class ModifyDNRequest : System.DirectoryServices.Protocols.DirectoryRequest { public ModifyDNRequest() { } public ModifyDNRequest(string distinguishedName, string newParentDistinguishedName, string newName) { } public bool DeleteOldRdn { get { throw null; } set { } } public string DistinguishedName { get { throw null; } set { } } public string NewName { get { throw null; } set { } } public string NewParentDistinguishedName { get { throw null; } set { } } } public partial class ModifyDNResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal ModifyDNResponse() { } } public partial class ModifyRequest : System.DirectoryServices.Protocols.DirectoryRequest { public ModifyRequest() { } public ModifyRequest(string distinguishedName, params System.DirectoryServices.Protocols.DirectoryAttributeModification[] modifications) { } public ModifyRequest(string distinguishedName, System.DirectoryServices.Protocols.DirectoryAttributeOperation operation, string attributeName, params object[] values) { } public string DistinguishedName { get { throw null; } set { } } public System.DirectoryServices.Protocols.DirectoryAttributeModificationCollection Modifications { get { throw null; } } } public partial class ModifyResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal ModifyResponse() { } } public delegate bool NotifyOfNewConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection referralFromConnection, string newDistinguishedName, System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.DirectoryServices.Protocols.LdapConnection newConnection, System.Net.NetworkCredential credential, long currentUserToken, int errorCodeFromBind); public partial class PageResultRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public PageResultRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public PageResultRequestControl(byte[] cookie) : base (default(string), default(byte[]), default(bool), default(bool)) { } public PageResultRequestControl(int pageSize) : base (default(string), default(byte[]), default(bool), default(bool)) { } public byte[] Cookie { get { throw null; } set { } } public int PageSize { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class PageResultResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal PageResultResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public byte[] Cookie { get { throw null; } } public int TotalCount { get { throw null; } } } public enum PartialResultProcessing { NoPartialResultSupport = 0, ReturnPartialResults = 1, ReturnPartialResultsAndNotifyCallback = 2, } public partial class PartialResultsCollection : System.Collections.ReadOnlyCollectionBase { internal PartialResultsCollection() { } public object this[int index] { get { throw null; } } public bool Contains(object value) { throw null; } public void CopyTo(object[] values, int index) { } public int IndexOf(object value) { throw null; } } public partial class PermissiveModifyControl : System.DirectoryServices.Protocols.DirectoryControl { public PermissiveModifyControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public delegate System.Security.Cryptography.X509Certificates.X509Certificate QueryClientCertificateCallback(System.DirectoryServices.Protocols.LdapConnection connection, byte[][] trustedCAs); public delegate System.DirectoryServices.Protocols.LdapConnection QueryForConnectionCallback(System.DirectoryServices.Protocols.LdapConnection primaryConnection, System.DirectoryServices.Protocols.LdapConnection referralFromConnection, string newDistinguishedName, System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier, System.Net.NetworkCredential credential, long currentUserToken); [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public partial class QuotaControl : System.DirectoryServices.Protocols.DirectoryControl { public QuotaControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public QuotaControl(System.Security.Principal.SecurityIdentifier querySid) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.Security.Principal.SecurityIdentifier QuerySid { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public sealed partial class ReferralCallback { public ReferralCallback() { } public System.DirectoryServices.Protocols.DereferenceConnectionCallback DereferenceConnection { get { throw null; } set { } } public System.DirectoryServices.Protocols.NotifyOfNewConnectionCallback NotifyNewConnection { get { throw null; } set { } } public System.DirectoryServices.Protocols.QueryForConnectionCallback QueryForConnection { get { throw null; } set { } } } [System.FlagsAttribute] public enum ReferralChasingOptions { None = 0, Subordinate = 32, External = 64, All = 96, } public enum ResultCode { Success = 0, OperationsError = 1, ProtocolError = 2, TimeLimitExceeded = 3, SizeLimitExceeded = 4, CompareFalse = 5, CompareTrue = 6, AuthMethodNotSupported = 7, StrongAuthRequired = 8, ReferralV2 = 9, Referral = 10, AdminLimitExceeded = 11, UnavailableCriticalExtension = 12, ConfidentialityRequired = 13, SaslBindInProgress = 14, NoSuchAttribute = 16, UndefinedAttributeType = 17, InappropriateMatching = 18, ConstraintViolation = 19, AttributeOrValueExists = 20, InvalidAttributeSyntax = 21, NoSuchObject = 32, AliasProblem = 33, InvalidDNSyntax = 34, AliasDereferencingProblem = 36, InappropriateAuthentication = 48, InsufficientAccessRights = 50, Busy = 51, Unavailable = 52, UnwillingToPerform = 53, LoopDetect = 54, SortControlMissing = 60, OffsetRangeError = 61, NamingViolation = 64, ObjectClassViolation = 65, NotAllowedOnNonLeaf = 66, NotAllowedOnRdn = 67, EntryAlreadyExists = 68, ObjectClassModificationsProhibited = 69, ResultsTooLarge = 70, AffectsMultipleDsas = 71, VirtualListViewError = 76, Other = 80, } public enum SearchOption { DomainScope = 1, PhantomRoot = 2, } public partial class SearchOptionsControl : System.DirectoryServices.Protocols.DirectoryControl { public SearchOptionsControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption flags) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.SearchOption SearchOption { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class SearchRequest : System.DirectoryServices.Protocols.DirectoryRequest { public SearchRequest() { } public SearchRequest(string distinguishedName, string ldapFilter, System.DirectoryServices.Protocols.SearchScope searchScope, params string[] attributeList) { } public System.DirectoryServices.Protocols.DereferenceAlias Aliases { get { throw null; } set { } } public System.Collections.Specialized.StringCollection Attributes { get { throw null; } } public string DistinguishedName { get { throw null; } set { } } public object Filter { get { throw null; } set { } } public System.DirectoryServices.Protocols.SearchScope Scope { get { throw null; } set { } } public int SizeLimit { get { throw null; } set { } } public System.TimeSpan TimeLimit { get { throw null; } set { } } public bool TypesOnly { get { throw null; } set { } } } public partial class SearchResponse : System.DirectoryServices.Protocols.DirectoryResponse { internal SearchResponse() { } public override System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } } public System.DirectoryServices.Protocols.SearchResultEntryCollection Entries { get { throw null; } } public override string ErrorMessage { get { throw null; } } public override string MatchedDN { get { throw null; } } public System.DirectoryServices.Protocols.SearchResultReferenceCollection References { get { throw null; } } public override System.Uri[] Referral { get { throw null; } } public override System.DirectoryServices.Protocols.ResultCode ResultCode { get { throw null; } } } public partial class SearchResultAttributeCollection : System.Collections.DictionaryBase { internal SearchResultAttributeCollection() { } public System.Collections.ICollection AttributeNames { get { throw null; } } public System.DirectoryServices.Protocols.DirectoryAttribute this[string attributeName] { get { throw null; } } public System.Collections.ICollection Values { get { throw null; } } public bool Contains(string attributeName) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.DirectoryAttribute[] array, int index) { } } public partial class SearchResultEntry { internal SearchResultEntry() { } public System.DirectoryServices.Protocols.SearchResultAttributeCollection Attributes { get { throw null; } } public System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } } public string DistinguishedName { get { throw null; } } } public partial class SearchResultEntryCollection : System.Collections.ReadOnlyCollectionBase { internal SearchResultEntryCollection() { } public System.DirectoryServices.Protocols.SearchResultEntry this[int index] { get { throw null; } } public bool Contains(System.DirectoryServices.Protocols.SearchResultEntry value) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.SearchResultEntry[] values, int index) { } public int IndexOf(System.DirectoryServices.Protocols.SearchResultEntry value) { throw null; } } public partial class SearchResultReference { internal SearchResultReference() { } public System.DirectoryServices.Protocols.DirectoryControl[] Controls { get { throw null; } } public System.Uri[] Reference { get { throw null; } } } public partial class SearchResultReferenceCollection : System.Collections.ReadOnlyCollectionBase { internal SearchResultReferenceCollection() { } public System.DirectoryServices.Protocols.SearchResultReference this[int index] { get { throw null; } } public bool Contains(System.DirectoryServices.Protocols.SearchResultReference value) { throw null; } public void CopyTo(System.DirectoryServices.Protocols.SearchResultReference[] values, int index) { } public int IndexOf(System.DirectoryServices.Protocols.SearchResultReference value) { throw null; } } public enum SearchScope { Base = 0, OneLevel = 1, Subtree = 2, } public partial class SecurityDescriptorFlagControl : System.DirectoryServices.Protocols.DirectoryControl { public SecurityDescriptorFlagControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public SecurityDescriptorFlagControl(System.DirectoryServices.Protocols.SecurityMasks masks) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.SecurityMasks SecurityMasks { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } [System.FlagsAttribute] public enum SecurityMasks { None = 0, Owner = 1, Group = 2, Dacl = 4, Sacl = 8, } public partial class SecurityPackageContextConnectionInformation { internal SecurityPackageContextConnectionInformation() { } public System.Security.Authentication.CipherAlgorithmType AlgorithmIdentifier { get { throw null; } } public int CipherStrength { get { throw null; } } public int ExchangeStrength { get { throw null; } } public System.Security.Authentication.HashAlgorithmType Hash { get { throw null; } } public int HashStrength { get { throw null; } } public int KeyExchangeAlgorithm { get { throw null; } } public System.DirectoryServices.Protocols.SecurityProtocol Protocol { get { throw null; } } } public enum SecurityProtocol { Pct1Server = 1, Pct1Client = 2, Ssl2Server = 4, Ssl2Client = 8, Ssl3Server = 16, Ssl3Client = 32, Tls1Server = 64, Tls1Client = 128, } public partial class ShowDeletedControl : System.DirectoryServices.Protocols.DirectoryControl { public ShowDeletedControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class SortKey { public SortKey() { } public SortKey(string attributeName, string matchingRule, bool reverseOrder) { } public string AttributeName { get { throw null; } set { } } public string MatchingRule { get { throw null; } set { } } public bool ReverseOrder { get { throw null; } set { } } } public partial class SortRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public SortRequestControl(params System.DirectoryServices.Protocols.SortKey[] sortKeys) : base (default(string), default(byte[]), default(bool), default(bool)) { } public SortRequestControl(string attributeName, bool reverseOrder) : base (default(string), default(byte[]), default(bool), default(bool)) { } public SortRequestControl(string attributeName, string matchingRule, bool reverseOrder) : base (default(string), default(byte[]), default(bool), default(bool)) { } public System.DirectoryServices.Protocols.SortKey[] SortKeys { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class SortResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal SortResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public string AttributeName { get { throw null; } } public System.DirectoryServices.Protocols.ResultCode Result { get { throw null; } } } public partial class TlsOperationException : System.DirectoryServices.Protocols.DirectoryOperationException { public TlsOperationException() { } public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response) { } public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message) { } public TlsOperationException(System.DirectoryServices.Protocols.DirectoryResponse response, string message, System.Exception inner) { } protected TlsOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public TlsOperationException(string message) { } public TlsOperationException(string message, System.Exception inner) { } } public partial class TreeDeleteControl : System.DirectoryServices.Protocols.DirectoryControl { public TreeDeleteControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } } public partial class VerifyNameControl : System.DirectoryServices.Protocols.DirectoryControl { public VerifyNameControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public VerifyNameControl(string serverName) : base (default(string), default(byte[]), default(bool), default(bool)) { } public VerifyNameControl(string serverName, int flag) : base (default(string), default(byte[]), default(bool), default(bool)) { } public int Flag { get { throw null; } set { } } public string ServerName { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public delegate bool VerifyServerCertificateCallback(System.DirectoryServices.Protocols.LdapConnection connection, System.Security.Cryptography.X509Certificates.X509Certificate certificate); public partial class VlvRequestControl : System.DirectoryServices.Protocols.DirectoryControl { public VlvRequestControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public VlvRequestControl(int beforeCount, int afterCount, byte[] target) : base (default(string), default(byte[]), default(bool), default(bool)) { } public VlvRequestControl(int beforeCount, int afterCount, int offset) : base (default(string), default(byte[]), default(bool), default(bool)) { } public VlvRequestControl(int beforeCount, int afterCount, string target) : base (default(string), default(byte[]), default(bool), default(bool)) { } public int AfterCount { get { throw null; } set { } } public int BeforeCount { get { throw null; } set { } } public byte[] ContextId { get { throw null; } set { } } public int EstimateCount { get { throw null; } set { } } public int Offset { get { throw null; } set { } } public byte[] Target { get { throw null; } set { } } public override byte[] GetValue() { throw null; } } public partial class VlvResponseControl : System.DirectoryServices.Protocols.DirectoryControl { internal VlvResponseControl() : base (default(string), default(byte[]), default(bool), default(bool)) { } public int ContentCount { get { throw null; } } public byte[] ContextId { get { throw null; } } public System.DirectoryServices.Protocols.ResultCode Result { get { throw null; } } public int TargetPosition { get { throw null; } } } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/Common/tests/System/Xml/XPath/TestData/space.xml
<Doc> <Title>XPath test</Title> <Summary>This shall test XPath test</Summary> <Chap xml:space="preserve"> <Title>XPath test</Title> <Para>First paragraph <Para> Nested <Origin/> Paragraph </Para> End of first paragraph </Para> <Para>Second paragraph </Para> </Chap> <Chap> <Title>XPath test</Title> Direct content </Chap> </Doc>
<Doc> <Title>XPath test</Title> <Summary>This shall test XPath test</Summary> <Chap xml:space="preserve"> <Title>XPath test</Title> <Para>First paragraph <Para> Nested <Origin/> Paragraph </Para> End of first paragraph </Para> <Para>Second paragraph </Para> </Chap> <Chap> <Title>XPath test</Title> Direct content </Chap> </Doc>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b71155/b71155.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/Arrays/range/int32_1_il_r.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="int32_1.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="int32_1.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.Private.Xml/tests/XmlConvert/SqlXmlConvertTests0.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using OLEDB.Test.ModuleCore; namespace System.Xml.Tests { internal class SqlXmlConvertTests0 : SqlXmlConvertTests { #region Constructors and Destructors public SqlXmlConvertTests0() { foreach (string token in strEncode) { AddVariation(new CVariation(this, "EncodeNmToken-EncodeLocalNmToken with " + token, XmlEncodeName2)); } } #endregion #region Public Methods and Operators public int XmlEncodeName2() { int i = (CurVariation.id) - 1; string strEnVal = string.Empty; CError.WriteLine(strEncode[i]); strEnVal = XmlConvert.EncodeNmToken(strEncode[i]); CError.Compare(strEnVal, strExpEncodeNmToken[i], "Comparison failed at " + i); return TEST_PASS; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using OLEDB.Test.ModuleCore; namespace System.Xml.Tests { internal class SqlXmlConvertTests0 : SqlXmlConvertTests { #region Constructors and Destructors public SqlXmlConvertTests0() { foreach (string token in strEncode) { AddVariation(new CVariation(this, "EncodeNmToken-EncodeLocalNmToken with " + token, XmlEncodeName2)); } } #endregion #region Public Methods and Operators public int XmlEncodeName2() { int i = (CurVariation.id) - 1; string strEnVal = string.Empty; CError.WriteLine(strEncode[i]); strEnVal = XmlConvert.EncodeNmToken(strEncode[i]); CError.Compare(strEnVal, strExpEncodeNmToken[i], "Comparison failed at " + i); return TEST_PASS; } #endregion } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/coreclr/pal/tests/palsuite/file_io/GetFileAttributesA/test1/ro_test_file
file_io CopyFileW Positive Test for CopyFileW test the CopyFileW function DEFAULT CopyFileW
file_io CopyFileW Positive Test for CopyFileW test the CopyFileW function DEFAULT CopyFileW
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.Private.CoreLib/src/Internal/Console.Unix.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.Text; namespace Internal { public static partial class Console { public static unsafe void Write(string s) { byte[] bytes = Encoding.UTF8.GetBytes(s); fixed (byte* pBytes = bytes) { Interop.Sys.Log(pBytes, bytes.Length); } } public static partial class Error { public static unsafe void Write(string s) { byte[] bytes = Encoding.UTF8.GetBytes(s); fixed (byte* pBytes = bytes) { Interop.Sys.LogError(pBytes, bytes.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; using System.Text; namespace Internal { public static partial class Console { public static unsafe void Write(string s) { byte[] bytes = Encoding.UTF8.GetBytes(s); fixed (byte* pBytes = bytes) { Interop.Sys.Log(pBytes, bytes.Length); } } public static partial class Error { public static unsafe void Write(string s) { byte[] bytes = Encoding.UTF8.GetBytes(s); fixed (byte* pBytes = bytes) { Interop.Sys.LogError(pBytes, bytes.Length); } } } } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Max.Vector128.UInt32.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 Max_Vector128_UInt32() { var test = new SimpleBinaryOpTest__Max_Vector128_UInt32(); 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__Max_Vector128_UInt32 { 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(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); 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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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 Vector128<UInt32> _fld1; public Vector128<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Max_Vector128_UInt32 testClass) { var result = AdvSimd.Max(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Max_Vector128_UInt32 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Max_Vector128_UInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public SimpleBinaryOpTest__Max_Vector128_UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new UInt32[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.Max( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_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.Max( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_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).GetMethod(nameof(AdvSimd.Max), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Max), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Max( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((UInt32*)(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<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = AdvSimd.Max(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.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Max_Vector128_UInt32(); var result = AdvSimd.Max(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__Max_Vector128_UInt32(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt32>* pFld2 = &test._fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Max(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(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.Max(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.Max( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((UInt32*)(&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(Vector128<UInt32> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Max(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Max)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {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 Max_Vector128_UInt32() { var test = new SimpleBinaryOpTest__Max_Vector128_UInt32(); 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__Max_Vector128_UInt32 { 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(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); 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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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 Vector128<UInt32> _fld1; public Vector128<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Max_Vector128_UInt32 testClass) { var result = AdvSimd.Max(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Max_Vector128_UInt32 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Max_Vector128_UInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public SimpleBinaryOpTest__Max_Vector128_UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new UInt32[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.Max( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_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.Max( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_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).GetMethod(nameof(AdvSimd.Max), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Max), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Max( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector128((UInt32*)(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<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = AdvSimd.Max(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.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Max_Vector128_UInt32(); var result = AdvSimd.Max(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__Max_Vector128_UInt32(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt32>* pFld2 = &test._fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Max(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector128((UInt32*)(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.Max(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.Max( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector128((UInt32*)(&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(Vector128<UInt32> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Max(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Max)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {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,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b27564/b27564.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 legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly ILGEN_0xd4f4498 {} .class ILGEN_0xd4f4498 { .method static int32 main() { .entrypoint .maxstack 19 .locals (unsigned int32 local_0x5) ldc.i4 0x3f887477 stloc local_0x5 ldc.i4 7 newarr [mscorlib]System.Single ldc.i4 5 ldc.i8 0x22ab10e430c242a3 conv.r4 Start_Orphan_8: ldloc local_0x5 not stloc local_0x5 End_Orphan_8: stelem.r4 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 legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly ILGEN_0xd4f4498 {} .class ILGEN_0xd4f4498 { .method static int32 main() { .entrypoint .maxstack 19 .locals (unsigned int32 local_0x5) ldc.i4 0x3f887477 stloc local_0x5 ldc.i4 7 newarr [mscorlib]System.Single ldc.i4 5 ldc.i8 0x22ab10e430c242a3 conv.r4 Start_Orphan_8: ldloc local_0x5 not stloc local_0x5 End_Orphan_8: stelem.r4 ldc.i4 100 ret } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Asn1/CertificateAsn.xml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable SA1028 // ignore whitespace warnings for generated code using System; using System.Formats.Asn1; using System.Runtime.InteropServices; namespace System.Security.Cryptography.X509Certificates.Asn1 { [StructLayout(LayoutKind.Sequential)] internal partial struct CertificateAsn { internal System.Security.Cryptography.X509Certificates.Asn1.TbsCertificateAsn TbsCertificate; internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn SignatureAlgorithm; internal ReadOnlyMemory<byte> SignatureValue; internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); TbsCertificate.Encode(writer); SignatureAlgorithm.Encode(writer); writer.WriteBitString(SignatureValue.Span, 0); writer.PopSequence(tag); } internal static CertificateAsn Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static CertificateAsn Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { try { AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out CertificateAsn decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out CertificateAsn decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out CertificateAsn decoded) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out CertificateAsn decoded) { decoded = default; AsnValueReader sequenceReader = reader.ReadSequence(expectedTag); ReadOnlySpan<byte> rebindSpan = rebind.Span; int offset; ReadOnlySpan<byte> tmpSpan; System.Security.Cryptography.X509Certificates.Asn1.TbsCertificateAsn.Decode(ref sequenceReader, rebind, out decoded.TbsCertificate); System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(ref sequenceReader, rebind, out decoded.SignatureAlgorithm); if (sequenceReader.TryReadPrimitiveBitString(out _, out tmpSpan)) { decoded.SignatureValue = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray(); } else { decoded.SignatureValue = sequenceReader.ReadBitString(out _); } sequenceReader.ThrowIfNotEmpty(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable SA1028 // ignore whitespace warnings for generated code using System; using System.Formats.Asn1; using System.Runtime.InteropServices; namespace System.Security.Cryptography.X509Certificates.Asn1 { [StructLayout(LayoutKind.Sequential)] internal partial struct CertificateAsn { internal System.Security.Cryptography.X509Certificates.Asn1.TbsCertificateAsn TbsCertificate; internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn SignatureAlgorithm; internal ReadOnlyMemory<byte> SignatureValue; internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); TbsCertificate.Encode(writer); SignatureAlgorithm.Encode(writer); writer.WriteBitString(SignatureValue.Span, 0); writer.PopSequence(tag); } internal static CertificateAsn Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static CertificateAsn Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { try { AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out CertificateAsn decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out CertificateAsn decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out CertificateAsn decoded) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out CertificateAsn decoded) { decoded = default; AsnValueReader sequenceReader = reader.ReadSequence(expectedTag); ReadOnlySpan<byte> rebindSpan = rebind.Span; int offset; ReadOnlySpan<byte> tmpSpan; System.Security.Cryptography.X509Certificates.Asn1.TbsCertificateAsn.Decode(ref sequenceReader, rebind, out decoded.TbsCertificate); System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(ref sequenceReader, rebind, out decoded.SignatureAlgorithm); if (sequenceReader.TryReadPrimitiveBitString(out _, out tmpSpan)) { decoded.SignatureValue = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray(); } else { decoded.SignatureValue = sequenceReader.ReadBitString(out _); } sequenceReader.ThrowIfNotEmpty(); } } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/CodeGenBringUpTests/FPSmall_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="FPSmall.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="FPSmall.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Performance/CodeQuality/V8/Crypto/Crypto.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <NoWarn>$(NoWarn);xUnit1013</NoWarn> </PropertyGroup> <PropertyGroup> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> <PropertyGroup> <ProjectAssetsFile>$(JitPackagesConfigFileDirectory)benchmark\obj\project.assets.json</ProjectAssetsFile> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <NoWarn>$(NoWarn);xUnit1013</NoWarn> </PropertyGroup> <PropertyGroup> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> <PropertyGroup> <ProjectAssetsFile>$(JitPackagesConfigFileDirectory)benchmark\obj\project.assets.json</ProjectAssetsFile> </PropertyGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/int64/signed/s_ldc_div_il_d.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="s_ldc_div.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="s_ldc_div.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/Common/tests/Tests/System/IO/PathInternal.Unix.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; using System.IO; using Xunit; namespace Tests.System.IO { [PlatformSpecific(TestPlatforms.AnyUnix)] public class PathInternalTests_Unix { [Theory, InlineData(@"", @""), InlineData(null, null), InlineData(@"/", @"/"), InlineData(@"//", @"/"), InlineData(@"///", @"/"), InlineData(@"\", @"\"), InlineData(@"\\", @"\\"), InlineData(@"\\\", @"\\\"), InlineData(@"\/", @"\/"), InlineData(@"\/\", @"\/\"), InlineData(@"a/a", @"a/a"), InlineData(@"a//a", @"a/a"), InlineData(@"a\\a", @"a\\a"), InlineData(@"/a", @"/a"), InlineData(@"//a", @"/a"), InlineData(@"\\a", @"\\a"), InlineData(@"a/", @"a/"), InlineData(@"a//", @"a/"), InlineData(@"a\\", @"a\\"), ] [PlatformSpecific(TestPlatforms.AnyUnix)] public void NormalizeDirectorySeparatorTests(string path, string expected) { string result = PathInternal.NormalizeDirectorySeparators(path); Assert.Equal(expected, result); if (string.Equals(path, expected, StringComparison.Ordinal)) Assert.Same(path, result); } [Fact] [PlatformSpecific(TestPlatforms.OSX)] public void IsCaseInsensitive_OSX() { // There have been reports of casing handling not being appropriate on MacOS // https://github.com/dotnet/runtime/issues/24898 Assert.False(PathInternal.IsCaseSensitive); } } }
// 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; using Xunit; namespace Tests.System.IO { [PlatformSpecific(TestPlatforms.AnyUnix)] public class PathInternalTests_Unix { [Theory, InlineData(@"", @""), InlineData(null, null), InlineData(@"/", @"/"), InlineData(@"//", @"/"), InlineData(@"///", @"/"), InlineData(@"\", @"\"), InlineData(@"\\", @"\\"), InlineData(@"\\\", @"\\\"), InlineData(@"\/", @"\/"), InlineData(@"\/\", @"\/\"), InlineData(@"a/a", @"a/a"), InlineData(@"a//a", @"a/a"), InlineData(@"a\\a", @"a\\a"), InlineData(@"/a", @"/a"), InlineData(@"//a", @"/a"), InlineData(@"\\a", @"\\a"), InlineData(@"a/", @"a/"), InlineData(@"a//", @"a/"), InlineData(@"a\\", @"a\\"), ] [PlatformSpecific(TestPlatforms.AnyUnix)] public void NormalizeDirectorySeparatorTests(string path, string expected) { string result = PathInternal.NormalizeDirectorySeparators(path); Assert.Equal(expected, result); if (string.Equals(path, expected, StringComparison.Ordinal)) Assert.Same(path, result); } [Fact] [PlatformSpecific(TestPlatforms.OSX)] public void IsCaseInsensitive_OSX() { // There have been reports of casing handling not being appropriate on MacOS // https://github.com/dotnet/runtime/issues/24898 Assert.False(PathInternal.IsCaseSensitive); } } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/GC/API/WeakReference/IsAlive_neg.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestExecutionArguments /> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="IsAlive_neg.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestExecutionArguments /> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="IsAlive_neg.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/baseservices/exceptions/unittests/baseclass.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; // // main // public class TestSet { static void CountResults(int testReturnValue, ref int nSuccesses, ref int nFailures) { if (100 == testReturnValue) { nSuccesses++; } else { nFailures++; } } public static int Main() { int nSuccesses = 0; int nFailures = 0; CountResults(new BaseClassTest().Run(), ref nSuccesses, ref nFailures); if (0 == nFailures) { Console.WriteLine("OVERALL PASS: " + nSuccesses + " tests"); return 100; } else { Console.WriteLine("OVERALL FAIL: " + nFailures + " tests failed"); return 999; } } } class BaseClassTest { Trace _trace; void f2() { throw new FileNotFoundException("1"); } void f1() { try { f2(); } catch(FileNotFoundException e) { Console.WriteLine(e); _trace.Write("0" + e.Message); throw e; } catch(IOException e) { Console.WriteLine(e); _trace.Write("!" + e.Message); throw e; } catch(Exception e) { Console.WriteLine(e); _trace.Write("@" + e.Message); throw e; } } public int Run() { _trace = new Trace("BaseClassTest", "0121"); try { f1(); } catch(Exception e) { Console.WriteLine(e); _trace.Write("2" + e.Message); } return _trace.Match(); } }
// 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; // // main // public class TestSet { static void CountResults(int testReturnValue, ref int nSuccesses, ref int nFailures) { if (100 == testReturnValue) { nSuccesses++; } else { nFailures++; } } public static int Main() { int nSuccesses = 0; int nFailures = 0; CountResults(new BaseClassTest().Run(), ref nSuccesses, ref nFailures); if (0 == nFailures) { Console.WriteLine("OVERALL PASS: " + nSuccesses + " tests"); return 100; } else { Console.WriteLine("OVERALL FAIL: " + nFailures + " tests failed"); return 999; } } } class BaseClassTest { Trace _trace; void f2() { throw new FileNotFoundException("1"); } void f1() { try { f2(); } catch(FileNotFoundException e) { Console.WriteLine(e); _trace.Write("0" + e.Message); throw e; } catch(IOException e) { Console.WriteLine(e); _trace.Write("!" + e.Message); throw e; } catch(Exception e) { Console.WriteLine(e); _trace.Write("@" + e.Message); throw e; } } public int Run() { _trace = new Trace("BaseClassTest", "0121"); try { f1(); } catch(Exception e) { Console.WriteLine(e); _trace.Write("2" + e.Message); } return _trace.Match(); } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/mono/mono/tests/custom-modifiers-inheritance.cs
using System; using System.Reflection; using System.Reflection.Emit; public class Tests { // This set of tests are for checking the impact of custom modifiers on vtable layout and // method overrides. CustomModifiers are used for one thing and one thing alone, and that's making // two method signatures that would otherwise be equal into unequal signatures. This is used by C++/CLI // to tag primitive types with the C++-side type. For instance, this allows a single primitive type for // various integer types, but prevents a function taking an int from overriding a function taking a long. // // We have to use SRE or il to interact with it, as C# compilers don't do much with modifiers beyond // reflection. There's no way to generate the below hierarchy and methods by compiling C#. Object childNoModObj; Object childOptModObj; Object childSameModObj; Object childForwardObj; Object childBackwardObj; MethodInfo invokeParentSig; MethodInfo invokeParentForwardSig; public static void DefineMethodM (TypeBuilder tb, string className, Type [] required_modifiers, Type [] optional_modifiers) { // Example il (no equivalent C# for modreqs) // Note that the modifiers will change for each class // // // method line 4 // .method public virtual hidebysig // instance default string M (int32* modreq ([mscorlib]System.Runtime.CompilerServices.IsReadOnlyAttribute) A_1) cil managed // { // // Method begins at RVA 0x2104 // Code size 6 (0x6) // .maxstack 8 // IL_0000: ldstr "ChildSameMod" // IL_0005: ret // } // end of method ChildSameMod::M // Type[][] req_mods = required_modifiers != null ? new Type [][] {required_modifiers} : null; Type[][] opt_mods = optional_modifiers != null ? new Type [][] {optional_modifiers} : null; MethodBuilder mbIM = tb.DefineMethod("M", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, CallingConventions.Standard, typeof (string), null, null, new Type[] {typeof (int *)}, req_mods, opt_mods); ILGenerator il = mbIM.GetILGenerator(); il.Emit (OpCodes.Ldstr, className); //il.Emit (OpCodes.Ldstr, className); //il.Emit (OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) })); il.Emit (OpCodes.Ret); } public static void DefineMethodInvoke (TypeBuilder tb, string invokeName, MethodInfo target, Type argument) { // Example il (no equivalent C# for modreqs) // Note that the modifiers will change as per the callee // // .method public static // default string InvokeParentSig (class Parent A_0) cil managed // { // // Code size 14 (0xe) // .maxstack 3 // .locals init ( // int32 V_0) // IL_0000: ldarg.0 // IL_0001: ldc.i4.0 // IL_0002: stloc.0 // IL_0003: ldloca.s 0 // IL_0005: nop // IL_0006: nop // IL_0007: nop // IL_0008: callvirt instance string class Parent::M(int32* modreq ([mscorlib]System.Runtime.CompilerServices.IsReadOnlyAttribute) ) // IL_000d: ret //} // end of method Invoker::InvokeParentSig // // MethodBuilder mbIM = tb.DefineMethod(invokeName, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof (string), null, null, new Type [] {argument}, null, null); ILGenerator il = mbIM.GetILGenerator(); var local = il.DeclareLocal (typeof (int)); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldc_I4_0); il.Emit (OpCodes.Stloc, local); il.Emit (OpCodes.Ldloca_S, 0); il.Emit (OpCodes.Callvirt, target); il.Emit (OpCodes.Ret); } public Tests () { string name = "CustomModifiersOverride"; AssemblyName asmName = new AssemblyName(name); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder mb = ab.DefineDynamicModule(name, name + ".dll"); // Create class hierarchy: // Parent > ChildSameMod // Parent > ChildNoMod // Parent > ChildOptMod // // The Same, No, and Opt labels describe whether it's the same modifiers, // optional modifiers rather than required, or with no modifiers. // // ParentThreeForward > ChildThreeForward // ParentThreeForward > ChildThreeBackward // // These have to do with ordering. There are 3 mods, and forward/backwards is // relative and has to do with the order the modifiers appear in the IL. // // Each of these classes has a function called "M" with an int pointer argument which // contains custom modifiers. Based on whether the child's method overrides the parent's // method, we can tell whether the method signatures have been found equal by the underlying // runtime, and whether the impact on VTable layout is correct. var mods = new Type [] { typeof (System.Runtime.CompilerServices.IsReadOnlyAttribute) }; var parent = mb.DefineType("Parent", TypeAttributes.Public); DefineMethodM (parent, "Parent", mods, null); var parentType = parent.CreateType (); var childSameMod = mb.DefineType("ChildSameMod", TypeAttributes.Public, parent); DefineMethodM (childSameMod, "ChildSameMod", mods, null); var childSameModType = childSameMod.CreateType (); var childNoMod = mb.DefineType("ChildNoMod", TypeAttributes.Public, parent); DefineMethodM (childNoMod, "ChildNoMod", null, null); var childNoModType = childNoMod.CreateType (); var childOptMod = mb.DefineType("ChildOptMod", TypeAttributes.Public, parent); DefineMethodM (childOptMod, "ChildOptMod", null, mods); var childOptModType = childOptMod.CreateType (); var first_mod = typeof (System.Runtime.CompilerServices.IsReadOnlyAttribute); var second_mod = typeof (System.Runtime.CompilerServices.SpecialNameAttribute); var third_mod = typeof (System.Runtime.CompilerServices.IsConst); var forwardMods = new Type [] {first_mod, second_mod, third_mod}; var backwardMods = new Type [] {third_mod, second_mod, first_mod}; var parentThreeForward = mb.DefineType("ParentThreeForward", TypeAttributes.Public); DefineMethodM (parentThreeForward, "ParentThreeForward", forwardMods, null); var parentThreeForwardType = parentThreeForward.CreateType (); var childThreeForward = mb.DefineType("ChildThreeForward", TypeAttributes.Public, parentThreeForward); DefineMethodM (childThreeForward, "ChildThreeForward", forwardMods, null); var childThreeForwardType = childThreeForward.CreateType (); var childThreeBackward = mb.DefineType("ChildThreeBackward", TypeAttributes.Public, parentThreeForward); DefineMethodM (childThreeBackward, "ChildThreeBackward", backwardMods, null); var childThreeBackwardType = childThreeBackward.CreateType (); var invoker = mb.DefineType("Invoker", TypeAttributes.Public); // Since we want to generate callvirt calls which contain references to the custom modifiers // for the parent types, to actually probe overloading or not, we need to generate the classes the make those // calls var methodBaseReference = parentType.GetMethod ("M"); DefineMethodInvoke (invoker, "InvokeParentSig", methodBaseReference, parentType); var methodBaseReferenceMultiple = parentThreeForwardType.GetMethod ("M"); DefineMethodInvoke (invoker, "InvokeParentThreeForwardSig", methodBaseReferenceMultiple, parentThreeForwardType); var invokerType = invoker.CreateType (); ab.Save(name + ".dll"); childNoModObj = Activator.CreateInstance (childNoModType); childOptModObj = Activator.CreateInstance (childOptModType); childSameModObj = Activator.CreateInstance (childSameModType); childForwardObj = Activator.CreateInstance (childThreeForwardType); childBackwardObj = Activator.CreateInstance (childThreeBackwardType); invokeParentSig = invokerType.GetMethod ("InvokeParentSig"); invokeParentForwardSig = invokerType.GetMethod ("InvokeParentThreeForwardSig"); } public static int Main () { // The expected behavior can be near impossible to reproduce using this .exe on // another CLR because many SRE implementations do not correctly use modifiers. To // compare results with another runtime, get the dll saved by the above ab.Save() // line, manually copy it over, and run it with the other CLR. var tester = new Tests (); tester.TestModSufficient (); tester.TestModNecessary (); tester.TestModReqSameAsOpt (); tester.TestModReqMulti (); tester.TestModReqMultiNoOrder (); return 0; } public void TestModSufficient() { var result = (string)invokeParentSig.Invoke(null, new Object[] { childSameModObj }); if (result != "ChildSameMod") throw new Exception("TestModSufficient: Unexpected Class Override"); else Console.WriteLine("Success: {0} {1}", childSameModObj.GetType().Name, result); } public void TestModNecessary() { var result = (string)invokeParentSig.Invoke(null, new Object[] { childNoModObj }); if (result != "Parent") throw new Exception(String.Format("Unexpected Class Override: {0}", result)); else Console.WriteLine("Success: {0} {1}", childNoModObj.GetType().Name, result); } public void TestModReqSameAsOpt() { var result = (string)invokeParentSig.Invoke(null, new Object[] { childOptModObj }); if (result != "Parent") throw new Exception("Unexpected Class Override"); else Console.WriteLine("Success: {0} {1}", childOptModObj.GetType().Name, result); } public void TestModReqMulti() { var result = (string)invokeParentForwardSig.Invoke(null, new Object[] { childForwardObj }); if (result != "ChildThreeForward") throw new Exception(String.Format("Unexpected Class Override {0}, MULTIPLE MODS BROKEN", result)); else Console.WriteLine("Success MULTI MODS: {0} {1}", childForwardObj.GetType().Name, result); } public void TestModReqMultiNoOrder() { var result = (string)invokeParentForwardSig.Invoke(null, new Object[] { childBackwardObj }); if (result != "ParentThreeForward") throw new Exception(String.Format("Unexpected Class Override: {0}, ORDER MATTERS", result)); else Console.WriteLine("Success ORDER MATTERS: {0} {1}", childBackwardObj.GetType().Name, result); } }
using System; using System.Reflection; using System.Reflection.Emit; public class Tests { // This set of tests are for checking the impact of custom modifiers on vtable layout and // method overrides. CustomModifiers are used for one thing and one thing alone, and that's making // two method signatures that would otherwise be equal into unequal signatures. This is used by C++/CLI // to tag primitive types with the C++-side type. For instance, this allows a single primitive type for // various integer types, but prevents a function taking an int from overriding a function taking a long. // // We have to use SRE or il to interact with it, as C# compilers don't do much with modifiers beyond // reflection. There's no way to generate the below hierarchy and methods by compiling C#. Object childNoModObj; Object childOptModObj; Object childSameModObj; Object childForwardObj; Object childBackwardObj; MethodInfo invokeParentSig; MethodInfo invokeParentForwardSig; public static void DefineMethodM (TypeBuilder tb, string className, Type [] required_modifiers, Type [] optional_modifiers) { // Example il (no equivalent C# for modreqs) // Note that the modifiers will change for each class // // // method line 4 // .method public virtual hidebysig // instance default string M (int32* modreq ([mscorlib]System.Runtime.CompilerServices.IsReadOnlyAttribute) A_1) cil managed // { // // Method begins at RVA 0x2104 // Code size 6 (0x6) // .maxstack 8 // IL_0000: ldstr "ChildSameMod" // IL_0005: ret // } // end of method ChildSameMod::M // Type[][] req_mods = required_modifiers != null ? new Type [][] {required_modifiers} : null; Type[][] opt_mods = optional_modifiers != null ? new Type [][] {optional_modifiers} : null; MethodBuilder mbIM = tb.DefineMethod("M", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, CallingConventions.Standard, typeof (string), null, null, new Type[] {typeof (int *)}, req_mods, opt_mods); ILGenerator il = mbIM.GetILGenerator(); il.Emit (OpCodes.Ldstr, className); //il.Emit (OpCodes.Ldstr, className); //il.Emit (OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) })); il.Emit (OpCodes.Ret); } public static void DefineMethodInvoke (TypeBuilder tb, string invokeName, MethodInfo target, Type argument) { // Example il (no equivalent C# for modreqs) // Note that the modifiers will change as per the callee // // .method public static // default string InvokeParentSig (class Parent A_0) cil managed // { // // Code size 14 (0xe) // .maxstack 3 // .locals init ( // int32 V_0) // IL_0000: ldarg.0 // IL_0001: ldc.i4.0 // IL_0002: stloc.0 // IL_0003: ldloca.s 0 // IL_0005: nop // IL_0006: nop // IL_0007: nop // IL_0008: callvirt instance string class Parent::M(int32* modreq ([mscorlib]System.Runtime.CompilerServices.IsReadOnlyAttribute) ) // IL_000d: ret //} // end of method Invoker::InvokeParentSig // // MethodBuilder mbIM = tb.DefineMethod(invokeName, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof (string), null, null, new Type [] {argument}, null, null); ILGenerator il = mbIM.GetILGenerator(); var local = il.DeclareLocal (typeof (int)); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldc_I4_0); il.Emit (OpCodes.Stloc, local); il.Emit (OpCodes.Ldloca_S, 0); il.Emit (OpCodes.Callvirt, target); il.Emit (OpCodes.Ret); } public Tests () { string name = "CustomModifiersOverride"; AssemblyName asmName = new AssemblyName(name); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder mb = ab.DefineDynamicModule(name, name + ".dll"); // Create class hierarchy: // Parent > ChildSameMod // Parent > ChildNoMod // Parent > ChildOptMod // // The Same, No, and Opt labels describe whether it's the same modifiers, // optional modifiers rather than required, or with no modifiers. // // ParentThreeForward > ChildThreeForward // ParentThreeForward > ChildThreeBackward // // These have to do with ordering. There are 3 mods, and forward/backwards is // relative and has to do with the order the modifiers appear in the IL. // // Each of these classes has a function called "M" with an int pointer argument which // contains custom modifiers. Based on whether the child's method overrides the parent's // method, we can tell whether the method signatures have been found equal by the underlying // runtime, and whether the impact on VTable layout is correct. var mods = new Type [] { typeof (System.Runtime.CompilerServices.IsReadOnlyAttribute) }; var parent = mb.DefineType("Parent", TypeAttributes.Public); DefineMethodM (parent, "Parent", mods, null); var parentType = parent.CreateType (); var childSameMod = mb.DefineType("ChildSameMod", TypeAttributes.Public, parent); DefineMethodM (childSameMod, "ChildSameMod", mods, null); var childSameModType = childSameMod.CreateType (); var childNoMod = mb.DefineType("ChildNoMod", TypeAttributes.Public, parent); DefineMethodM (childNoMod, "ChildNoMod", null, null); var childNoModType = childNoMod.CreateType (); var childOptMod = mb.DefineType("ChildOptMod", TypeAttributes.Public, parent); DefineMethodM (childOptMod, "ChildOptMod", null, mods); var childOptModType = childOptMod.CreateType (); var first_mod = typeof (System.Runtime.CompilerServices.IsReadOnlyAttribute); var second_mod = typeof (System.Runtime.CompilerServices.SpecialNameAttribute); var third_mod = typeof (System.Runtime.CompilerServices.IsConst); var forwardMods = new Type [] {first_mod, second_mod, third_mod}; var backwardMods = new Type [] {third_mod, second_mod, first_mod}; var parentThreeForward = mb.DefineType("ParentThreeForward", TypeAttributes.Public); DefineMethodM (parentThreeForward, "ParentThreeForward", forwardMods, null); var parentThreeForwardType = parentThreeForward.CreateType (); var childThreeForward = mb.DefineType("ChildThreeForward", TypeAttributes.Public, parentThreeForward); DefineMethodM (childThreeForward, "ChildThreeForward", forwardMods, null); var childThreeForwardType = childThreeForward.CreateType (); var childThreeBackward = mb.DefineType("ChildThreeBackward", TypeAttributes.Public, parentThreeForward); DefineMethodM (childThreeBackward, "ChildThreeBackward", backwardMods, null); var childThreeBackwardType = childThreeBackward.CreateType (); var invoker = mb.DefineType("Invoker", TypeAttributes.Public); // Since we want to generate callvirt calls which contain references to the custom modifiers // for the parent types, to actually probe overloading or not, we need to generate the classes the make those // calls var methodBaseReference = parentType.GetMethod ("M"); DefineMethodInvoke (invoker, "InvokeParentSig", methodBaseReference, parentType); var methodBaseReferenceMultiple = parentThreeForwardType.GetMethod ("M"); DefineMethodInvoke (invoker, "InvokeParentThreeForwardSig", methodBaseReferenceMultiple, parentThreeForwardType); var invokerType = invoker.CreateType (); ab.Save(name + ".dll"); childNoModObj = Activator.CreateInstance (childNoModType); childOptModObj = Activator.CreateInstance (childOptModType); childSameModObj = Activator.CreateInstance (childSameModType); childForwardObj = Activator.CreateInstance (childThreeForwardType); childBackwardObj = Activator.CreateInstance (childThreeBackwardType); invokeParentSig = invokerType.GetMethod ("InvokeParentSig"); invokeParentForwardSig = invokerType.GetMethod ("InvokeParentThreeForwardSig"); } public static int Main () { // The expected behavior can be near impossible to reproduce using this .exe on // another CLR because many SRE implementations do not correctly use modifiers. To // compare results with another runtime, get the dll saved by the above ab.Save() // line, manually copy it over, and run it with the other CLR. var tester = new Tests (); tester.TestModSufficient (); tester.TestModNecessary (); tester.TestModReqSameAsOpt (); tester.TestModReqMulti (); tester.TestModReqMultiNoOrder (); return 0; } public void TestModSufficient() { var result = (string)invokeParentSig.Invoke(null, new Object[] { childSameModObj }); if (result != "ChildSameMod") throw new Exception("TestModSufficient: Unexpected Class Override"); else Console.WriteLine("Success: {0} {1}", childSameModObj.GetType().Name, result); } public void TestModNecessary() { var result = (string)invokeParentSig.Invoke(null, new Object[] { childNoModObj }); if (result != "Parent") throw new Exception(String.Format("Unexpected Class Override: {0}", result)); else Console.WriteLine("Success: {0} {1}", childNoModObj.GetType().Name, result); } public void TestModReqSameAsOpt() { var result = (string)invokeParentSig.Invoke(null, new Object[] { childOptModObj }); if (result != "Parent") throw new Exception("Unexpected Class Override"); else Console.WriteLine("Success: {0} {1}", childOptModObj.GetType().Name, result); } public void TestModReqMulti() { var result = (string)invokeParentForwardSig.Invoke(null, new Object[] { childForwardObj }); if (result != "ChildThreeForward") throw new Exception(String.Format("Unexpected Class Override {0}, MULTIPLE MODS BROKEN", result)); else Console.WriteLine("Success MULTI MODS: {0} {1}", childForwardObj.GetType().Name, result); } public void TestModReqMultiNoOrder() { var result = (string)invokeParentForwardSig.Invoke(null, new Object[] { childBackwardObj }); if (result != "ParentThreeForward") throw new Exception(String.Format("Unexpected Class Override: {0}, ORDER MATTERS", result)); else Console.WriteLine("Success ORDER MATTERS: {0} {1}", childBackwardObj.GetType().Name, result); } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.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; namespace System.Diagnostics { public class CounterCreationDataCollection : CollectionBase { public CounterCreationDataCollection() { } public CounterCreationDataCollection(CounterCreationDataCollection value) { AddRange(value); } public CounterCreationDataCollection(CounterCreationData[] value) { AddRange(value); } public CounterCreationData this[int index] { get { return ((CounterCreationData)(List[index])); } set { List[index] = value; } } public int Add(CounterCreationData value) { return List.Add(value); } public void AddRange(CounterCreationData[] value!!) { for (int i = 0; i < value.Length; i++) { Add(value[i]); } } public void AddRange(CounterCreationDataCollection value!!) { int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { Add(value[i]); } } public bool Contains(CounterCreationData value) { return List.Contains(value); } public void CopyTo(CounterCreationData[] array, int index) { List.CopyTo(array, index); } public int IndexOf(CounterCreationData value) { return List.IndexOf(value); } public void Insert(int index, CounterCreationData value) { List.Insert(index, value); } public virtual void Remove(CounterCreationData value) { List.Remove(value); } protected override void OnValidate(object value!!) { if (!(value is CounterCreationData)) throw new ArgumentException(SR.MustAddCounterCreationData); } } }
// 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; namespace System.Diagnostics { public class CounterCreationDataCollection : CollectionBase { public CounterCreationDataCollection() { } public CounterCreationDataCollection(CounterCreationDataCollection value) { AddRange(value); } public CounterCreationDataCollection(CounterCreationData[] value) { AddRange(value); } public CounterCreationData this[int index] { get { return ((CounterCreationData)(List[index])); } set { List[index] = value; } } public int Add(CounterCreationData value) { return List.Add(value); } public void AddRange(CounterCreationData[] value!!) { for (int i = 0; i < value.Length; i++) { Add(value[i]); } } public void AddRange(CounterCreationDataCollection value!!) { int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { Add(value[i]); } } public bool Contains(CounterCreationData value) { return List.Contains(value); } public void CopyTo(CounterCreationData[] array, int index) { List.CopyTo(array, index); } public int IndexOf(CounterCreationData value) { return List.IndexOf(value); } public void Insert(int index, CounterCreationData value) { List.Insert(index, value); } public virtual void Remove(CounterCreationData value) { List.Remove(value); } protected override void OnValidate(object value!!) { if (!(value is CounterCreationData)) throw new ArgumentException(SR.MustAddCounterCreationData); } } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtenderProvidedPropertyAttribute.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; namespace System.ComponentModel { /// <summary> /// ExtenderProvidedPropertyAttribute is an attribute that marks that a property /// was actually offered up by and extender provider. /// </summary> [AttributeUsage(AttributeTargets.All)] public sealed class ExtenderProvidedPropertyAttribute : Attribute { /// <summary> /// Creates a new ExtenderProvidedPropertyAttribute. /// </summary> internal static ExtenderProvidedPropertyAttribute Create(PropertyDescriptor? extenderProperty, Type? receiverType, IExtenderProvider? provider) { return new ExtenderProvidedPropertyAttribute { ExtenderProperty = extenderProperty, ReceiverType = receiverType, Provider = provider }; } /// <summary> /// Creates an empty ExtenderProvidedPropertyAttribute. /// </summary> public ExtenderProvidedPropertyAttribute() { } /// <summary> /// PropertyDescriptor of the property that is being provided. /// </summary> public PropertyDescriptor? ExtenderProperty { get; private set; } /// <summary> /// Extender provider that is providing the property. /// </summary> public IExtenderProvider? Provider { get; private set; } /// <summary> /// The type of object that can receive these properties. /// </summary> public Type? ReceiverType { get; private set; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == this) { return true; } if (!(obj is ExtenderProvidedPropertyAttribute other)) { return false; } // ExtenderProperty is null if the attribute is created with // the default constructor. In this case, all the properties // are null (and are immutable), so we only need to check the // nullability of one property to know about the nullability // of the rest. if (other.ExtenderProperty == null) { Debug.Assert(other.Provider == null); Debug.Assert(other.ReceiverType == null); Debug.Assert(Provider == null); Debug.Assert(ReceiverType == null); return ExtenderProperty == null; } return other.ExtenderProperty.Equals(ExtenderProperty) && other.Provider!.Equals(Provider) && other.ReceiverType!.Equals(ReceiverType); } public override int GetHashCode() => base.GetHashCode(); public override bool IsDefaultAttribute() => ReceiverType == 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.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel { /// <summary> /// ExtenderProvidedPropertyAttribute is an attribute that marks that a property /// was actually offered up by and extender provider. /// </summary> [AttributeUsage(AttributeTargets.All)] public sealed class ExtenderProvidedPropertyAttribute : Attribute { /// <summary> /// Creates a new ExtenderProvidedPropertyAttribute. /// </summary> internal static ExtenderProvidedPropertyAttribute Create(PropertyDescriptor? extenderProperty, Type? receiverType, IExtenderProvider? provider) { return new ExtenderProvidedPropertyAttribute { ExtenderProperty = extenderProperty, ReceiverType = receiverType, Provider = provider }; } /// <summary> /// Creates an empty ExtenderProvidedPropertyAttribute. /// </summary> public ExtenderProvidedPropertyAttribute() { } /// <summary> /// PropertyDescriptor of the property that is being provided. /// </summary> public PropertyDescriptor? ExtenderProperty { get; private set; } /// <summary> /// Extender provider that is providing the property. /// </summary> public IExtenderProvider? Provider { get; private set; } /// <summary> /// The type of object that can receive these properties. /// </summary> public Type? ReceiverType { get; private set; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == this) { return true; } if (!(obj is ExtenderProvidedPropertyAttribute other)) { return false; } // ExtenderProperty is null if the attribute is created with // the default constructor. In this case, all the properties // are null (and are immutable), so we only need to check the // nullability of one property to know about the nullability // of the rest. if (other.ExtenderProperty == null) { Debug.Assert(other.Provider == null); Debug.Assert(other.ReceiverType == null); Debug.Assert(Provider == null); Debug.Assert(ReceiverType == null); return ExtenderProperty == null; } return other.ExtenderProperty.Equals(ExtenderProperty) && other.Provider!.Equals(Provider) && other.ReceiverType!.Equals(ReceiverType); } public override int GetHashCode() => base.GetHashCode(); public override bool IsDefaultAttribute() => ReceiverType == null; } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test2/MapViewOfFile.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================= ** ** Source: MapViewOfFile.c ** ** Purpose: Positive test the MapViewOfFile API. ** Call MapViewOfFile with access FILE_MAP_WRITE. ** ** Depends: CreateFile, ** GetFileSize, ** memset, ** CreateFileMapping, ** CloseHandle, ** memcpy, ** ReadFile, ** memcmp, ** UnMapViewOfFile. ** ** **============================================================*/ #include <palsuite.h> PALTEST(filemapping_memmgt_MapViewOfFile_test2_paltest_mapviewoffile_test2, "filemapping_memmgt/MapViewOfFile/test2/paltest_mapviewoffile_test2") { HANDLE hFile; HANDLE hFileMapping; LPVOID lpMapViewAddress; char buf[] = "this is a test string"; const int MAPPINGSIZE = 2048; char ch[2048]; char readString[2048]; char lpFileName[] = "test.tmp"; DWORD dwBytesRead; DWORD dwInitialSize = 0; DWORD dwFinalSize = 0; BOOL bRetVal; /* Initialize the PAL environment. */ if(0 != PAL_Initialize(argc, argv)) { return FAIL; } /* Create a file handle with CreateFile. */ hFile = CreateFile( lpFileName, GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { Fail("ERROR: %u :unable to create file \"%s\".\n", GetLastError(), lpFileName); } /* Get the initial size of file, for latter tests. */ dwInitialSize = GetFileSize (hFile, NULL); if ( dwInitialSize == INVALID_FILE_SIZE ) { Fail("ERROR:%u: The created file \"%s\" has an invalid " "file size.\n", GetLastError(), lpFileName); } /* Initialize the buffers. */ memset(ch, 0, MAPPINGSIZE); memset(readString, 0, MAPPINGSIZE); /* Create a unnamed file-mapping object with file handle FileHandle * and with PAGE_READWRITE protection. */ hFileMapping = CreateFileMapping( hFile, NULL, /*not inherited*/ PAGE_READWRITE, /*read and wite*/ 0, /*high-order of object size*/ MAPPINGSIZE, /*low-orger of object size*/ NULL); /*unnamed object*/ if(NULL == hFileMapping) { Trace("ERROR:%u: Failed to create File Mapping.\n", GetLastError()); CloseHandle(hFile); Fail(""); } /* maps a view of a file into the address space of the calling process. */ lpMapViewAddress = MapViewOfFile( hFileMapping, FILE_MAP_WRITE, /* access code */ 0, /*high order offset*/ 0, /*low order offset*/ MAPPINGSIZE); /* number of bytes for map */ if(NULL == lpMapViewAddress) { Trace("ERROR:%u: Failed to call MapViewOfFile API to map a view" " of file!\n", GetLastError()); CloseHandle(hFile); CloseHandle(hFileMapping); Fail(""); } /* Verify that the size of the file has increased to * accomidate the MapView. */ dwFinalSize = GetFileSize (hFile, NULL); if ( (dwFinalSize <= dwInitialSize) && (dwFinalSize != MAPPINGSIZE)) { CloseHandle(hFile); CloseHandle(hFileMapping); Fail("ERROR: Size of the file was expected to " "increase from \"%d\", to \"%d\".\n ", dwInitialSize, MAPPINGSIZE); } /* Write to the MapView and copy the MapViewOfFile * to buffer, so we can compare with value read from * file directly. */ memcpy(lpMapViewAddress, buf, strlen(buf)); /* Read from the File handle. */ bRetVal = ReadFile(hFile, readString, strlen(buf), &dwBytesRead, NULL); if (bRetVal == FALSE) { Trace("ERROR: %u :unable to read from file handle " "hFile=0x%lx\n", GetLastError(), hFile); CloseHandle(hFile); CloseHandle(hFileMapping); Fail(""); } if (memcmp(buf, readString, strlen(readString)) != 0) { CloseHandle(hFile); CloseHandle(hFileMapping); Fail("ERROR: Read string from file \"%s\", is " "not equal to string written through MapView " "\"%s\".\n", readString, ch); } /* Unmap the view of file. */ if(UnmapViewOfFile(lpMapViewAddress) == FALSE) { Trace("ERROR: Failed to call UnmapViewOfFile API to" " unmap the view of a file, error code=%u\n", GetLastError()); CloseHandle(hFile); CloseHandle(hFileMapping); Fail(""); } /* Close handle to create file. */ if(CloseHandle(hFile) == FALSE) { Trace("ERROR:%u:Failed to call CloseHandle API " "to close a file handle.", GetLastError()); CloseHandle(hFileMapping); Fail(""); } if(CloseHandle(hFileMapping) == FALSE) { Fail("ERROR:%u:Failed to call CloseHandle API " "to close a file mapping handle.", GetLastError()); } PAL_Terminate(); return PASS; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================= ** ** Source: MapViewOfFile.c ** ** Purpose: Positive test the MapViewOfFile API. ** Call MapViewOfFile with access FILE_MAP_WRITE. ** ** Depends: CreateFile, ** GetFileSize, ** memset, ** CreateFileMapping, ** CloseHandle, ** memcpy, ** ReadFile, ** memcmp, ** UnMapViewOfFile. ** ** **============================================================*/ #include <palsuite.h> PALTEST(filemapping_memmgt_MapViewOfFile_test2_paltest_mapviewoffile_test2, "filemapping_memmgt/MapViewOfFile/test2/paltest_mapviewoffile_test2") { HANDLE hFile; HANDLE hFileMapping; LPVOID lpMapViewAddress; char buf[] = "this is a test string"; const int MAPPINGSIZE = 2048; char ch[2048]; char readString[2048]; char lpFileName[] = "test.tmp"; DWORD dwBytesRead; DWORD dwInitialSize = 0; DWORD dwFinalSize = 0; BOOL bRetVal; /* Initialize the PAL environment. */ if(0 != PAL_Initialize(argc, argv)) { return FAIL; } /* Create a file handle with CreateFile. */ hFile = CreateFile( lpFileName, GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { Fail("ERROR: %u :unable to create file \"%s\".\n", GetLastError(), lpFileName); } /* Get the initial size of file, for latter tests. */ dwInitialSize = GetFileSize (hFile, NULL); if ( dwInitialSize == INVALID_FILE_SIZE ) { Fail("ERROR:%u: The created file \"%s\" has an invalid " "file size.\n", GetLastError(), lpFileName); } /* Initialize the buffers. */ memset(ch, 0, MAPPINGSIZE); memset(readString, 0, MAPPINGSIZE); /* Create a unnamed file-mapping object with file handle FileHandle * and with PAGE_READWRITE protection. */ hFileMapping = CreateFileMapping( hFile, NULL, /*not inherited*/ PAGE_READWRITE, /*read and wite*/ 0, /*high-order of object size*/ MAPPINGSIZE, /*low-orger of object size*/ NULL); /*unnamed object*/ if(NULL == hFileMapping) { Trace("ERROR:%u: Failed to create File Mapping.\n", GetLastError()); CloseHandle(hFile); Fail(""); } /* maps a view of a file into the address space of the calling process. */ lpMapViewAddress = MapViewOfFile( hFileMapping, FILE_MAP_WRITE, /* access code */ 0, /*high order offset*/ 0, /*low order offset*/ MAPPINGSIZE); /* number of bytes for map */ if(NULL == lpMapViewAddress) { Trace("ERROR:%u: Failed to call MapViewOfFile API to map a view" " of file!\n", GetLastError()); CloseHandle(hFile); CloseHandle(hFileMapping); Fail(""); } /* Verify that the size of the file has increased to * accomidate the MapView. */ dwFinalSize = GetFileSize (hFile, NULL); if ( (dwFinalSize <= dwInitialSize) && (dwFinalSize != MAPPINGSIZE)) { CloseHandle(hFile); CloseHandle(hFileMapping); Fail("ERROR: Size of the file was expected to " "increase from \"%d\", to \"%d\".\n ", dwInitialSize, MAPPINGSIZE); } /* Write to the MapView and copy the MapViewOfFile * to buffer, so we can compare with value read from * file directly. */ memcpy(lpMapViewAddress, buf, strlen(buf)); /* Read from the File handle. */ bRetVal = ReadFile(hFile, readString, strlen(buf), &dwBytesRead, NULL); if (bRetVal == FALSE) { Trace("ERROR: %u :unable to read from file handle " "hFile=0x%lx\n", GetLastError(), hFile); CloseHandle(hFile); CloseHandle(hFileMapping); Fail(""); } if (memcmp(buf, readString, strlen(readString)) != 0) { CloseHandle(hFile); CloseHandle(hFileMapping); Fail("ERROR: Read string from file \"%s\", is " "not equal to string written through MapView " "\"%s\".\n", readString, ch); } /* Unmap the view of file. */ if(UnmapViewOfFile(lpMapViewAddress) == FALSE) { Trace("ERROR: Failed to call UnmapViewOfFile API to" " unmap the view of a file, error code=%u\n", GetLastError()); CloseHandle(hFile); CloseHandle(hFileMapping); Fail(""); } /* Close handle to create file. */ if(CloseHandle(hFile) == FALSE) { Trace("ERROR:%u:Failed to call CloseHandle API " "to close a file handle.", GetLastError()); CloseHandle(hFileMapping); Fail(""); } if(CloseHandle(hFileMapping) == FALSE) { Fail("ERROR:%u:Failed to call CloseHandle API " "to close a file mapping handle.", GetLastError()); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/HardwareIntrinsics/General/Vector256/Dot.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\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 DotInt16() { var test = new VectorBinaryOpTest__DotInt16(); // 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__DotInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); 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<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 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 Vector256<Int16> _fld1; public Vector256<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<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__DotInt16 testClass) { var result = Vector256.Dot(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__DotInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public VectorBinaryOpTest__DotInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<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, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Dot( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Dot), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Dot), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (Int16)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Dot( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Vector256.Dot(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__DotInt16(); var result = Vector256.Dot(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Dot(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Dot(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(Vector256<Int16> op1, Vector256<Int16> op2, Int16 result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, Int16 result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16 result, [CallerMemberName] string method = "") { bool succeeded = true; Int16 actualResult = default; Int16 intermResult = default; for (var i = 0; i < Op1ElementCount; i++) { if ((i % Vector128<Int16>.Count) == 0) { actualResult += intermResult; intermResult = default; } intermResult += (Int16)(left[i] * right[i]); } actualResult += intermResult; if (actualResult != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Dot)}<Int16>(Vector256<Int16>, Vector256<Int16>): {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 DotInt16() { var test = new VectorBinaryOpTest__DotInt16(); // 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__DotInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); 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<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 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 Vector256<Int16> _fld1; public Vector256<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<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__DotInt16 testClass) { var result = Vector256.Dot(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__DotInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public VectorBinaryOpTest__DotInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<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, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Dot( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Dot), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Dot), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (Int16)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Dot( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Vector256.Dot(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__DotInt16(); var result = Vector256.Dot(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Dot(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Dot(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(Vector256<Int16> op1, Vector256<Int16> op2, Int16 result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, Int16 result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16 result, [CallerMemberName] string method = "") { bool succeeded = true; Int16 actualResult = default; Int16 intermResult = default; for (var i = 0; i < Op1ElementCount; i++) { if ((i % Vector128<Int16>.Count) == 0) { actualResult += intermResult; intermResult = default; } intermResult += (Int16)(left[i] * right[i]); } actualResult += intermResult; if (actualResult != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Dot)}<Int16>(Vector256<Int16>, Vector256<Int16>): {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,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/Loader/classloader/regressions/dev10_897464/Test.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.Console { } .assembly extern mscorlib { } .assembly Test { .hash algorithm 0x00008004 .ver 1:0:0:0 } .module Test.dll .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY .field public static literal valuetype Test.MyEnum LiteralValue = int32(0x00000001) .class public auto ansi sealed Test.MyEnum extends [mscorlib]System.Enum { .field public specialname rtspecialname int32 value__ .field public static literal valuetype Test.MyEnum Zero = int32(0x00000000) .field public static literal valuetype Test.MyEnum One = int32(0x00000001) } // Just here so we can reference something /*.class interface public abstract auto ansi Test.IEmpty { } */
// 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.Console { } .assembly extern mscorlib { } .assembly Test { .hash algorithm 0x00008004 .ver 1:0:0:0 } .module Test.dll .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY .field public static literal valuetype Test.MyEnum LiteralValue = int32(0x00000001) .class public auto ansi sealed Test.MyEnum extends [mscorlib]System.Enum { .field public specialname rtspecialname int32 value__ .field public static literal valuetype Test.MyEnum Zero = int32(0x00000000) .field public static literal valuetype Test.MyEnum One = int32(0x00000001) } // Just here so we can reference something /*.class interface public abstract auto ansi Test.IEmpty { } */
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.Data.Common/tests/TrimmingTests/System.Data.Common.TrimmingTests.proj
<Project DefaultTargets="Build"> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props))" /> <ItemGroup> <TestConsoleAppSourceFiles Include="CreateSqlXmlReader.cs" /> <TestConsoleAppSourceFiles Include="DbConnectionStringBuilder.cs" /> </ItemGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets))" /> </Project>
<Project DefaultTargets="Build"> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props))" /> <ItemGroup> <TestConsoleAppSourceFiles Include="CreateSqlXmlReader.cs" /> <TestConsoleAppSourceFiles Include="DbConnectionStringBuilder.cs" /> </ItemGroup> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets))" /> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Regression/JitBlue/GitHub_18522/GitHub_18522_2.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; // Based on // Original generated by Fuzzlyn on 2018-06-20 00:58:58 // Seed: 11049252875418439527 // Reduced from 97.5 KiB to 0.5 KiB // Debug: Outputs -1 // Release: Outputs -65536 struct S0 { public sbyte F0; public char F1; public ushort F2; } struct S1 { public short F0; public S0 F1; public S0 F2; public S0 F3; public int F4; public S1(int f4): this() { F4 = f4; } } public class GitHub_18522_2 { static S1 s_6; static S1[] s_13 = new S1[]{new S1(-1)}; public static int Main() { // When generating code for the x64 SysV ABI, the jit was // incorrectly typing the return type from M16, and so // inadvertently overwriting the F4 field of s_13[0] on return // from the (not inlined) call. s_13[0].F3 = M16(); return s_13[0].F4 == -1 ? 100 : 0; } [MethodImpl(MethodImplOptions.NoInlining)] static S0 M16() { return s_6.F3; } }
// 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; // Based on // Original generated by Fuzzlyn on 2018-06-20 00:58:58 // Seed: 11049252875418439527 // Reduced from 97.5 KiB to 0.5 KiB // Debug: Outputs -1 // Release: Outputs -65536 struct S0 { public sbyte F0; public char F1; public ushort F2; } struct S1 { public short F0; public S0 F1; public S0 F2; public S0 F3; public int F4; public S1(int f4): this() { F4 = f4; } } public class GitHub_18522_2 { static S1 s_6; static S1[] s_13 = new S1[]{new S1(-1)}; public static int Main() { // When generating code for the x64 SysV ABI, the jit was // incorrectly typing the return type from M16, and so // inadvertently overwriting the F4 field of s_13[0] on return // from the (not inlined) call. s_13[0].F3 = M16(); return s_13[0].F4 == -1 ? 100 : 0; } [MethodImpl(MethodImplOptions.NoInlining)] static S0 M16() { return s_6.F3; } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/explicit/funcptr/seq_funcptr_val_il_d.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="seq_funcptr_val.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="seq_funcptr_val.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest484/Generated484.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 Generated484 { .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 sequential sealed MyStruct534`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase2`2<class BaseClass1,!T1>, class IBase2`2<!T0,class BaseClass0> { .pack 0 .size 1 .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct534::Method7.4090<" 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 'IBase2<class BaseClass1,T1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass1,!T1>::Method7<[1]>() ldstr "MyStruct534::Method7.MI.4091<" 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 'IBase2<T0,class BaseClass0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<!T0,class BaseClass0>::Method7<[1]>() ldstr "MyStruct534::Method7.MI.4093<" 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 instance string ClassMethod1063() cil managed noinlining { ldstr "MyStruct534::ClassMethod1063.4094()" ret } .method public hidebysig newslot instance string ClassMethod1064<M0>() cil managed noinlining { ldstr "MyStruct534::ClassMethod1064.4095<" 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 instance string ClassMethod1065<M0>() cil managed noinlining { ldstr "MyStruct534::ClassMethod1065.4096<" 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 bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated484 { .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.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.MyStruct534.T.T<T0,T1,(valuetype MyStruct534`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.T.T<T0,T1,(valuetype MyStruct534`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<!!T0,!!T1> callvirt instance string class IBase2`2<!!T0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct534.A.T<T1,(valuetype MyStruct534`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.A.T<T1,(valuetype MyStruct534`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,!!T1> 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.MyStruct534.A.A<(valuetype MyStruct534`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.A.A<(valuetype MyStruct534`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,class BaseClass0> 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.MyStruct534.A.B<(valuetype MyStruct534`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.A.B<(valuetype MyStruct534`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,class BaseClass1> 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.MyStruct534.B.T<T1,(valuetype MyStruct534`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.B.T<T1,(valuetype MyStruct534`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass1,!!T1> 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.MyStruct534.B.B<(valuetype MyStruct534`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.B.B<(valuetype MyStruct534`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass1,class BaseClass1> 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 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) .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1063() ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1064<object>() ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1065<object>() ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1063() ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1064<object>() ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1065<object>() ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct534`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1063() ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1064<object>() ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1065<object>() ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass1,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) .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.A<valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.A<valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.B<valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.B<valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass1> .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.B<valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.A<valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.B<valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .locals init (valuetype MyStruct534`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct534`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.B<valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV24 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV24} LV24: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.B.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV25 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV25} LV25: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.B.A<valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV26 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV26} LV26: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV27 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV27} LV27: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV28 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV28} LV28: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.B<valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV29 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV29} LV29: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV30 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV30} LV30: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV31 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV31} LV31: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.A<valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV32 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV32} LV32: 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) .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.A.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.A.A<valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass1> V_10) ldloca V_10 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass1> .try { ldloc V_10 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_10 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.A.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_10 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.A.B<valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct534`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct534`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_12 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.B.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_12 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.B.B<valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: 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) .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1063() calli default string(object) ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1064<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1065<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass1> V_14) ldloca V_14 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1063() calli default string(object) ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1064<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1065<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldnull ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance bool valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct534`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1063() calli default string(object) ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1064<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1065<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass1,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 Generated484::MethodCallingTest() call void Generated484::ConstrainedCallsTest() call void Generated484::StructConstrainedInterfaceCallsTest() call void Generated484::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 Generated484 { .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 sequential sealed MyStruct534`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase2`2<class BaseClass1,!T1>, class IBase2`2<!T0,class BaseClass0> { .pack 0 .size 1 .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct534::Method7.4090<" 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 'IBase2<class BaseClass1,T1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass1,!T1>::Method7<[1]>() ldstr "MyStruct534::Method7.MI.4091<" 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 'IBase2<T0,class BaseClass0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<!T0,class BaseClass0>::Method7<[1]>() ldstr "MyStruct534::Method7.MI.4093<" 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 instance string ClassMethod1063() cil managed noinlining { ldstr "MyStruct534::ClassMethod1063.4094()" ret } .method public hidebysig newslot instance string ClassMethod1064<M0>() cil managed noinlining { ldstr "MyStruct534::ClassMethod1064.4095<" 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 instance string ClassMethod1065<M0>() cil managed noinlining { ldstr "MyStruct534::ClassMethod1065.4096<" 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 bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated484 { .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.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.MyStruct534.T.T<T0,T1,(valuetype MyStruct534`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.T.T<T0,T1,(valuetype MyStruct534`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<!!T0,!!T1> callvirt instance string class IBase2`2<!!T0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct534.A.T<T1,(valuetype MyStruct534`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.A.T<T1,(valuetype MyStruct534`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,!!T1> 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.MyStruct534.A.A<(valuetype MyStruct534`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.A.A<(valuetype MyStruct534`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,class BaseClass0> 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.MyStruct534.A.B<(valuetype MyStruct534`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.A.B<(valuetype MyStruct534`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass0,class BaseClass1> 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.MyStruct534.B.T<T1,(valuetype MyStruct534`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.B.T<T1,(valuetype MyStruct534`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass1,!!T1> 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.MyStruct534.B.B<(valuetype MyStruct534`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct534.B.B<(valuetype MyStruct534`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct534`2<class BaseClass1,class BaseClass1> 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 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) .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1063() ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1064<object>() ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1065<object>() ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1063() ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1064<object>() ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1065<object>() ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct534`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1063() ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1064<object>() ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1065<object>() ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type MyStruct534" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass1,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) .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.A<valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.A<valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.B<valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_5 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.B<valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass1> .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.B<valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.A<valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_6 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.B<valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .locals init (valuetype MyStruct534`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct534`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.B.B<valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV24 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV24} LV24: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.B.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV25 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV25} LV25: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.B.A<valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV26 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV26} LV26: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV27 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV27} LV27: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV28 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV28} LV28: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" call void Generated484::M.IBase2.A.B<valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV29 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV29} LV29: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV30 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV30} LV30: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV31 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV31} LV31: .try { ldloc V_8 ldstr "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.IBase2.A.A<valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV32 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV32} LV32: 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) .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.A.T<class BaseClass0,valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.A.A<valuetype MyStruct534`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass1> V_10) ldloca V_10 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass1> .try { ldloc V_10 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_10 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.A.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_10 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.A.B<valuetype MyStruct534`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct534`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct534`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_12 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.B.T<class BaseClass1,valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_12 ldstr "MyStruct534::Method7.MI.4091<System.Object>()#" + "MyStruct534::Method7.MI.4093<System.Object>()#" call void Generated484::M.MyStruct534.B.B<valuetype MyStruct534`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: 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) .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1063() calli default string(object) ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1064<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ClassMethod1065<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct534`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct534`2<class BaseClass0,class BaseClass1> V_14) ldloca V_14 initobj valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1063() calli default string(object) ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1064<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ClassMethod1065<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldnull ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance bool valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct534`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct534`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.4090<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1063() calli default string(object) ldstr "MyStruct534::ClassMethod1063.4094()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1064<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1064.4095<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ClassMethod1065<object>() calli default string(object) ldstr "MyStruct534::ClassMethod1065.4096<System.Object>()" ldstr "valuetype MyStruct534`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct534`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4091<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct534`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct534`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct534::Method7.MI.4093<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct534`2<class BaseClass1,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 Generated484::MethodCallingTest() call void Generated484::ConstrainedCallsTest() call void Generated484::StructConstrainedInterfaceCallsTest() call void Generated484::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/cctor/misc/Desktop/throw.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; internal class measure { public static int a = 0xCC; } internal class test { static test() { if (measure.a != 0xCC) { Console.WriteLine("in .cctor(), measure.a is {0}", measure.a); Console.WriteLine("FAILED"); throw new Exception(); } Console.WriteLine("in .cctor(), measure.a is {0}", measure.a); measure.a = 8; if (measure.a != 8) { Console.WriteLine("in .cctor() after measure.a=8, measure.a is {0}", measure.a); Console.WriteLine("FAILED"); throw new Exception(); } Console.WriteLine("in .cctor() after measure.a=8, measure.a is {0}", measure.a); throw new Exception(); } } internal class Driver { public static int Main() { try { Console.WriteLine("Testing .cctor() invocation by calling instance method"); Console.WriteLine(); Console.WriteLine("Before calling instance method"); if (measure.a != 0xCC) { Console.WriteLine("in Main(), measure.a is {0}", measure.a); Console.WriteLine("FAILED"); return 1; } test t = new test(); Console.WriteLine("After calling instance method"); if (measure.a != 8) { Console.WriteLine("in Main() after new test(), measure.a is {0}", measure.a); Console.WriteLine("FAILED"); return -1; } } catch (Exception e) { Console.WriteLine(e.StackTrace); Console.WriteLine(); Console.WriteLine("PASSED"); return 100; } return -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; internal class measure { public static int a = 0xCC; } internal class test { static test() { if (measure.a != 0xCC) { Console.WriteLine("in .cctor(), measure.a is {0}", measure.a); Console.WriteLine("FAILED"); throw new Exception(); } Console.WriteLine("in .cctor(), measure.a is {0}", measure.a); measure.a = 8; if (measure.a != 8) { Console.WriteLine("in .cctor() after measure.a=8, measure.a is {0}", measure.a); Console.WriteLine("FAILED"); throw new Exception(); } Console.WriteLine("in .cctor() after measure.a=8, measure.a is {0}", measure.a); throw new Exception(); } } internal class Driver { public static int Main() { try { Console.WriteLine("Testing .cctor() invocation by calling instance method"); Console.WriteLine(); Console.WriteLine("Before calling instance method"); if (measure.a != 0xCC) { Console.WriteLine("in Main(), measure.a is {0}", measure.a); Console.WriteLine("FAILED"); return 1; } test t = new test(); Console.WriteLine("After calling instance method"); if (measure.a != 8) { Console.WriteLine("in Main() after new test(), measure.a is {0}", measure.a); Console.WriteLine("FAILED"); return -1; } } catch (Exception e) { Console.WriteLine(e.StackTrace); Console.WriteLine(); Console.WriteLine("PASSED"); return 100; } return -1; } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/HardwareIntrinsics/General/Vector128/LessThanAny.SByte.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 LessThanAnySByte() { var test = new VectorBooleanBinaryOpTest__LessThanAnySByte(); // 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__LessThanAnySByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); 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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, 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<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__LessThanAnySByte testClass) { var result = Vector128.LessThanAny(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__LessThanAnySByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public VectorBooleanBinaryOpTest__LessThanAnySByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.LessThanAny( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_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.LessThanAny), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.LessThanAny), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(SByte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.LessThanAny( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Vector128.LessThanAny(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__LessThanAnySByte(); var result = Vector128.LessThanAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.LessThanAny(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.LessThanAny(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<SByte> op1, Vector128<SByte> op2, bool result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(SByte[] left, SByte[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = false; for (var i = 0; i < Op1ElementCount; i++) { expectedResult |= (left[i] < right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.LessThanAny)}<SByte>(Vector128<SByte>, Vector128<SByte>): {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 LessThanAnySByte() { var test = new VectorBooleanBinaryOpTest__LessThanAnySByte(); // 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__LessThanAnySByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); 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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, 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<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__LessThanAnySByte testClass) { var result = Vector128.LessThanAny(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__LessThanAnySByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public VectorBooleanBinaryOpTest__LessThanAnySByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.LessThanAny( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_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.LessThanAny), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.LessThanAny), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(SByte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.LessThanAny( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Vector128.LessThanAny(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__LessThanAnySByte(); var result = Vector128.LessThanAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.LessThanAny(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.LessThanAny(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<SByte> op1, Vector128<SByte> op2, bool result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(SByte[] left, SByte[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = false; for (var i = 0; i < Op1ElementCount; i++) { expectedResult |= (left[i] < right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.LessThanAny)}<SByte>(Vector128<SByte>, Vector128<SByte>): {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,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Directed/UnrollLoop/loop3_il_d.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="loop3.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="loop3.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/GC/Features/KeepAlive/keepaliveother/keepalivehandle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Tests KeepAlive() with GCHandles using System; using System.Runtime.InteropServices; public class Test_keepalivehandle { public class Dummy { public static bool visited; ~Dummy() { //Console.WriteLine("In Finalize() of Dummy"); visited=true; } } public static int Main() { int returnValue = 0; Dummy obj = new Dummy(); Console.WriteLine("Allocating a Weak handle to object.."); GCHandle handle = GCHandle.Alloc(obj,GCHandleType.Weak); GC.Collect(); GC.WaitForPendingFinalizers(); if(Dummy.visited == false) { // has not visited the Finalize() returnValue = 100; Console.WriteLine("Test for KeepAlive() passed!"); } else { returnValue = 1; Console.WriteLine("Test for KeepAlive() failed!"); } GC.KeepAlive(obj); // will keep alive 'obj' till this point GC.Collect(); return returnValue; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Tests KeepAlive() with GCHandles using System; using System.Runtime.InteropServices; public class Test_keepalivehandle { public class Dummy { public static bool visited; ~Dummy() { //Console.WriteLine("In Finalize() of Dummy"); visited=true; } } public static int Main() { int returnValue = 0; Dummy obj = new Dummy(); Console.WriteLine("Allocating a Weak handle to object.."); GCHandle handle = GCHandle.Alloc(obj,GCHandleType.Weak); GC.Collect(); GC.WaitForPendingFinalizers(); if(Dummy.visited == false) { // has not visited the Finalize() returnValue = 100; Console.WriteLine("Test for KeepAlive() passed!"); } else { returnValue = 1; Console.WriteLine("Test for KeepAlive() failed!"); } GC.KeepAlive(obj); // will keep alive 'obj' till this point GC.Collect(); return returnValue; } }
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/jit64/opt/cse/HugeArray1.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <GCStressIncompatible>true</GCStressIncompatible> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="HugeArray1.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <GCStressIncompatible>true</GCStressIncompatible> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="HugeArray1.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/tests/JIT/Methodical/refany/gcreport_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="gcreport.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="gcreport.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,042
[wasm] Add support for symbolicating native traces from JS, using a symbols file
- adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
radical
2022-03-02T00:42:29Z
2022-03-05T02:38:26Z
1b3ef865fd71b898848a1a4b53bf062db622efa9
95770c9198df503d16b5aa9880ebc4e634a970e7
[wasm] Add support for symbolicating native traces from JS, using a symbols file. - adds support for symbolicating error, and warning messages - `debug.js.symbols` is loaded from the vfs - This is enabled by default, only for non-aot tests (since we don't strip aot tests) - Works for debugger tests too
./src/libraries/System.Security.Cryptography.Xml/tests/XmlDsigC14NTransformTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // XmlDsigC14NTransformTest.cs - Test Cases for XmlDsigC14NTransform // // Author: // Sebastien Pouliot <[email protected]> // Aleksey Sanin ([email protected]) // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // (C) 2003 Aleksey Sanin ([email protected]) // (C) 2004 Novell (http://www.novell.com) using System.IO; using System.Text; using System.Xml; using System.Xml.Resolvers; using Xunit; namespace System.Security.Cryptography.Xml.Tests { // Note: GetInnerXml is protected in XmlDsigC14NTransform making it // difficult to test properly. This class "open it up" :-) public class UnprotectedXmlDsigC14NTransform : XmlDsigC14NTransform { public XmlNodeList UnprotectedGetInnerXml() { return base.GetInnerXml(); } } public class XmlDsigC14NTransformTest { [Fact] public void Constructor_Empty() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); Assert.Equal("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", transform.Algorithm); CheckProperties(transform); } [Theory] [InlineData(true, "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments")] [InlineData(false, "http://www.w3.org/TR/2001/REC-xml-c14n-20010315")] public void Constructor_Bool(bool includeComments, string expectedAlgorithm) { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(includeComments); Assert.Equal(expectedAlgorithm, transform.Algorithm); CheckProperties(transform); } private static void CheckProperties(XmlDsigC14NTransform transform) { Assert.Null(transform.Context); Assert.Equal(new[] { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }, transform.InputTypes); Assert.Equal(new[] { typeof(Stream) }, transform.OutputTypes); } [Fact] public void GetInnerXml() { UnprotectedXmlDsigC14NTransform transform = new UnprotectedXmlDsigC14NTransform(); XmlNodeList xnl = transform.UnprotectedGetInnerXml(); Assert.Null(xnl); } static string xml = "<Test attrib='at ' xmlns=\"http://www.go-mono.com/\" > \r\n &#xD; <Toto/> text &amp; </Test >"; // GOOD for Stream input static string c14xml2 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> \n &#xD; <Toto></Toto> text &amp; </Test>"; // GOOD for XmlDocument input. The difference is because once // xml string is loaded to XmlDocument, there is no difference // between \r and &#xD;, so every \r must be handled as &#xD;. static string c14xml3 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> &#xD;\n &#xD; <Toto></Toto> text &amp; </Test>"; private XmlDocument GetDoc() { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); return doc; } [Fact] public void LoadInputAsXmlDocument() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = GetDoc(); transform.LoadInput(doc); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(c14xml3, output); } [Fact] // see LoadInputAsXmlNodeList2 description public void LoadInputAsXmlNodeList() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = GetDoc(); // Argument list just contains element Test. transform.LoadInput(doc.ChildNodes); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(@"<Test xmlns=""http://www.go-mono.com/""></Test>", output); } [Fact] // MS has a bug that those namespace declaration nodes in // the node-set are written to output. Related spec section is: // http://www.w3.org/TR/2001/REC-xml-c14n-20010315#ProcessingModel public void LoadInputAsXmlNodeList2() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = GetDoc(); transform.LoadInput(doc.SelectNodes("//*")); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); string expected = @"<Test xmlns=""http://www.go-mono.com/""><Toto></Toto></Test>"; Assert.Equal(expected, output); } [Fact] public void LoadInputAsStream() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); MemoryStream ms = new MemoryStream(); byte[] x = Encoding.ASCII.GetBytes(xml); ms.Write(x, 0, x.Length); ms.Position = 0; transform.LoadInput(ms); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(c14xml2, output); } [Fact] public void LoadInputWithUnsupportedType() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); byte[] bad = { 0xBA, 0xD }; AssertExtensions.Throws<ArgumentException>("obj", () => transform.LoadInput(bad)); } [Fact] public void UnsupportedOutput() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = new XmlDocument(); AssertExtensions.Throws<ArgumentException>("type", () => transform.GetOutput(doc.GetType())); } [Fact] public void C14NSpecExample1() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(new Uri("doc.xsl", UriKind.Relative), ""); string result = TestHelpers.ExecuteTransform(C14NSpecExample1Input, new XmlDsigC14NTransform()); Assert.Equal(C14NSpecExample1Output, result); } [Theory] [InlineData(C14NSpecExample2Input, C14NSpecExample2Output)] [InlineData(C14NSpecExample3Input, C14NSpecExample3Output)] [InlineData(C14NSpecExample4Input, C14NSpecExample4Output)] public void C14NSpecExample(string input, string expectedOutput) { string result = TestHelpers.ExecuteTransform(input, new XmlDsigC14NTransform()); Assert.Equal(expectedOutput, result); } [Fact] public void C14NSpecExample5() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("doc.txt"), "world"); string result = TestHelpers.ExecuteTransform(C14NSpecExample5Input, new XmlDsigC14NTransform(), Encoding.UTF8, resolver); Assert.Equal(C14NSpecExample5Output, result); } [Fact] public void C14NSpecExample6() { string result = TestHelpers.ExecuteTransform(C14NSpecExample6Input, new XmlDsigC14NTransform(), Encoding.GetEncoding("ISO-8859-1")); Assert.Equal(C14NSpecExample6Output, result); } // // Example 1 from C14N spec - PIs, Comments, and Outside of Document Element: // http://www.w3.org/TR/xml-c14n#Example-OutsideDoc // // Aleksey: // removed reference to an empty external DTD // static string C14NSpecExample1Input = "<?xml version=\"1.0\"?>\n" + "\n" + "<?xml-stylesheet href=\"doc.xsl\"\n" + " type=\"text/xsl\" ?>\n" + "\n" + "\n" + "<doc>Hello, world!<!-- Comment 1 --></doc>\n" + "\n" + "<?pi-without-data ?>\n\n" + "<!-- Comment 2 -->\n\n" + "<!-- Comment 3 -->\n"; static string C14NSpecExample1Output = "<?xml-stylesheet href=\"doc.xsl\"\n" + " type=\"text/xsl\" ?>\n" + "<doc>Hello, world!</doc>\n" + "<?pi-without-data?>"; // // Example 2 from C14N spec - Whitespace in Document Content: // http://www.w3.org/TR/xml-c14n#Example-WhitespaceInContent // const string C14NSpecExample2Input = "<doc>\n" + " <clean> </clean>\n" + " <dirty> A B </dirty>\n" + " <mixed>\n" + " A\n" + " <clean> </clean>\n" + " B\n" + " <dirty> A B </dirty>\n" + " C\n" + " </mixed>\n" + "</doc>\n"; const string C14NSpecExample2Output = "<doc>\n" + " <clean> </clean>\n" + " <dirty> A B </dirty>\n" + " <mixed>\n" + " A\n" + " <clean> </clean>\n" + " B\n" + " <dirty> A B </dirty>\n" + " C\n" + " </mixed>\n" + "</doc>"; // // Example 3 from C14N spec - Start and End Tags: // http://www.w3.org/TR/xml-c14n#Example-SETags // const string C14NSpecExample3Input = "<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]>\n" + "<doc>\n" + " <e1 />\n" + " <e2 ></e2>\n" + " <e3 name = \"elem3\" id=\"elem3\" />\n" + " <e4 name=\"elem4\" id=\"elem4\" ></e4>\n" + " <e5 a:attr=\"out\" b:attr=\"sorted\" attr2=\"all\" attr=\"I\'m\"\n" + " xmlns:b=\"http://www.ietf.org\" \n" + " xmlns:a=\"http://www.w3.org\"\n" + " xmlns=\"http://www.uvic.ca\"/>\n" + " <e6 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + " <e7 xmlns=\"http://www.ietf.org\">\n" + " <e8 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + " <e9 xmlns=\"\" xmlns:a=\"http://www.ietf.org\"/>\n" + " </e8>\n" + " </e7>\n" + " </e6>\n" + "</doc>\n"; const string C14NSpecExample3Output = "<doc>\n" + " <e1></e1>\n" + " <e2></e2>\n" + " <e3 id=\"elem3\" name=\"elem3\"></e3>\n" + " <e4 id=\"elem4\" name=\"elem4\"></e4>\n" + " <e5 xmlns=\"http://www.uvic.ca\" xmlns:a=\"http://www.w3.org\" xmlns:b=\"http://www.ietf.org\" attr=\"I\'m\" attr2=\"all\" b:attr=\"sorted\" a:attr=\"out\"></e5>\n" + " <e6 xmlns:a=\"http://www.w3.org\">\n" + " <e7 xmlns=\"http://www.ietf.org\">\n" + " <e8 xmlns=\"\">\n" + " <e9 xmlns:a=\"http://www.ietf.org\" attr=\"default\"></e9>\n" + // " <e9 xmlns:a=\"http://www.ietf.org\"></e9>\n" + " </e8>\n" + " </e7>\n" + " </e6>\n" + "</doc>"; // // Example 4 from C14N spec - Character Modifications and Character References: // http://www.w3.org/TR/xml-c14n#Example-Chars // // Aleksey: // This test does not include "normId" element // because it has an invalid ID attribute "id" which // should be normalized by XML parser. Currently Mono // does not support this (see comment after this example // in the spec). const string C14NSpecExample4Input = "<!DOCTYPE doc [<!ATTLIST normId id ID #IMPLIED>]>\n" + "<doc>\n" + " <text>First line&#x0d;&#10;Second line</text>\n" + " <value>&#x32;</value>\n" + " <compute><![CDATA[value>\"0\" && value<\"10\" ?\"valid\":\"error\"]]></compute>\n" + " <compute expr=\'value>\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"\'>valid</compute>\n" + " <norm attr=\' &apos; &#x20;&#13;&#xa;&#9; &apos; \'/>\n" + // " <normId id=\' &apos; &#x20;&#13;&#xa;&#9; &apos; \'/>\n" + "</doc>\n"; const string C14NSpecExample4Output = "<doc>\n" + " <text>First line&#xD;\n" + "Second line</text>\n" + " <value>2</value>\n" + " <compute>value&gt;\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"</compute>\n" + " <compute expr=\"value>&quot;0&quot; &amp;&amp; value&lt;&quot;10&quot; ?&quot;valid&quot;:&quot;error&quot;\">valid</compute>\n" + " <norm attr=\" \' &#xD;&#xA;&#x9; \' \"></norm>\n" + // " <normId id=\"\' &#xD;&#xA;&#x9; \'\"></normId>\n" + "</doc>"; // // Example 5 from C14N spec - Entity References: // http://www.w3.org/TR/xml-c14n#Example-Entities // static string C14NSpecExample5Input => "<!DOCTYPE doc [\n" + "<!ATTLIST doc attrExtEnt ENTITY #IMPLIED>\n" + "<!ENTITY ent1 \"Hello\">\n" + $"<!ENTITY ent2 SYSTEM \"doc.txt\">\n" + "<!ENTITY entExt SYSTEM \"earth.gif\" NDATA gif>\n" + "<!NOTATION gif SYSTEM \"viewgif.exe\">\n" + "]>\n" + "<doc attrExtEnt=\"entExt\">\n" + " &ent1;, &ent2;!\n" + "</doc>\n" + "\n" + "<!-- Let world.txt contain \"world\" (excluding the quotes) -->\n"; static string C14NSpecExample5Output = "<doc attrExtEnt=\"entExt\">\n" + " Hello, world!\n" + "</doc>"; // // Example 6 from C14N spec - UTF-8 Encoding: // http://www.w3.org/TR/xml-c14n#Example-UTF8 // static string C14NSpecExample6Input = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + "<doc>&#169;</doc>\n"; static string C14NSpecExample6Output = "<doc>\xC2\xA9</doc>"; [Fact] public void SimpleNamespacePrefixes() { string input = "<a:Action xmlns:a='urn:foo'>http://tempuri.org/IFoo/Echo</a:Action>"; string expected = @"<a:Action xmlns:a=""urn:foo"">http://tempuri.org/IFoo/Echo</a:Action>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(input); XmlDsigC14NTransform t = new XmlDsigC14NTransform(); t.LoadInput(doc); Stream s = t.GetOutput() as Stream; Assert.Equal(new StreamReader(s, Encoding.UTF8).ReadToEnd(), expected); } [Fact] public void OrdinalSortForAttributes() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = new XmlDocument(); string xml = "<foo Aa=\"one\" Bb=\"two\" aa=\"three\" bb=\"four\"><bar></bar></foo>"; doc.LoadXml(xml); transform.LoadInput(doc); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(xml, output); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20487")] [Fact] public void PrefixlessNamespaceOutput() { XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("foo", "urn:foo")); doc.DocumentElement.AppendChild(doc.CreateElement("bar", "urn:bar")); Assert.Equal(string.Empty, doc.DocumentElement.GetAttribute("xmlns")); XmlDsigC14NTransform t = new XmlDsigC14NTransform(); t.LoadInput(doc); Stream s = t.GetOutput() as Stream; Assert.Equal("<foo xmlns=\"urn:foo\"><bar xmlns=\"urn:bar\"></bar></foo>", new StreamReader(s, Encoding.UTF8).ReadToEnd()); Assert.Equal("urn:foo", doc.DocumentElement.GetAttribute("xmlns")); } [Fact] public void GetDigestedOutput_Null() { Assert.Throws< NullReferenceException>(() => new XmlDsigExcC14NTransform().GetDigestedOutput(null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // XmlDsigC14NTransformTest.cs - Test Cases for XmlDsigC14NTransform // // Author: // Sebastien Pouliot <[email protected]> // Aleksey Sanin ([email protected]) // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // (C) 2003 Aleksey Sanin ([email protected]) // (C) 2004 Novell (http://www.novell.com) using System.IO; using System.Text; using System.Xml; using System.Xml.Resolvers; using Xunit; namespace System.Security.Cryptography.Xml.Tests { // Note: GetInnerXml is protected in XmlDsigC14NTransform making it // difficult to test properly. This class "open it up" :-) public class UnprotectedXmlDsigC14NTransform : XmlDsigC14NTransform { public XmlNodeList UnprotectedGetInnerXml() { return base.GetInnerXml(); } } public class XmlDsigC14NTransformTest { [Fact] public void Constructor_Empty() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); Assert.Equal("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", transform.Algorithm); CheckProperties(transform); } [Theory] [InlineData(true, "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments")] [InlineData(false, "http://www.w3.org/TR/2001/REC-xml-c14n-20010315")] public void Constructor_Bool(bool includeComments, string expectedAlgorithm) { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(includeComments); Assert.Equal(expectedAlgorithm, transform.Algorithm); CheckProperties(transform); } private static void CheckProperties(XmlDsigC14NTransform transform) { Assert.Null(transform.Context); Assert.Equal(new[] { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }, transform.InputTypes); Assert.Equal(new[] { typeof(Stream) }, transform.OutputTypes); } [Fact] public void GetInnerXml() { UnprotectedXmlDsigC14NTransform transform = new UnprotectedXmlDsigC14NTransform(); XmlNodeList xnl = transform.UnprotectedGetInnerXml(); Assert.Null(xnl); } static string xml = "<Test attrib='at ' xmlns=\"http://www.go-mono.com/\" > \r\n &#xD; <Toto/> text &amp; </Test >"; // GOOD for Stream input static string c14xml2 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> \n &#xD; <Toto></Toto> text &amp; </Test>"; // GOOD for XmlDocument input. The difference is because once // xml string is loaded to XmlDocument, there is no difference // between \r and &#xD;, so every \r must be handled as &#xD;. static string c14xml3 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> &#xD;\n &#xD; <Toto></Toto> text &amp; </Test>"; private XmlDocument GetDoc() { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); return doc; } [Fact] public void LoadInputAsXmlDocument() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = GetDoc(); transform.LoadInput(doc); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(c14xml3, output); } [Fact] // see LoadInputAsXmlNodeList2 description public void LoadInputAsXmlNodeList() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = GetDoc(); // Argument list just contains element Test. transform.LoadInput(doc.ChildNodes); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(@"<Test xmlns=""http://www.go-mono.com/""></Test>", output); } [Fact] // MS has a bug that those namespace declaration nodes in // the node-set are written to output. Related spec section is: // http://www.w3.org/TR/2001/REC-xml-c14n-20010315#ProcessingModel public void LoadInputAsXmlNodeList2() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = GetDoc(); transform.LoadInput(doc.SelectNodes("//*")); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); string expected = @"<Test xmlns=""http://www.go-mono.com/""><Toto></Toto></Test>"; Assert.Equal(expected, output); } [Fact] public void LoadInputAsStream() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); MemoryStream ms = new MemoryStream(); byte[] x = Encoding.ASCII.GetBytes(xml); ms.Write(x, 0, x.Length); ms.Position = 0; transform.LoadInput(ms); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(c14xml2, output); } [Fact] public void LoadInputWithUnsupportedType() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); byte[] bad = { 0xBA, 0xD }; AssertExtensions.Throws<ArgumentException>("obj", () => transform.LoadInput(bad)); } [Fact] public void UnsupportedOutput() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = new XmlDocument(); AssertExtensions.Throws<ArgumentException>("type", () => transform.GetOutput(doc.GetType())); } [Fact] public void C14NSpecExample1() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(new Uri("doc.xsl", UriKind.Relative), ""); string result = TestHelpers.ExecuteTransform(C14NSpecExample1Input, new XmlDsigC14NTransform()); Assert.Equal(C14NSpecExample1Output, result); } [Theory] [InlineData(C14NSpecExample2Input, C14NSpecExample2Output)] [InlineData(C14NSpecExample3Input, C14NSpecExample3Output)] [InlineData(C14NSpecExample4Input, C14NSpecExample4Output)] public void C14NSpecExample(string input, string expectedOutput) { string result = TestHelpers.ExecuteTransform(input, new XmlDsigC14NTransform()); Assert.Equal(expectedOutput, result); } [Fact] public void C14NSpecExample5() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("doc.txt"), "world"); string result = TestHelpers.ExecuteTransform(C14NSpecExample5Input, new XmlDsigC14NTransform(), Encoding.UTF8, resolver); Assert.Equal(C14NSpecExample5Output, result); } [Fact] public void C14NSpecExample6() { string result = TestHelpers.ExecuteTransform(C14NSpecExample6Input, new XmlDsigC14NTransform(), Encoding.GetEncoding("ISO-8859-1")); Assert.Equal(C14NSpecExample6Output, result); } // // Example 1 from C14N spec - PIs, Comments, and Outside of Document Element: // http://www.w3.org/TR/xml-c14n#Example-OutsideDoc // // Aleksey: // removed reference to an empty external DTD // static string C14NSpecExample1Input = "<?xml version=\"1.0\"?>\n" + "\n" + "<?xml-stylesheet href=\"doc.xsl\"\n" + " type=\"text/xsl\" ?>\n" + "\n" + "\n" + "<doc>Hello, world!<!-- Comment 1 --></doc>\n" + "\n" + "<?pi-without-data ?>\n\n" + "<!-- Comment 2 -->\n\n" + "<!-- Comment 3 -->\n"; static string C14NSpecExample1Output = "<?xml-stylesheet href=\"doc.xsl\"\n" + " type=\"text/xsl\" ?>\n" + "<doc>Hello, world!</doc>\n" + "<?pi-without-data?>"; // // Example 2 from C14N spec - Whitespace in Document Content: // http://www.w3.org/TR/xml-c14n#Example-WhitespaceInContent // const string C14NSpecExample2Input = "<doc>\n" + " <clean> </clean>\n" + " <dirty> A B </dirty>\n" + " <mixed>\n" + " A\n" + " <clean> </clean>\n" + " B\n" + " <dirty> A B </dirty>\n" + " C\n" + " </mixed>\n" + "</doc>\n"; const string C14NSpecExample2Output = "<doc>\n" + " <clean> </clean>\n" + " <dirty> A B </dirty>\n" + " <mixed>\n" + " A\n" + " <clean> </clean>\n" + " B\n" + " <dirty> A B </dirty>\n" + " C\n" + " </mixed>\n" + "</doc>"; // // Example 3 from C14N spec - Start and End Tags: // http://www.w3.org/TR/xml-c14n#Example-SETags // const string C14NSpecExample3Input = "<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]>\n" + "<doc>\n" + " <e1 />\n" + " <e2 ></e2>\n" + " <e3 name = \"elem3\" id=\"elem3\" />\n" + " <e4 name=\"elem4\" id=\"elem4\" ></e4>\n" + " <e5 a:attr=\"out\" b:attr=\"sorted\" attr2=\"all\" attr=\"I\'m\"\n" + " xmlns:b=\"http://www.ietf.org\" \n" + " xmlns:a=\"http://www.w3.org\"\n" + " xmlns=\"http://www.uvic.ca\"/>\n" + " <e6 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + " <e7 xmlns=\"http://www.ietf.org\">\n" + " <e8 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + " <e9 xmlns=\"\" xmlns:a=\"http://www.ietf.org\"/>\n" + " </e8>\n" + " </e7>\n" + " </e6>\n" + "</doc>\n"; const string C14NSpecExample3Output = "<doc>\n" + " <e1></e1>\n" + " <e2></e2>\n" + " <e3 id=\"elem3\" name=\"elem3\"></e3>\n" + " <e4 id=\"elem4\" name=\"elem4\"></e4>\n" + " <e5 xmlns=\"http://www.uvic.ca\" xmlns:a=\"http://www.w3.org\" xmlns:b=\"http://www.ietf.org\" attr=\"I\'m\" attr2=\"all\" b:attr=\"sorted\" a:attr=\"out\"></e5>\n" + " <e6 xmlns:a=\"http://www.w3.org\">\n" + " <e7 xmlns=\"http://www.ietf.org\">\n" + " <e8 xmlns=\"\">\n" + " <e9 xmlns:a=\"http://www.ietf.org\" attr=\"default\"></e9>\n" + // " <e9 xmlns:a=\"http://www.ietf.org\"></e9>\n" + " </e8>\n" + " </e7>\n" + " </e6>\n" + "</doc>"; // // Example 4 from C14N spec - Character Modifications and Character References: // http://www.w3.org/TR/xml-c14n#Example-Chars // // Aleksey: // This test does not include "normId" element // because it has an invalid ID attribute "id" which // should be normalized by XML parser. Currently Mono // does not support this (see comment after this example // in the spec). const string C14NSpecExample4Input = "<!DOCTYPE doc [<!ATTLIST normId id ID #IMPLIED>]>\n" + "<doc>\n" + " <text>First line&#x0d;&#10;Second line</text>\n" + " <value>&#x32;</value>\n" + " <compute><![CDATA[value>\"0\" && value<\"10\" ?\"valid\":\"error\"]]></compute>\n" + " <compute expr=\'value>\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"\'>valid</compute>\n" + " <norm attr=\' &apos; &#x20;&#13;&#xa;&#9; &apos; \'/>\n" + // " <normId id=\' &apos; &#x20;&#13;&#xa;&#9; &apos; \'/>\n" + "</doc>\n"; const string C14NSpecExample4Output = "<doc>\n" + " <text>First line&#xD;\n" + "Second line</text>\n" + " <value>2</value>\n" + " <compute>value&gt;\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"</compute>\n" + " <compute expr=\"value>&quot;0&quot; &amp;&amp; value&lt;&quot;10&quot; ?&quot;valid&quot;:&quot;error&quot;\">valid</compute>\n" + " <norm attr=\" \' &#xD;&#xA;&#x9; \' \"></norm>\n" + // " <normId id=\"\' &#xD;&#xA;&#x9; \'\"></normId>\n" + "</doc>"; // // Example 5 from C14N spec - Entity References: // http://www.w3.org/TR/xml-c14n#Example-Entities // static string C14NSpecExample5Input => "<!DOCTYPE doc [\n" + "<!ATTLIST doc attrExtEnt ENTITY #IMPLIED>\n" + "<!ENTITY ent1 \"Hello\">\n" + $"<!ENTITY ent2 SYSTEM \"doc.txt\">\n" + "<!ENTITY entExt SYSTEM \"earth.gif\" NDATA gif>\n" + "<!NOTATION gif SYSTEM \"viewgif.exe\">\n" + "]>\n" + "<doc attrExtEnt=\"entExt\">\n" + " &ent1;, &ent2;!\n" + "</doc>\n" + "\n" + "<!-- Let world.txt contain \"world\" (excluding the quotes) -->\n"; static string C14NSpecExample5Output = "<doc attrExtEnt=\"entExt\">\n" + " Hello, world!\n" + "</doc>"; // // Example 6 from C14N spec - UTF-8 Encoding: // http://www.w3.org/TR/xml-c14n#Example-UTF8 // static string C14NSpecExample6Input = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + "<doc>&#169;</doc>\n"; static string C14NSpecExample6Output = "<doc>\xC2\xA9</doc>"; [Fact] public void SimpleNamespacePrefixes() { string input = "<a:Action xmlns:a='urn:foo'>http://tempuri.org/IFoo/Echo</a:Action>"; string expected = @"<a:Action xmlns:a=""urn:foo"">http://tempuri.org/IFoo/Echo</a:Action>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(input); XmlDsigC14NTransform t = new XmlDsigC14NTransform(); t.LoadInput(doc); Stream s = t.GetOutput() as Stream; Assert.Equal(new StreamReader(s, Encoding.UTF8).ReadToEnd(), expected); } [Fact] public void OrdinalSortForAttributes() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = new XmlDocument(); string xml = "<foo Aa=\"one\" Bb=\"two\" aa=\"three\" bb=\"four\"><bar></bar></foo>"; doc.LoadXml(xml); transform.LoadInput(doc); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(xml, output); } [ActiveIssue("https://github.com/dotnet/runtime/issues/20487")] [Fact] public void PrefixlessNamespaceOutput() { XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("foo", "urn:foo")); doc.DocumentElement.AppendChild(doc.CreateElement("bar", "urn:bar")); Assert.Equal(string.Empty, doc.DocumentElement.GetAttribute("xmlns")); XmlDsigC14NTransform t = new XmlDsigC14NTransform(); t.LoadInput(doc); Stream s = t.GetOutput() as Stream; Assert.Equal("<foo xmlns=\"urn:foo\"><bar xmlns=\"urn:bar\"></bar></foo>", new StreamReader(s, Encoding.UTF8).ReadToEnd()); Assert.Equal("urn:foo", doc.DocumentElement.GetAttribute("xmlns")); } [Fact] public void GetDigestedOutput_Null() { Assert.Throws< NullReferenceException>(() => new XmlDsigExcC14NTransform().GetDigestedOutput(null)); } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DfaMatchingState.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.Runtime.CompilerServices; using System.Net; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Captures a state of a DFA explored during matching.</summary> internal sealed class DfaMatchingState<T> where T : notnull { internal DfaMatchingState(SymbolicRegexNode<T> node, uint prevCharKind) { Node = node; PrevCharKind = prevCharKind; } internal SymbolicRegexNode<T> Node { get; } internal uint PrevCharKind { get; } internal int Id { get; set; } internal bool IsInitialState { get; set; } /// <summary>This is a deadend state</summary> internal bool IsDeadend => Node.IsNothing; /// <summary>The node must be nullable here</summary> internal int FixedLength { get { if (Node._kind == SymbolicRegexNodeKind.FixedLengthMarker) { return Node._lower; } if (Node._kind == SymbolicRegexNodeKind.Or) { Debug.Assert(Node._alts is not null); return Node._alts._maximumLength; } return -1; } } /// <summary>If true then the state is a dead-end, rejects all inputs.</summary> internal bool IsNothing => Node.IsNothing; /// <summary>If true then state starts with a ^ or $ or \A or \z or \Z</summary> internal bool StartsWithLineAnchor => Node._info.StartsWithLineAnchor; /// <summary> /// Translates a minterm predicate to a character kind, which is a general categorization of characters used /// for cheaply deciding the nullability of anchors. /// </summary> /// <remarks> /// A False predicate is handled as a special case to indicate the very last \n. /// </remarks> /// <param name="minterm">the minterm to translate</param> /// <returns>the character kind of the minterm</returns> private uint GetNextCharKind(ref T minterm) { ICharAlgebra<T> alg = Node._builder._solver; T wordLetterPredicate = Node._builder._wordLetterPredicateForAnchors; T newLinePredicate = Node._builder._newLinePredicate; // minterm == solver.False is used to represent the very last \n uint nextCharKind = CharKind.General; if (alg.False.Equals(minterm)) { nextCharKind = CharKind.NewLineS; minterm = newLinePredicate; } else if (newLinePredicate.Equals(minterm)) { // If the previous state was the start state, mark this as the very FIRST \n. // Essentially, this looks the same as the very last \n and is used to nullify // rev(\Z) in the conext of a reversed automaton. nextCharKind = PrevCharKind == CharKind.BeginningEnd ? CharKind.NewLineS : CharKind.Newline; } else if (alg.IsSatisfiable(alg.And(wordLetterPredicate, minterm))) { nextCharKind = CharKind.WordLetter; } return nextCharKind; } /// <summary> /// Compute the target state for the given input minterm. /// If <paramref name="minterm"/> is False this means that this is \n and it is the last character of the input. /// </summary> /// <param name="minterm">minterm corresponding to some input character or False corresponding to last \n</param> internal DfaMatchingState<T> Next(T minterm) { uint nextCharKind = GetNextCharKind(ref minterm); // Combined character context uint context = CharKind.Context(PrevCharKind, nextCharKind); // Compute the derivative of the node for the given context SymbolicRegexNode<T> derivative = Node.CreateDerivativeWithEffects(eager: true).TransitionOrdered(minterm, context); // nextCharKind will be the PrevCharKind of the target state // use an existing state instead if one exists already // otherwise create a new new id for it return Node._builder.CreateState(derivative, nextCharKind, capturing: false); } /// <summary> /// Compute a set of transitions for the given minterm. /// </summary> /// <param name="minterm">minterm corresponding to some input character or False corresponding to last \n</param> /// <returns>an enumeration of the transitions as pairs of the target state and a list of effects to be applied</returns> internal List<(DfaMatchingState<T> derivative, List<DerivativeEffect> effects)> NfaEagerNextWithEffects(T minterm) { uint nextCharKind = GetNextCharKind(ref minterm); // Combined character context uint context = CharKind.Context(PrevCharKind, nextCharKind); // Compute the transitions for the given context IEnumerable<(SymbolicRegexNode<T>, List<DerivativeEffect>)> derivativesAndEffects = Node.CreateDerivativeWithEffects(eager: true).TransitionsWithEffects(minterm, context); var list = new List<(DfaMatchingState<T> derivative, List<DerivativeEffect> effects)>(); foreach ((SymbolicRegexNode<T> derivative, List<DerivativeEffect> effects) in derivativesAndEffects) { // nextCharKind will be the PrevCharKind of the target state // use an existing state instead if one exists already // otherwise create a new new id for it list.Add((Node._builder.CreateState(derivative, nextCharKind, capturing: true), effects)); } return list; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool IsNullable(uint nextCharKind) { Debug.Assert(nextCharKind is 0 or CharKind.BeginningEnd or CharKind.Newline or CharKind.WordLetter or CharKind.NewLineS); uint context = CharKind.Context(PrevCharKind, nextCharKind); return Node.IsNullableFor(context); } public override bool Equals(object? obj) => obj is DfaMatchingState<T> s && PrevCharKind == s.PrevCharKind && Node.Equals(s.Node); public override int GetHashCode() => (PrevCharKind, Node).GetHashCode(); public override string ToString() => PrevCharKind == 0 ? Node.ToString() : $"({CharKind.DescribePrev(PrevCharKind)},{Node})"; #if DEBUG internal string DgmlView { get { string info = CharKind.DescribePrev(PrevCharKind); if (info != string.Empty) { info = $"Previous: {info}&#13;"; } string deriv = WebUtility.HtmlEncode(Node.ToString()); if (deriv == string.Empty) { deriv = "()"; } return $"{info}{deriv}"; } } #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.Runtime.CompilerServices; using System.Net; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Captures a state of a DFA explored during matching.</summary> internal sealed class DfaMatchingState<T> where T : notnull { internal DfaMatchingState(SymbolicRegexNode<T> node, uint prevCharKind) { Node = node; PrevCharKind = prevCharKind; } internal SymbolicRegexNode<T> Node { get; } internal uint PrevCharKind { get; } internal int Id { get; set; } internal bool IsInitialState { get; set; } /// <summary>This is a deadend state</summary> internal bool IsDeadend => Node.IsNothing; /// <summary>The node must be nullable here</summary> internal int FixedLength { get { if (Node._kind == SymbolicRegexNodeKind.FixedLengthMarker) { return Node._lower; } if (Node._kind == SymbolicRegexNodeKind.Or) { Debug.Assert(Node._alts is not null); return Node._alts._maximumLength; } return -1; } } /// <summary>If true then the state is a dead-end, rejects all inputs.</summary> internal bool IsNothing => Node.IsNothing; /// <summary>If true then state starts with a ^ or $ or \A or \z or \Z</summary> internal bool StartsWithLineAnchor => Node._info.StartsWithLineAnchor; /// <summary> /// Translates a minterm predicate to a character kind, which is a general categorization of characters used /// for cheaply deciding the nullability of anchors. /// </summary> /// <remarks> /// A False predicate is handled as a special case to indicate the very last \n. /// </remarks> /// <param name="minterm">the minterm to translate</param> /// <returns>the character kind of the minterm</returns> private uint GetNextCharKind(ref T minterm) { ICharAlgebra<T> alg = Node._builder._solver; T wordLetterPredicate = Node._builder._wordLetterPredicateForAnchors; T newLinePredicate = Node._builder._newLinePredicate; // minterm == solver.False is used to represent the very last \n uint nextCharKind = CharKind.General; if (alg.False.Equals(minterm)) { nextCharKind = CharKind.NewLineS; minterm = newLinePredicate; } else if (newLinePredicate.Equals(minterm)) { // If the previous state was the start state, mark this as the very FIRST \n. // Essentially, this looks the same as the very last \n and is used to nullify // rev(\Z) in the conext of a reversed automaton. nextCharKind = PrevCharKind == CharKind.BeginningEnd ? CharKind.NewLineS : CharKind.Newline; } else if (alg.IsSatisfiable(alg.And(wordLetterPredicate, minterm))) { nextCharKind = CharKind.WordLetter; } return nextCharKind; } /// <summary> /// Compute the target state for the given input minterm. /// If <paramref name="minterm"/> is False this means that this is \n and it is the last character of the input. /// </summary> /// <param name="minterm">minterm corresponding to some input character or False corresponding to last \n</param> internal DfaMatchingState<T> Next(T minterm) { uint nextCharKind = GetNextCharKind(ref minterm); // Combined character context uint context = CharKind.Context(PrevCharKind, nextCharKind); // Compute the derivative of the node for the given context SymbolicRegexNode<T> derivative = Node.CreateDerivative(minterm, context); // nextCharKind will be the PrevCharKind of the target state // use an existing state instead if one exists already // otherwise create a new new id for it return Node._builder.CreateState(derivative, nextCharKind, capturing: false); } /// <summary> /// Compute a set of transitions for the given minterm. /// </summary> /// <param name="minterm">minterm corresponding to some input character or False corresponding to last \n</param> /// <returns>an enumeration of the transitions as pairs of the target state and a list of effects to be applied</returns> internal List<(DfaMatchingState<T> State, DerivativeEffect[] Effects)> NfaNextWithEffects(T minterm) { uint nextCharKind = GetNextCharKind(ref minterm); // Combined character context uint context = CharKind.Context(PrevCharKind, nextCharKind); // Compute the transitions for the given context List<(SymbolicRegexNode<T>, DerivativeEffect[])> nodesAndEffects = Node.CreateNfaDerivativeWithEffects(minterm, context); var list = new List<(DfaMatchingState<T> State, DerivativeEffect[] Effects)>(); foreach ((SymbolicRegexNode<T> node, DerivativeEffect[]? effects) in nodesAndEffects) { // nextCharKind will be the PrevCharKind of the target state // use an existing state instead if one exists already // otherwise create a new new id for it list.Add((Node._builder.CreateState(node, nextCharKind, capturing: true), effects)); } return list; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool IsNullable(uint nextCharKind) { Debug.Assert(nextCharKind is 0 or CharKind.BeginningEnd or CharKind.Newline or CharKind.WordLetter or CharKind.NewLineS); uint context = CharKind.Context(PrevCharKind, nextCharKind); return Node.IsNullableFor(context); } public override bool Equals(object? obj) => obj is DfaMatchingState<T> s && PrevCharKind == s.PrevCharKind && Node.Equals(s.Node); public override int GetHashCode() => (PrevCharKind, Node).GetHashCode(); public override string ToString() => PrevCharKind == 0 ? Node.ToString() : $"({CharKind.DescribePrev(PrevCharKind)},{Node})"; #if DEBUG internal string DgmlView { get { string info = CharKind.DescribePrev(PrevCharKind); if (info != string.Empty) { info = $"Previous: {info}&#13;"; } string deriv = WebUtility.HtmlEncode(Node.ToString()); if (deriv == string.Empty) { deriv = "()"; } return $"{info}{deriv}"; } } #endif } }
1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.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; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents the exploration of a symbolic regex as a symbolic NFA</summary> internal sealed class SymbolicNFA<S> where S : notnull { private readonly IBooleanAlgebra<S> _solver; private readonly Transition[] _transitionFunction; private readonly SymbolicRegexNode<S>[] _finalCondition; private readonly HashSet<int> _unexplored; private readonly SymbolicRegexNode<S>[] _nodes; private const int DeadendState = -1; private const int UnexploredState = -2; /// <summary>If true then some states have not been explored</summary> public bool IsIncomplete => _unexplored.Count > 0; private SymbolicNFA(IBooleanAlgebra<S> solver, Transition[] transitionFunction, HashSet<int> unexplored, SymbolicRegexNode<S>[] nodes) { Debug.Assert(transitionFunction.Length > 0 && nodes.Length == transitionFunction.Length); _solver = solver; _transitionFunction = transitionFunction; _finalCondition = new SymbolicRegexNode<S>[nodes.Length]; for (int i = 0; i < nodes.Length; i++) { _finalCondition[i] = nodes[i].ExtractNullabilityTest(); } _unexplored = unexplored; _nodes = nodes; } /// <summary>Total number of states, 0 is the initial state, states are numbered from 0 to StateCount-1</summary> public int StateCount => _transitionFunction.Length; /// <summary>If true then the state has not been explored</summary> public bool IsUnexplored(int state) => _transitionFunction[state]._leaf == UnexploredState; /// <summary>If true then the state has no outgoing transitions</summary> public bool IsDeadend(int state) => _transitionFunction[state]._leaf == DeadendState; /// <summary>If true then the state involves lazy loops or has no loops</summary> public bool IsLazy(int state) => _nodes[state].IsLazy; /// <summary>Returns true if the state is nullable in the given context</summary> public bool IsFinal(int state, uint context) => _finalCondition[state].IsNullableFor(context); /// <summary>Returns true if the state is nullable for some context</summary> public bool CanBeNullable(int state) => _finalCondition[state].CanBeNullable; /// <summary>Returns true if the state is nullable for all contexts</summary> public bool IsNullable(int state) => _finalCondition[state].IsNullable; /// <summary>Gets the underlying node of the state</summary> public SymbolicRegexNode<S> GetNode(int state) => _nodes[state]; /// <summary>Enumerates all target states from the given source state</summary> /// <param name="sourceState">must be a an integer between 0 and StateCount-1</param> /// <param name="input">must be a value that acts as a minterm for the transitions emanating from the source state</param> /// <param name="context">reflects the immediate surrounding of the input and is used to determine nullability of anchors</param> public IEnumerable<int> EnumerateTargetStates(int sourceState, S input, uint context) { Debug.Assert(sourceState >= 0 && sourceState < _transitionFunction.Length); // First operate in a mode assuming no Union happens by finding the target leaf state if one exists Transition transition = _transitionFunction[sourceState]; while (transition._kind != TransitionRegexKind.Union) { switch (transition._kind) { case TransitionRegexKind.Leaf: // deadend and unexplored are negative if (transition._leaf >= 0) { Debug.Assert(transition._leaf < _transitionFunction.Length); yield return transition._leaf; } // The single target (or no target) state was found, so exit the whole enumeration yield break; case TransitionRegexKind.Conditional: Debug.Assert(transition._test is not null && transition._first is not null && transition._second is not null); // Branch according to the input condition in relation to the test condition if (_solver.IsSatisfiable(_solver.And(input, transition._test))) { // in a conditional transition input must be exclusive Debug.Assert(!_solver.IsSatisfiable(_solver.And(input, _solver.Not(transition._test)))); transition = transition._first; } else { transition = transition._second; } break; default: Debug.Assert(transition._kind == TransitionRegexKind.Lookaround && transition._look is not null && transition._first is not null && transition._second is not null); // Branch according to nullability of the lookaround condition in the given context transition = transition._look.IsNullableFor(context) ? transition._first : transition._second; break; } } // Continue operating in a mode where several target states can be yielded Debug.Assert(transition._first is not null && transition._second is not null); Stack<Transition> todo = new(); todo.Push(transition._second); todo.Push(transition._first); while (todo.TryPop(out _)) { switch (transition._kind) { case TransitionRegexKind.Leaf: // dead-end if (transition._leaf >= 0) { Debug.Assert(transition._leaf < _transitionFunction.Length); yield return transition._leaf; } break; case TransitionRegexKind.Conditional: Debug.Assert(transition._test is not null && transition._first is not null && transition._second is not null); // Branch according to the input condition in relation to the test condition if (_solver.IsSatisfiable(_solver.And(input, transition._test))) { // in a conditional transition input must be exclusive Debug.Assert(!_solver.IsSatisfiable(_solver.And(input, _solver.Not(transition._test)))); todo.Push(transition._first); } else { todo.Push(transition._second); } break; case TransitionRegexKind.Lookaround: Debug.Assert(transition._look is not null && transition._first is not null && transition._second is not null); // Branch according to nullability of the lookaround condition in the given context todo.Push(transition._look.IsNullableFor(context) ? transition._first : transition._second); break; default: Debug.Assert(transition._kind == TransitionRegexKind.Union && transition._first is not null && transition._second is not null); todo.Push(transition._second); todo.Push(transition._first); break; } } } public IEnumerable<(S, SymbolicRegexNode<S>?, int)> EnumeratePaths(int sourceState) => _transitionFunction[sourceState].EnumeratePaths(_solver, _solver.True); /// <summary> /// TODO: Explore an unexplored state on transition further. /// </summary> public void ExploreState(int state) => new NotImplementedException(); public static SymbolicNFA<S> Explore(SymbolicRegexNode<S> root, int bound) { (Dictionary<TransitionRegex<S>, Transition> cache, Dictionary<SymbolicRegexNode<S>, int> statemap, List<SymbolicRegexNode<S>> nodes, Stack<int> front) workState = (new(), new(), new(), new()); workState.nodes.Add(root); workState.statemap[root] = 0; workState.front.Push(0); Dictionary<int, Transition> transitions = new(); Stack<int> front = new(); while (workState.front.Count > 0) { Debug.Assert(front.Count == 0); // Work Breadth-First in layers, swap front with workState.front Stack<int> tmp = front; front = workState.front; workState.front = tmp; // Process all the states in front first // Any new states detected in Convert are added to workState.front while (front.Count > 0 && (bound <= 0 || workState.nodes.Count < bound)) { int q = front.Pop(); // If q was on the front it must be associated with a node but not have a transition yet Debug.Assert(q >= 0 && q < workState.nodes.Count && !transitions.ContainsKey(q)); transitions[q] = Convert(workState.nodes[q].CreateDerivative(), workState); } if (front.Count > 0) { // The state bound was reached without completing the exploration so exit the loop break; } } SymbolicRegexNode<S>[] nodes_array = workState.nodes.ToArray(); // All states are numbered from 0 to nodes.Count-1 Transition[] transition_array = new Transition[nodes_array.Length]; foreach (KeyValuePair<int, SymbolicNFA<S>.Transition> entry in transitions) { transition_array[entry.Key] = entry.Value; } HashSet<int> unexplored = new(front); unexplored.UnionWith(workState.front); foreach (int q in unexplored) { transition_array[q] = Transition.s_unexplored; } // At this point no entry can be null in the transition array Debug.Assert(Array.TrueForAll(transition_array, tr => tr is not null)); var nfa = new SymbolicNFA<S>(root._builder._solver, transition_array, unexplored, nodes_array); return nfa; } private static Transition Convert(TransitionRegex<S> tregex, (Dictionary<TransitionRegex<S>, Transition> cache, Dictionary<SymbolicRegexNode<S>, int> statemap, List<SymbolicRegexNode<S>> nodes, Stack<int> front) args) { Transition? transition; if (args.cache.TryGetValue(tregex, out transition)) { return transition; } Stack<(TransitionRegex<S>, bool)> work = new(); work.Push((tregex, false)); while (work.TryPop(out (TransitionRegex<S>, bool) top)) { TransitionRegex<S> tr = top.Item1; bool wasPushedSecondTime = top.Item2; if (wasPushedSecondTime) { Debug.Assert(tr._kind != TransitionRegexKind.Leaf && tr._first is not null && tr._second is not null); transition = new Transition(kind: tr._kind, test: tr._test, look: tr._node, first: args.cache[tr._first], second: args.cache[tr._second]); args.cache[tr] = transition; } else { switch (tr._kind) { case TransitionRegexKind.Leaf: Debug.Assert(tr._node is not null); if (tr._node.IsNothing) { args.cache[tr] = Transition.s_deadend; } else { int state; if (!args.statemap.TryGetValue(tr._node, out state)) { state = args.nodes.Count; args.nodes.Add(tr._node); args.statemap[tr._node] = state; args.front.Push(state); } transition = new Transition(kind: TransitionRegexKind.Leaf, leaf: state); args.cache[tr] = transition; } break; default: Debug.Assert(tr._first is not null && tr._second is not null); // Push the tr for the second time work.Push((tr, true)); // Push the branches also, unless they have been computed already if (!args.cache.ContainsKey(tr._second)) { work.Push((tr._second, false)); } if (!args.cache.ContainsKey(tr._first)) { work.Push((tr._first, false)); } break; } } } return args.cache[tregex]; } /// <summary>Representation of transitions inside the parent class</summary> private sealed class Transition { public readonly TransitionRegexKind _kind; public readonly int _leaf; public readonly S? _test; public readonly SymbolicRegexNode<S>? _look; public readonly Transition? _first; public readonly Transition? _second; public static readonly Transition s_deadend = new Transition(TransitionRegexKind.Leaf, leaf: DeadendState); public static readonly Transition s_unexplored = new Transition(TransitionRegexKind.Leaf, leaf: UnexploredState); internal Transition(TransitionRegexKind kind, int leaf = 0, S? test = default(S), SymbolicRegexNode<S>? look = null, Transition? first = null, Transition? second = null) { _kind = kind; _leaf = leaf; _test = test; _look = look; _first = first; _second = second; } /// <summary>Enumerates all the paths in this transition excluding paths to dead-ends (and unexplored states if any)</summary> internal IEnumerable<(S, SymbolicRegexNode<S>?, int)> EnumeratePaths(IBooleanAlgebra<S> solver, S pathCondition) { switch (_kind) { case TransitionRegexKind.Leaf: // Omit any path that leads to a deadend or is unexplored if (_leaf >= 0) { yield return (pathCondition, null, _leaf); } break; case TransitionRegexKind.Union: case TransitionRegexKind.OrderedUnion: Debug.Assert(_first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, int) path in _first.EnumeratePaths(solver, pathCondition)) { yield return path; } foreach ((S, SymbolicRegexNode<S>?, int) path in _second.EnumeratePaths(solver, pathCondition)) { yield return path; } break; case TransitionRegexKind.Conditional: Debug.Assert(_test is not null && _first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, int) path in _first.EnumeratePaths(solver, solver.And(pathCondition, _test))) { yield return path; } foreach ((S, SymbolicRegexNode<S>?, int) path in _second.EnumeratePaths(solver, solver.And(pathCondition, solver.Not(_test)))) { yield return path; } break; default: Debug.Assert(_kind is TransitionRegexKind.Lookaround && _look is not null && _first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, int) path in _first.EnumeratePaths(solver, pathCondition)) { SymbolicRegexNode<S> nullabilityTest = path.Item2 is null ? _look : _look._builder.And(path.Item2, _look); yield return (path.Item1, nullabilityTest, path.Item3); } foreach ((S, SymbolicRegexNode<S>?, int) path in _second.EnumeratePaths(solver, pathCondition)) { // Complement the nullability test SymbolicRegexNode<S> nullabilityTest = path.Item2 is null ? _look._builder.Not(_look) : _look._builder.And(path.Item2, _look._builder.Not(_look)); yield return (path.Item1, nullabilityTest, path.Item3); } break; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if DEBUG using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents the exploration of a symbolic regex as a symbolic NFA</summary> internal sealed class SymbolicNFA<S> where S : notnull { private readonly IBooleanAlgebra<S> _solver; private readonly Transition[] _transitionFunction; private readonly SymbolicRegexNode<S>[] _finalCondition; private readonly HashSet<int> _unexplored; private readonly SymbolicRegexNode<S>[] _nodes; private const int DeadendState = -1; private const int UnexploredState = -2; /// <summary>If true then some states have not been explored</summary> public bool IsIncomplete => _unexplored.Count > 0; private SymbolicNFA(IBooleanAlgebra<S> solver, Transition[] transitionFunction, HashSet<int> unexplored, SymbolicRegexNode<S>[] nodes) { Debug.Assert(transitionFunction.Length > 0 && nodes.Length == transitionFunction.Length); _solver = solver; _transitionFunction = transitionFunction; _finalCondition = new SymbolicRegexNode<S>[nodes.Length]; for (int i = 0; i < nodes.Length; i++) { _finalCondition[i] = nodes[i].ExtractNullabilityTest(); } _unexplored = unexplored; _nodes = nodes; } /// <summary>Total number of states, 0 is the initial state, states are numbered from 0 to StateCount-1</summary> public int StateCount => _transitionFunction.Length; /// <summary>If true then the state has not been explored</summary> public bool IsUnexplored(int state) => _transitionFunction[state]._leaf == UnexploredState; /// <summary>If true then the state has no outgoing transitions</summary> public bool IsDeadend(int state) => _transitionFunction[state]._leaf == DeadendState; /// <summary>If true then the state involves lazy loops or has no loops</summary> public bool IsLazy(int state) => _nodes[state].IsLazy; /// <summary>Returns true if the state is nullable in the given context</summary> public bool IsFinal(int state, uint context) => _finalCondition[state].IsNullableFor(context); /// <summary>Returns true if the state is nullable for some context</summary> public bool CanBeNullable(int state) => _finalCondition[state].CanBeNullable; /// <summary>Returns true if the state is nullable for all contexts</summary> public bool IsNullable(int state) => _finalCondition[state].IsNullable; /// <summary>Gets the underlying node of the state</summary> public SymbolicRegexNode<S> GetNode(int state) => _nodes[state]; /// <summary>Enumerates all target states from the given source state</summary> /// <param name="sourceState">must be a an integer between 0 and StateCount-1</param> /// <param name="input">must be a value that acts as a minterm for the transitions emanating from the source state</param> /// <param name="context">reflects the immediate surrounding of the input and is used to determine nullability of anchors</param> public IEnumerable<int> EnumerateTargetStates(int sourceState, S input, uint context) { Debug.Assert(sourceState >= 0 && sourceState < _transitionFunction.Length); // First operate in a mode assuming no Union happens by finding the target leaf state if one exists Transition transition = _transitionFunction[sourceState]; while (transition._kind != TransitionRegexKind.Union) { switch (transition._kind) { case TransitionRegexKind.Leaf: // deadend and unexplored are negative if (transition._leaf >= 0) { Debug.Assert(transition._leaf < _transitionFunction.Length); yield return transition._leaf; } // The single target (or no target) state was found, so exit the whole enumeration yield break; case TransitionRegexKind.Conditional: Debug.Assert(transition._test is not null && transition._first is not null && transition._second is not null); // Branch according to the input condition in relation to the test condition if (_solver.IsSatisfiable(_solver.And(input, transition._test))) { // in a conditional transition input must be exclusive Debug.Assert(!_solver.IsSatisfiable(_solver.And(input, _solver.Not(transition._test)))); transition = transition._first; } else { transition = transition._second; } break; default: Debug.Assert(transition._kind == TransitionRegexKind.Lookaround && transition._look is not null && transition._first is not null && transition._second is not null); // Branch according to nullability of the lookaround condition in the given context transition = transition._look.IsNullableFor(context) ? transition._first : transition._second; break; } } // Continue operating in a mode where several target states can be yielded Debug.Assert(transition._first is not null && transition._second is not null); Stack<Transition> todo = new(); todo.Push(transition._second); todo.Push(transition._first); while (todo.TryPop(out _)) { switch (transition._kind) { case TransitionRegexKind.Leaf: // dead-end if (transition._leaf >= 0) { Debug.Assert(transition._leaf < _transitionFunction.Length); yield return transition._leaf; } break; case TransitionRegexKind.Conditional: Debug.Assert(transition._test is not null && transition._first is not null && transition._second is not null); // Branch according to the input condition in relation to the test condition if (_solver.IsSatisfiable(_solver.And(input, transition._test))) { // in a conditional transition input must be exclusive Debug.Assert(!_solver.IsSatisfiable(_solver.And(input, _solver.Not(transition._test)))); todo.Push(transition._first); } else { todo.Push(transition._second); } break; case TransitionRegexKind.Lookaround: Debug.Assert(transition._look is not null && transition._first is not null && transition._second is not null); // Branch according to nullability of the lookaround condition in the given context todo.Push(transition._look.IsNullableFor(context) ? transition._first : transition._second); break; default: Debug.Assert(transition._kind == TransitionRegexKind.Union && transition._first is not null && transition._second is not null); todo.Push(transition._second); todo.Push(transition._first); break; } } } public IEnumerable<(S, SymbolicRegexNode<S>?, int)> EnumeratePaths(int sourceState) => _transitionFunction[sourceState].EnumeratePaths(_solver, _solver.True); /// <summary> /// TODO: Explore an unexplored state on transition further. /// </summary> public void ExploreState(int state) => new NotImplementedException(); public static SymbolicNFA<S> Explore(SymbolicRegexNode<S> root, int bound) { (Dictionary<TransitionRegex<S>, Transition> cache, Dictionary<SymbolicRegexNode<S>, int> statemap, List<SymbolicRegexNode<S>> nodes, Stack<int> front) workState = (new(), new(), new(), new()); workState.nodes.Add(root); workState.statemap[root] = 0; workState.front.Push(0); Dictionary<int, Transition> transitions = new(); Stack<int> front = new(); while (workState.front.Count > 0) { Debug.Assert(front.Count == 0); // Work Breadth-First in layers, swap front with workState.front Stack<int> tmp = front; front = workState.front; workState.front = tmp; // Process all the states in front first // Any new states detected in Convert are added to workState.front while (front.Count > 0 && (bound <= 0 || workState.nodes.Count < bound)) { int q = front.Pop(); // If q was on the front it must be associated with a node but not have a transition yet Debug.Assert(q >= 0 && q < workState.nodes.Count && !transitions.ContainsKey(q)); transitions[q] = Convert(workState.nodes[q].CreateDerivative(), workState); } if (front.Count > 0) { // The state bound was reached without completing the exploration so exit the loop break; } } SymbolicRegexNode<S>[] nodes_array = workState.nodes.ToArray(); // All states are numbered from 0 to nodes.Count-1 Transition[] transition_array = new Transition[nodes_array.Length]; foreach (KeyValuePair<int, SymbolicNFA<S>.Transition> entry in transitions) { transition_array[entry.Key] = entry.Value; } HashSet<int> unexplored = new(front); unexplored.UnionWith(workState.front); foreach (int q in unexplored) { transition_array[q] = Transition.s_unexplored; } // At this point no entry can be null in the transition array Debug.Assert(Array.TrueForAll(transition_array, tr => tr is not null)); var nfa = new SymbolicNFA<S>(root._builder._solver, transition_array, unexplored, nodes_array); return nfa; } private static Transition Convert(TransitionRegex<S> tregex, (Dictionary<TransitionRegex<S>, Transition> cache, Dictionary<SymbolicRegexNode<S>, int> statemap, List<SymbolicRegexNode<S>> nodes, Stack<int> front) args) { Transition? transition; if (args.cache.TryGetValue(tregex, out transition)) { return transition; } Stack<(TransitionRegex<S>, bool)> work = new(); work.Push((tregex, false)); while (work.TryPop(out (TransitionRegex<S>, bool) top)) { TransitionRegex<S> tr = top.Item1; bool wasPushedSecondTime = top.Item2; if (wasPushedSecondTime) { Debug.Assert(tr._kind != TransitionRegexKind.Leaf && tr._first is not null && tr._second is not null); transition = new Transition(kind: tr._kind, test: tr._test, look: tr._node, first: args.cache[tr._first], second: args.cache[tr._second]); args.cache[tr] = transition; } else { switch (tr._kind) { case TransitionRegexKind.Leaf: Debug.Assert(tr._node is not null); if (tr._node.IsNothing) { args.cache[tr] = Transition.s_deadend; } else { int state; if (!args.statemap.TryGetValue(tr._node, out state)) { state = args.nodes.Count; args.nodes.Add(tr._node); args.statemap[tr._node] = state; args.front.Push(state); } transition = new Transition(kind: TransitionRegexKind.Leaf, leaf: state); args.cache[tr] = transition; } break; default: Debug.Assert(tr._first is not null && tr._second is not null); // Push the tr for the second time work.Push((tr, true)); // Push the branches also, unless they have been computed already if (!args.cache.ContainsKey(tr._second)) { work.Push((tr._second, false)); } if (!args.cache.ContainsKey(tr._first)) { work.Push((tr._first, false)); } break; } } } return args.cache[tregex]; } /// <summary>Representation of transitions inside the parent class</summary> private sealed class Transition { public readonly TransitionRegexKind _kind; public readonly int _leaf; public readonly S? _test; public readonly SymbolicRegexNode<S>? _look; public readonly Transition? _first; public readonly Transition? _second; public static readonly Transition s_deadend = new Transition(TransitionRegexKind.Leaf, leaf: DeadendState); public static readonly Transition s_unexplored = new Transition(TransitionRegexKind.Leaf, leaf: UnexploredState); internal Transition(TransitionRegexKind kind, int leaf = 0, S? test = default(S), SymbolicRegexNode<S>? look = null, Transition? first = null, Transition? second = null) { _kind = kind; _leaf = leaf; _test = test; _look = look; _first = first; _second = second; } /// <summary>Enumerates all the paths in this transition excluding paths to dead-ends (and unexplored states if any)</summary> internal IEnumerable<(S, SymbolicRegexNode<S>?, int)> EnumeratePaths(IBooleanAlgebra<S> solver, S pathCondition) { switch (_kind) { case TransitionRegexKind.Leaf: // Omit any path that leads to a deadend or is unexplored if (_leaf >= 0) { yield return (pathCondition, null, _leaf); } break; case TransitionRegexKind.Union: Debug.Assert(_first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, int) path in _first.EnumeratePaths(solver, pathCondition)) { yield return path; } foreach ((S, SymbolicRegexNode<S>?, int) path in _second.EnumeratePaths(solver, pathCondition)) { yield return path; } break; case TransitionRegexKind.Conditional: Debug.Assert(_test is not null && _first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, int) path in _first.EnumeratePaths(solver, solver.And(pathCondition, _test))) { yield return path; } foreach ((S, SymbolicRegexNode<S>?, int) path in _second.EnumeratePaths(solver, solver.And(pathCondition, solver.Not(_test)))) { yield return path; } break; default: Debug.Assert(_kind is TransitionRegexKind.Lookaround && _look is not null && _first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, int) path in _first.EnumeratePaths(solver, pathCondition)) { SymbolicRegexNode<S> nullabilityTest = path.Item2 is null ? _look : _look._builder.And(path.Item2, _look); yield return (path.Item1, nullabilityTest, path.Item3); } foreach ((S, SymbolicRegexNode<S>?, int) path in _second.EnumeratePaths(solver, pathCondition)) { // Complement the nullability test SymbolicRegexNode<S> nullabilityTest = path.Item2 is null ? _look._builder.Not(_look) : _look._builder.And(path.Item2, _look._builder.Not(_look)); yield return (path.Item1, nullabilityTest, path.Item3); } break; } } } } } #endif
1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.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.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary> /// Builder of symbolic regexes over TElement. /// TElement is the type of elements of an effective Boolean algebra. /// Used to convert .NET regexes to symbolic regexes. /// </summary> internal sealed class SymbolicRegexBuilder<TElement> where TElement : notnull { internal readonly ICharAlgebra<TElement> _solver; internal readonly SymbolicRegexNode<TElement> _nothing; internal readonly SymbolicRegexNode<TElement> _anyChar; internal readonly SymbolicRegexNode<TElement> _anyStar; private SymbolicRegexNode<TElement>? _epsilon; internal SymbolicRegexNode<TElement> Epsilon => _epsilon ??= SymbolicRegexNode<TElement>.CreateEpsilon(this); private SymbolicRegexNode<TElement>? _beginningAnchor; internal SymbolicRegexNode<TElement> BeginningAnchor => _beginningAnchor ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.BeginningAnchor); private SymbolicRegexNode<TElement>? _endAnchor; internal SymbolicRegexNode<TElement> EndAnchor => _endAnchor ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.EndAnchor); private SymbolicRegexNode<TElement>? _endAnchorZ; internal SymbolicRegexNode<TElement> EndAnchorZ => _endAnchorZ ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.EndAnchorZ); private SymbolicRegexNode<TElement>? _endAnchorZReverse; internal SymbolicRegexNode<TElement> EndAnchorZReverse => _endAnchorZReverse ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.EndAnchorZReverse); private SymbolicRegexNode<TElement>? _bolAnchor; internal SymbolicRegexNode<TElement> BolAnchor => _bolAnchor ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.BOLAnchor); private SymbolicRegexNode<TElement>? _eolAnchor; internal SymbolicRegexNode<TElement> EolAnchor => _eolAnchor ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.EOLAnchor); private SymbolicRegexNode<TElement>? _wbAnchor; internal SymbolicRegexNode<TElement> BoundaryAnchor => _wbAnchor ??= SymbolicRegexNode<TElement>.CreateBoundaryAnchor(this, SymbolicRegexNodeKind.BoundaryAnchor); private SymbolicRegexNode<TElement>? _nwbAnchor; internal SymbolicRegexNode<TElement> NonBoundaryAnchor => _nwbAnchor ??= SymbolicRegexNode<TElement>.CreateBoundaryAnchor(this, SymbolicRegexNodeKind.NonBoundaryAnchor); private SymbolicRegexSet<TElement>? _fullSet; internal SymbolicRegexSet<TElement> FullSet => _fullSet ??= SymbolicRegexSet<TElement>.CreateFull(this); private SymbolicRegexSet<TElement>? _emptySet; internal SymbolicRegexSet<TElement> EmptySet => _emptySet ??= SymbolicRegexSet<TElement>.CreateEmpty(this); private SymbolicRegexNode<TElement>? _eagerEmptyLoop; internal SymbolicRegexNode<TElement> EagerEmptyLoop => _eagerEmptyLoop ??= SymbolicRegexNode<TElement>.CreateEagerEmptyLoop(this, Epsilon); internal TElement _wordLetterPredicateForAnchors; internal TElement _newLinePredicate; /// <summary>Partition of the input space of predicates.</summary> internal TElement[]? _minterms; private readonly Dictionary<TElement, SymbolicRegexNode<TElement>> _singletonCache = new(); // states that have been created internal HashSet<DfaMatchingState<TElement>> _stateCache = new(); // capturing states that have been created internal HashSet<DfaMatchingState<TElement>> _capturingStateCache = new(); internal readonly Dictionary<(SymbolicRegexNodeKind, SymbolicRegexNode<TElement>?, // _left SymbolicRegexNode<TElement>?, // _right int, int, TElement?, // _lower, _upper, _set SymbolicRegexSet<TElement>?, SymbolicRegexInfo), SymbolicRegexNode<TElement>> _nodeCache = new(); internal readonly Dictionary<(TransitionRegexKind, // _kind TElement?, // _test TransitionRegex<TElement>?, // _first TransitionRegex<TElement>?, // _second SymbolicRegexNode<TElement>?, // _leaf DerivativeEffect?), // _effect TransitionRegex<TElement>> _trCache = new(); /// <summary> /// Maps state ids to states, initial capacity is 1024 states. /// Each time more states are needed the length is increased by 1024. /// </summary> internal DfaMatchingState<TElement>[]? _stateArray; internal DfaMatchingState<TElement>[]? _capturingStateArray; /// <remarks> /// For these "delta" arrays, technically Volatile.Read should be used to read out an element, /// but in practice that's not needed on the runtimes in use (though that needs to be documented /// via https://github.com/dotnet/runtime/issues/63474), and use of Volatile.Read is /// contributing non-trivial overhead (https://github.com/dotnet/runtime/issues/65789). /// </remarks> internal DfaMatchingState<TElement>?[]? _delta; internal List<(DfaMatchingState<TElement>, List<DerivativeEffect>)>?[]? _capturingDelta; private const int InitialStateLimit = 1024; /// <summary>1 + Log2(_minterms.Length), the smallest k s.t. 2^k >= minterms.Length + 1</summary> internal int _mintermsLog; /// <summary> /// Maps each NFA state id to the state id of the DfaMatchingState stored in _stateArray. /// This map is used to compactly represent NFA state ids in NFA mode in order to utilize /// the property that all NFA states are small integers in one interval. /// The valid entries are 0 to <see cref="NfaStateCount"/>-1. /// </summary> internal int[] _nfaStateArray = Array.Empty<int>(); /// <summary> /// Maps the id of a DfaMatchingState to the NFA state id that it is being identifed with in the NFA. /// It is the inverse of used entries in _nfaStateArray. /// The range of this map is 0 to <see cref="NfaStateCount"/>-1. /// </summary> internal readonly Dictionary<int, int> _nfaStateArrayInverse = new(); /// <summary>Gets <see cref="_nfaStateArrayInverse"/>.Count</summary> internal int NfaStateCount => _nfaStateArrayInverse.Count; /// <summary> /// Transition function for NFA transitions in NFA mode. /// Each NFA entry maps to a list of NFA target states. /// Each list of target states is without repetitions. /// If the entry is null then the targets states have not been computed yet. /// </summary> internal int[]?[] _nfaDelta = Array.Empty<int[]>(); /// <summary>Create a new symbolic regex builder.</summary> internal SymbolicRegexBuilder(ICharAlgebra<TElement> solver) { // Solver must be set first, else it will cause null reference exception in the following _solver = solver; // minterms = null if partition of the solver is undefined and returned as null _minterms = solver.GetMinterms(); if (_minterms == null) { _mintermsLog = -1; } else { _stateArray = new DfaMatchingState<TElement>[InitialStateLimit]; _capturingStateArray = new DfaMatchingState<TElement>[InitialStateLimit]; // the extra +1 slot with id minterms.Length is reserved for \Z (last occurrence of \n) _mintermsLog = BitOperations.Log2((uint)_minterms.Length) + 1; _delta = new DfaMatchingState<TElement>[InitialStateLimit << _mintermsLog]; _capturingDelta = new List<(DfaMatchingState<TElement>, List<DerivativeEffect>)>[InitialStateLimit << _mintermsLog]; } // initialized to False but updated later to the actual condition ony if \b or \B occurs anywhere in the regex // this implies that if a regex never uses \b or \B then the character context will never // update the previous character context to distinguish word and nonword letters _wordLetterPredicateForAnchors = solver.False; // initialized to False but updated later to the actual condition of \n only if a line anchor occurs anywhere in the regex // this implies that if a regex never uses a line anchor then the character context will never // update the previous character context to mark that the previous caharcter was \n _newLinePredicate = solver.False; _nothing = SymbolicRegexNode<TElement>.CreateFalse(this); _anyChar = SymbolicRegexNode<TElement>.CreateTrue(this); _anyStar = SymbolicRegexNode<TElement>.CreateLoop(this, _anyChar, 0, int.MaxValue, isLazy: false); // --- initialize singletonCache --- _singletonCache[_solver.False] = _nothing; _singletonCache[_solver.True] = _anyChar; } /// <summary>Lookup the actual minterm based on its ID.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal TElement GetMinterm(int mintermId) { TElement[]? minterms = _minterms; Debug.Assert(minterms is not null); return (uint)mintermId < (uint)minterms.Length ? minterms[mintermId] : _solver.False; // minterm=False represents \Z } /// <summary> /// Make a disjunction of given nodes, simplify by eliminating any regex that accepts no inputs /// </summary> internal SymbolicRegexNode<TElement> Or(params SymbolicRegexNode<TElement>[] nodes) => SymbolicRegexNode<TElement>.Or(this, nodes); /// <summary> /// Make an ordered disjunction of given nodes, simplify by eliminating any regex that accepts no inputs /// </summary> internal SymbolicRegexNode<TElement> OrderedOr(params SymbolicRegexNode<TElement>[] nodes) { SymbolicRegexNode<TElement>? or = null; foreach (SymbolicRegexNode<TElement> elem in nodes) { if (elem.IsNothing) continue; or = or is null ? elem : SymbolicRegexNode<TElement>.OrderedOr(this, or, elem); if (elem.IsAnyStar) break; // .* is the absorbing element } return or ?? _nothing; } /// <summary> /// Make a conjunction of given nodes, simplify by eliminating nodes that accept everything /// </summary> internal SymbolicRegexNode<TElement> And(params SymbolicRegexNode<TElement>[] nodes) => SymbolicRegexNode<TElement>.And(this, nodes); /// <summary> /// Make a disjunction of given set of nodes, simplify by eliminating any regex that accepts no inputs /// </summary> internal SymbolicRegexNode<TElement> Or(SymbolicRegexSet<TElement> set) => set.IsNothing ? _nothing : set.IsEverything ? _anyStar : set.IsSingleton ? set.GetSingletonElement() : SymbolicRegexNode<TElement>.Or(this, set); internal SymbolicRegexNode<TElement> Or(SymbolicRegexNode<TElement> x, SymbolicRegexNode<TElement> y) => x == _anyStar || y == _anyStar ? _anyStar : x == _nothing ? y : y == _nothing ? x : SymbolicRegexNode<TElement>.Or(this, x, y); /// <summary> /// Make a conjunction of given set, simplify by eliminating any regex that accepts all inputs, /// returns the empty regex if the regex accepts nothing /// </summary> internal SymbolicRegexNode<TElement> And(SymbolicRegexSet<TElement> set) => set.IsNothing ? _nothing : set.IsEverything ? _anyStar : set.IsSingleton ? set.GetSingletonElement() : SymbolicRegexNode<TElement>.And(this, set); /// <summary> /// Make a concatenation of given nodes, if any regex is nothing then return nothing, eliminate /// intermediate epsilons, if tryCreateFixedLengthMarker and length is fixed, add a fixed length /// marker at the end. /// </summary> internal SymbolicRegexNode<TElement> CreateConcat(SymbolicRegexNode<TElement>[] nodes, bool tryCreateFixedLengthMarker) { SymbolicRegexNode<TElement> sr = Epsilon; if (nodes.Length != 0) { if (tryCreateFixedLengthMarker) { int length = CalculateFixedLength(nodes); if (length >= 0) { sr = CreateFixedLengthMarker(length); } } // Iterate through all the nodes concatenating them together. We iterate in reverse in order to // avoid quadratic behavior in combination with the called CreateConcat method. for (int i = nodes.Length - 1; i >= 0; i--) { // If there's a nothing in the list, the whole concatenation can't match, so just return nothing. if (nodes[i] == _nothing) { return _nothing; } sr = SymbolicRegexNode<TElement>.CreateConcat(this, nodes[i], sr); } } return sr; } internal SymbolicRegexNode<TElement> CreateConcat(SymbolicRegexNode<TElement> left, SymbolicRegexNode<TElement> right) => SymbolicRegexNode<TElement>.CreateConcat(this, left, right); private int CalculateFixedLength(SymbolicRegexNode<TElement>[] nodes) { int length = 0; foreach (SymbolicRegexNode<TElement> node in nodes) { int k = node.GetFixedLength(); if (k < 0) { return -1; } length += k; } return length; } /// <summary> /// Make loop regex /// </summary> internal SymbolicRegexNode<TElement> CreateLoop(SymbolicRegexNode<TElement> node, bool isLazy, int lower = 0, int upper = int.MaxValue) { // If the lower and upper bound are both 1, then the node would be processed once and only once, so we can just return that node. if (lower == 1 && upper == 1) { return node; } // If the lower and upper bound are both 0, this is actually empty. if (lower == 0 && upper == 0) { return Epsilon; } // If this is equivalent to any*, return that. if (!isLazy && lower == 0 && upper == int.MaxValue && node._kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(node._set is not null); if (_solver.AreEquivalent(_solver.True, node._set)) { return _anyStar; } } // Otherwise, create the loop. return SymbolicRegexNode<TElement>.CreateLoop(this, node, lower, upper, isLazy); } /// <summary>Creates a "singleton", which matches a single character.</summary> internal SymbolicRegexNode<TElement> CreateSingleton(TElement set) { // We maintain a cache of singletons, under the assumption that it's likely the same one/notone/set appears // multiple times in the same pattern. First consult the cache, and then create a new singleton if one didn't exist. ref SymbolicRegexNode<TElement>? result = ref CollectionsMarshal.GetValueRefOrAddDefault(_singletonCache, set, out _); return result ??= SymbolicRegexNode<TElement>.CreateSingleton(this, set); } /// <summary>Creates a fixed length marker for the end of a sequence.</summary> internal SymbolicRegexNode<TElement> CreateFixedLengthMarker(int length) => SymbolicRegexNode<TElement>.CreateFixedLengthMarker(this, length); /// <summary> /// Make a complemented node /// </summary> /// <param name="node">node to be complemented</param> /// <returns></returns> internal SymbolicRegexNode<TElement> Not(SymbolicRegexNode<TElement> node) => SymbolicRegexNode<TElement>.Not(this, node); internal SymbolicRegexNode<TElement> CreateCapture(SymbolicRegexNode<TElement> child, int captureNum) => CreateConcat(CreateCaptureStart(captureNum), CreateConcat(child, CreateCaptureEnd(captureNum))); internal SymbolicRegexNode<TElement> CreateCaptureStart(int captureNum) => SymbolicRegexNode<TElement>.CreateCaptureStart(this, captureNum); internal SymbolicRegexNode<TElement> CreateCaptureEnd(int captureNum) => SymbolicRegexNode<TElement>.CreateCaptureEnd(this, captureNum); internal SymbolicRegexNode<T> Transform<T>(SymbolicRegexNode<TElement> sr, SymbolicRegexBuilder<T> builder, Func<TElement, T> predicateTransformer) where T : notnull { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(Transform, sr, builder, predicateTransformer); } switch (sr._kind) { case SymbolicRegexNodeKind.BeginningAnchor: return builder.BeginningAnchor; case SymbolicRegexNodeKind.EndAnchor: return builder.EndAnchor; case SymbolicRegexNodeKind.EndAnchorZ: return builder.EndAnchorZ; case SymbolicRegexNodeKind.EndAnchorZReverse: return builder.EndAnchorZReverse; case SymbolicRegexNodeKind.BOLAnchor: return builder.BolAnchor; case SymbolicRegexNodeKind.EOLAnchor: return builder.EolAnchor; case SymbolicRegexNodeKind.BoundaryAnchor: return builder.BoundaryAnchor; case SymbolicRegexNodeKind.NonBoundaryAnchor: return builder.NonBoundaryAnchor; case SymbolicRegexNodeKind.FixedLengthMarker: return builder.CreateFixedLengthMarker(sr._lower); case SymbolicRegexNodeKind.Epsilon: return builder.Epsilon; case SymbolicRegexNodeKind.Singleton: Debug.Assert(sr._set is not null); return builder.CreateSingleton(predicateTransformer(sr._set)); case SymbolicRegexNodeKind.Loop: Debug.Assert(sr._left is not null); return builder.CreateLoop(Transform(sr._left, builder, predicateTransformer), sr.IsLazy, sr._lower, sr._upper); case SymbolicRegexNodeKind.Or: Debug.Assert(sr._alts is not null); return builder.Or(sr._alts.Transform(builder, predicateTransformer)); case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(sr._left is not null && sr._right is not null); return builder.OrderedOr(Transform(sr._left, builder, predicateTransformer), Transform(sr._right, builder, predicateTransformer)); case SymbolicRegexNodeKind.And: Debug.Assert(sr._alts is not null); return builder.And(sr._alts.Transform(builder, predicateTransformer)); case SymbolicRegexNodeKind.CaptureStart: return builder.CreateCaptureStart(sr._lower); case SymbolicRegexNodeKind.CaptureEnd: return builder.CreateCaptureEnd(sr._lower); case SymbolicRegexNodeKind.Concat: { List<SymbolicRegexNode<TElement>> sr_elems = sr.ToList(); SymbolicRegexNode<T>[] sr_elems_trasformed = new SymbolicRegexNode<T>[sr_elems.Count]; for (int i = 0; i < sr_elems.Count; i++) { sr_elems_trasformed[i] = Transform(sr_elems[i], builder, predicateTransformer); } return builder.CreateConcat(sr_elems_trasformed, false); } default: Debug.Assert(sr._kind == SymbolicRegexNodeKind.Not); Debug.Assert(sr._left is not null); return builder.Not(Transform(sr._left, builder, predicateTransformer)); } } /// <summary> /// Create a state with given node and previous character context. /// </summary> /// <param name="node">the pattern that this state will represent</param> /// <param name="prevCharKind">the kind of the character that led to this state</param> /// <param name="disableCaching">if true, then state won't be cached</param> /// <param name="capturing">whether to use the separate space of states with capturing transitions or not</param> /// <returns></returns> public DfaMatchingState<TElement> CreateState(SymbolicRegexNode<TElement> node, uint prevCharKind, bool disableCaching = false, bool capturing = false) { //first prune the anchors in the node TElement WLpred = _wordLetterPredicateForAnchors; TElement startSet = node.GetStartSet(); //true if the startset of the node overlaps with some wordletter or the node can be nullable bool contWithWL = node.CanBeNullable || _solver.IsSatisfiable(_solver.And(WLpred, startSet)); //true if the startset of the node overlaps with some nonwordletter or the node can be nullable bool contWithNWL = node.CanBeNullable || _solver.IsSatisfiable(_solver.And(_solver.Not(WLpred), startSet)); SymbolicRegexNode<TElement> pruned_node = node.PruneAnchors(prevCharKind, contWithWL, contWithNWL); var s = new DfaMatchingState<TElement>(pruned_node, prevCharKind); if (!(capturing ? _capturingStateCache : _stateCache).TryGetValue(s, out DfaMatchingState<TElement>? state)) { // do not cache set of states as states in NFA mode if (disableCaching && pruned_node.Kind == SymbolicRegexNodeKind.Or) { s.Id = -1; // mark the Id as invalid state = s; } else { state = MakeNewState(s, capturing); } } return state; } private DfaMatchingState<TElement> MakeNewState(DfaMatchingState<TElement> state, bool capturing) { lock (this) { HashSet<DfaMatchingState<TElement>> cache = capturing ? _capturingStateCache : _stateCache; state.Id = cache.Count; cache.Add(state); Debug.Assert(_stateArray is not null && _capturingStateArray is not null); const int GrowthSize = 1024; if (capturing) { if (state.Id == _capturingStateArray.Length) { int newsize = _capturingStateArray.Length + GrowthSize; Array.Resize(ref _capturingStateArray, newsize); Array.Resize(ref _capturingDelta, newsize << _mintermsLog); } _capturingStateArray[state.Id] = state; } else { if (state.Id == _stateArray.Length) { int newsize = _stateArray.Length + GrowthSize; Array.Resize(ref _stateArray, newsize); Array.Resize(ref _delta, newsize << _mintermsLog); } _stateArray[state.Id] = state; } return state; } } /// <summary> /// Make an NFA state for the given node and previous character kind. /// </summary> public int CreateNfaState(SymbolicRegexNode<TElement> node, uint prevCharKind) { // TBD: OrderedOr Debug.Assert(node.Kind != SymbolicRegexNodeKind.Or); // First make the underlying core state DfaMatchingState<TElement> coreState = CreateState(node, prevCharKind); if (!_nfaStateArrayInverse.TryGetValue(coreState.Id, out int nfaStateId)) { nfaStateId = MakeNewNfaState(coreState.Id); } return nfaStateId; } /// <summary>Critical region that creates a new NFA state for the underlying core state</summary> private int MakeNewNfaState(int coreStateId) { lock (this) { if (NfaStateCount == _nfaStateArray.Length) { // TBD: is 1024 reasonable? int newsize = _nfaStateArray.Length + 1024; Array.Resize(ref _nfaStateArray, newsize); Array.Resize(ref _nfaDelta, newsize << _mintermsLog); // TBD: capturing } int nfaStateId = NfaStateCount; _nfaStateArray[nfaStateId] = coreStateId; _nfaStateArrayInverse[coreStateId] = nfaStateId; return nfaStateId; } } /// <summary>Gets the core state corresponding to the NFA state</summary> public DfaMatchingState<TElement> GetCoreState(int nfaStateId) { Debug.Assert(_stateArray is not null); Debug.Assert(nfaStateId < _nfaStateArray.Length); Debug.Assert(_nfaStateArray[nfaStateId] < _stateArray.Length); return _stateArray[_nfaStateArray[nfaStateId]]; } /// <summary>Critical region for defining a new core transition</summary> public DfaMatchingState<TElement> CreateNewTransition(DfaMatchingState<TElement> sourceState, int mintermId, int offset) { TryCreateNewTransition(sourceState, mintermId, offset, checkThreshold: false, out DfaMatchingState<TElement>? nextState); Debug.Assert(nextState is not null); return nextState; } /// <summary>Gets or creates a new DFA transition.</summary> public bool TryCreateNewTransition( DfaMatchingState<TElement> sourceState, int mintermId, int offset, bool checkThreshold, [NotNullWhen(true)] out DfaMatchingState<TElement>? nextState) { Debug.Assert(_delta is not null); lock (this) { Debug.Assert(offset < _delta.Length); // check if meanwhile delta[offset] has become defined possibly by another thread DfaMatchingState<TElement>? targetState = _delta[offset]; if (targetState is null) { if (checkThreshold && _stateCache.Count >= SymbolicRegexMatcher<TElement>.NfaThreshold) { nextState = null; return false; } targetState = sourceState.Next(GetMinterm(mintermId)); Volatile.Write(ref _delta[offset], targetState); } nextState = targetState; return true; } } /// <summary>Gets or creates a new NFA transition.</summary> public int[] CreateNewNfaTransition(int nfaStateId, int mintermId, int nfaOffset) { Debug.Assert(_delta is not null); lock (this) { Debug.Assert(nfaOffset < _nfaDelta.Length); // check if meanwhile the nfaoffset has become defined possibly by another thread int[]? targets = _nfaDelta[nfaOffset]; if (targets is null) { // Create the underlying transition from the core state corresponding to the nfa state DfaMatchingState<TElement> coreState = GetCoreState(nfaStateId); int coreOffset = (coreState.Id << _mintermsLog) | mintermId; DfaMatchingState<TElement>? coreTarget = _delta[coreOffset] ?? CreateNewTransition(coreState, mintermId, coreOffset); // TBD: OrderedOr if (coreTarget.Node.Kind == SymbolicRegexNodeKind.Or) { // Create separate NFA states for all members of a disjunction // Here duplicate NFA states cannot arise because there are no duplicate nodes in the disjunction SymbolicRegexSet<TElement>? alts = coreTarget.Node._alts; Debug.Assert(alts is not null); targets = new int[alts.Count]; int targetIndex = 0; foreach (SymbolicRegexNode<TElement> q in alts) { Debug.Assert(!q.IsNothing); targets[targetIndex++] = CreateNfaState(q, coreTarget.PrevCharKind); } Debug.Assert(targetIndex == targets.Length); } else if (coreTarget.IsDeadend) { // Omit deadend states from the target list of states // target list being empty means that the NFA state itself is a deadend targets = Array.Empty<int>(); } else { // Add the single NFA target state correponding to the core target state if (!_nfaStateArrayInverse.TryGetValue(coreTarget.Id, out int nfaTargetId)) { nfaTargetId = MakeNewNfaState(coreTarget.Id); } targets = new[] { nfaTargetId }; } Volatile.Write(ref _nfaDelta[nfaOffset], targets); } return 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.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary> /// Builder of symbolic regexes over TElement. /// TElement is the type of elements of an effective Boolean algebra. /// Used to convert .NET regexes to symbolic regexes. /// </summary> internal sealed class SymbolicRegexBuilder<TElement> where TElement : notnull { internal readonly ICharAlgebra<TElement> _solver; internal readonly SymbolicRegexNode<TElement> _nothing; internal readonly SymbolicRegexNode<TElement> _anyChar; internal readonly SymbolicRegexNode<TElement> _anyStar; private SymbolicRegexNode<TElement>? _epsilon; internal SymbolicRegexNode<TElement> Epsilon => _epsilon ??= SymbolicRegexNode<TElement>.CreateEpsilon(this); private SymbolicRegexNode<TElement>? _beginningAnchor; internal SymbolicRegexNode<TElement> BeginningAnchor => _beginningAnchor ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.BeginningAnchor); private SymbolicRegexNode<TElement>? _endAnchor; internal SymbolicRegexNode<TElement> EndAnchor => _endAnchor ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.EndAnchor); private SymbolicRegexNode<TElement>? _endAnchorZ; internal SymbolicRegexNode<TElement> EndAnchorZ => _endAnchorZ ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.EndAnchorZ); private SymbolicRegexNode<TElement>? _endAnchorZReverse; internal SymbolicRegexNode<TElement> EndAnchorZReverse => _endAnchorZReverse ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.EndAnchorZReverse); private SymbolicRegexNode<TElement>? _bolAnchor; internal SymbolicRegexNode<TElement> BolAnchor => _bolAnchor ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.BOLAnchor); private SymbolicRegexNode<TElement>? _eolAnchor; internal SymbolicRegexNode<TElement> EolAnchor => _eolAnchor ??= SymbolicRegexNode<TElement>.CreateBeginEndAnchor(this, SymbolicRegexNodeKind.EOLAnchor); private SymbolicRegexNode<TElement>? _wbAnchor; internal SymbolicRegexNode<TElement> BoundaryAnchor => _wbAnchor ??= SymbolicRegexNode<TElement>.CreateBoundaryAnchor(this, SymbolicRegexNodeKind.BoundaryAnchor); private SymbolicRegexNode<TElement>? _nwbAnchor; internal SymbolicRegexNode<TElement> NonBoundaryAnchor => _nwbAnchor ??= SymbolicRegexNode<TElement>.CreateBoundaryAnchor(this, SymbolicRegexNodeKind.NonBoundaryAnchor); private SymbolicRegexSet<TElement>? _fullSet; internal SymbolicRegexSet<TElement> FullSet => _fullSet ??= SymbolicRegexSet<TElement>.CreateFull(this); private SymbolicRegexSet<TElement>? _emptySet; internal SymbolicRegexSet<TElement> EmptySet => _emptySet ??= SymbolicRegexSet<TElement>.CreateEmpty(this); private SymbolicRegexNode<TElement>? _eagerEmptyLoop; internal SymbolicRegexNode<TElement> EagerEmptyLoop => _eagerEmptyLoop ??= SymbolicRegexNode<TElement>.CreateEagerEmptyLoop(this, Epsilon); internal TElement _wordLetterPredicateForAnchors; internal TElement _newLinePredicate; /// <summary>Partition of the input space of predicates.</summary> internal TElement[]? _minterms; private readonly Dictionary<TElement, SymbolicRegexNode<TElement>> _singletonCache = new(); // states that have been created internal HashSet<DfaMatchingState<TElement>> _stateCache = new(); // capturing states that have been created internal HashSet<DfaMatchingState<TElement>> _capturingStateCache = new(); internal readonly Dictionary<(SymbolicRegexNodeKind, SymbolicRegexNode<TElement>?, // _left SymbolicRegexNode<TElement>?, // _right int, int, TElement?, // _lower, _upper, _set SymbolicRegexSet<TElement>?, SymbolicRegexInfo), SymbolicRegexNode<TElement>> _nodeCache = new(); #if DEBUG internal readonly Dictionary<(TransitionRegexKind, // _kind TElement?, // _test TransitionRegex<TElement>?, // _first TransitionRegex<TElement>?, // _second SymbolicRegexNode<TElement>?, // _leaf DerivativeEffect?), // _effect TransitionRegex<TElement>> _trCache = new(); #endif /// <summary> /// Maps state ids to states, initial capacity is 1024 states. /// Each time more states are needed the length is increased by 1024. /// </summary> internal DfaMatchingState<TElement>[]? _stateArray; internal DfaMatchingState<TElement>[]? _capturingStateArray; /// <remarks> /// For these "delta" arrays, technically Volatile.Read should be used to read out an element, /// but in practice that's not needed on the runtimes in use (though that needs to be documented /// via https://github.com/dotnet/runtime/issues/63474), and use of Volatile.Read is /// contributing non-trivial overhead (https://github.com/dotnet/runtime/issues/65789). /// </remarks> internal DfaMatchingState<TElement>?[]? _delta; internal List<(DfaMatchingState<TElement>, DerivativeEffect[])>?[]? _capturingDelta; private const int InitialStateLimit = 1024; /// <summary>1 + Log2(_minterms.Length), the smallest k s.t. 2^k >= minterms.Length + 1</summary> internal int _mintermsLog; /// <summary> /// Maps each NFA state id to the state id of the DfaMatchingState stored in _stateArray. /// This map is used to compactly represent NFA state ids in NFA mode in order to utilize /// the property that all NFA states are small integers in one interval. /// The valid entries are 0 to <see cref="NfaStateCount"/>-1. /// </summary> internal int[] _nfaStateArray = Array.Empty<int>(); /// <summary> /// Maps the id of a DfaMatchingState to the NFA state id that it is being identifed with in the NFA. /// It is the inverse of used entries in _nfaStateArray. /// The range of this map is 0 to <see cref="NfaStateCount"/>-1. /// </summary> internal readonly Dictionary<int, int> _nfaStateArrayInverse = new(); /// <summary>Gets <see cref="_nfaStateArrayInverse"/>.Count</summary> internal int NfaStateCount => _nfaStateArrayInverse.Count; /// <summary> /// Transition function for NFA transitions in NFA mode. /// Each NFA entry maps to a list of NFA target states. /// Each list of target states is without repetitions. /// If the entry is null then the targets states have not been computed yet. /// </summary> internal int[]?[] _nfaDelta = Array.Empty<int[]>(); /// <summary>Create a new symbolic regex builder.</summary> internal SymbolicRegexBuilder(ICharAlgebra<TElement> solver) { // Solver must be set first, else it will cause null reference exception in the following _solver = solver; // minterms = null if partition of the solver is undefined and returned as null _minterms = solver.GetMinterms(); if (_minterms == null) { _mintermsLog = -1; } else { _stateArray = new DfaMatchingState<TElement>[InitialStateLimit]; _capturingStateArray = new DfaMatchingState<TElement>[InitialStateLimit]; // the extra +1 slot with id minterms.Length is reserved for \Z (last occurrence of \n) _mintermsLog = BitOperations.Log2((uint)_minterms.Length) + 1; _delta = new DfaMatchingState<TElement>[InitialStateLimit << _mintermsLog]; _capturingDelta = new List<(DfaMatchingState<TElement>, DerivativeEffect[])>[InitialStateLimit << _mintermsLog]; } // initialized to False but updated later to the actual condition ony if \b or \B occurs anywhere in the regex // this implies that if a regex never uses \b or \B then the character context will never // update the previous character context to distinguish word and nonword letters _wordLetterPredicateForAnchors = solver.False; // initialized to False but updated later to the actual condition of \n only if a line anchor occurs anywhere in the regex // this implies that if a regex never uses a line anchor then the character context will never // update the previous character context to mark that the previous caharcter was \n _newLinePredicate = solver.False; _nothing = SymbolicRegexNode<TElement>.CreateFalse(this); _anyChar = SymbolicRegexNode<TElement>.CreateTrue(this); _anyStar = SymbolicRegexNode<TElement>.CreateLoop(this, _anyChar, 0, int.MaxValue, isLazy: false); // --- initialize singletonCache --- _singletonCache[_solver.False] = _nothing; _singletonCache[_solver.True] = _anyChar; } /// <summary>Lookup the actual minterm based on its ID.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal TElement GetMinterm(int mintermId) { TElement[]? minterms = _minterms; Debug.Assert(minterms is not null); return (uint)mintermId < (uint)minterms.Length ? minterms[mintermId] : _solver.False; // minterm=False represents \Z } /// <summary> /// Make a disjunction of given nodes, simplify by eliminating any regex that accepts no inputs /// </summary> internal SymbolicRegexNode<TElement> Or(params SymbolicRegexNode<TElement>[] nodes) => SymbolicRegexNode<TElement>.Or(this, nodes); /// <summary> /// Make an ordered disjunction of given nodes, simplify by eliminating any regex that accepts no inputs /// </summary> internal SymbolicRegexNode<TElement> OrderedOr(params SymbolicRegexNode<TElement>[] nodes) { SymbolicRegexNode<TElement>? or = null; // Iterate backwards to avoid quadratic rebuilding of the Or nodes, which are always simplified to // right associative form. Concretely: // In (a|(b|c)) | d -> (a|(b|(c|d)) the first argument is not a subtree of the result. // In a | (b|(c|d)) -> (a|(b|(c|d)) the second argument is a subtree of the result. // The first case performs linear work for each element, leading to a quadratic blowup. for (int i = nodes.Length - 1; i >= 0; --i) { SymbolicRegexNode<TElement> elem = nodes[i]; if (elem.IsNothing) continue; or = or is null ? elem : SymbolicRegexNode<TElement>.OrderedOr(this, elem, or); if (elem.IsAnyStar) or = elem; // .* is the absorbing element } return or ?? _nothing; } /// <summary> /// Make a conjunction of given nodes, simplify by eliminating nodes that accept everything /// </summary> internal SymbolicRegexNode<TElement> And(params SymbolicRegexNode<TElement>[] nodes) => SymbolicRegexNode<TElement>.And(this, nodes); /// <summary> /// Make a disjunction of given set of nodes, simplify by eliminating any regex that accepts no inputs /// </summary> internal SymbolicRegexNode<TElement> Or(SymbolicRegexSet<TElement> set) => set.IsNothing ? _nothing : set.IsEverything ? _anyStar : set.IsSingleton ? set.GetSingletonElement() : SymbolicRegexNode<TElement>.Or(this, set); internal SymbolicRegexNode<TElement> Or(SymbolicRegexNode<TElement> x, SymbolicRegexNode<TElement> y) => x == _anyStar || y == _anyStar ? _anyStar : x == _nothing ? y : y == _nothing ? x : SymbolicRegexNode<TElement>.Or(this, x, y); /// <summary> /// Make a conjunction of given set, simplify by eliminating any regex that accepts all inputs, /// returns the empty regex if the regex accepts nothing /// </summary> internal SymbolicRegexNode<TElement> And(SymbolicRegexSet<TElement> set) => set.IsNothing ? _nothing : set.IsEverything ? _anyStar : set.IsSingleton ? set.GetSingletonElement() : SymbolicRegexNode<TElement>.And(this, set); /// <summary> /// Make a concatenation of given nodes, if any regex is nothing then return nothing, eliminate /// intermediate epsilons, if tryCreateFixedLengthMarker and length is fixed, add a fixed length /// marker at the end. /// </summary> internal SymbolicRegexNode<TElement> CreateConcat(SymbolicRegexNode<TElement>[] nodes, bool tryCreateFixedLengthMarker) { SymbolicRegexNode<TElement> sr = Epsilon; if (nodes.Length != 0) { if (tryCreateFixedLengthMarker) { int length = CalculateFixedLength(nodes); if (length >= 0) { sr = CreateFixedLengthMarker(length); } } // Iterate through all the nodes concatenating them together. We iterate in reverse in order to // avoid quadratic behavior in combination with the called CreateConcat method. for (int i = nodes.Length - 1; i >= 0; i--) { // If there's a nothing in the list, the whole concatenation can't match, so just return nothing. if (nodes[i] == _nothing) { return _nothing; } sr = SymbolicRegexNode<TElement>.CreateConcat(this, nodes[i], sr); } } return sr; } internal SymbolicRegexNode<TElement> CreateConcat(SymbolicRegexNode<TElement> left, SymbolicRegexNode<TElement> right) => SymbolicRegexNode<TElement>.CreateConcat(this, left, right); private int CalculateFixedLength(SymbolicRegexNode<TElement>[] nodes) { int length = 0; foreach (SymbolicRegexNode<TElement> node in nodes) { int k = node.GetFixedLength(); if (k < 0) { return -1; } length += k; } return length; } /// <summary> /// Make loop regex /// </summary> internal SymbolicRegexNode<TElement> CreateLoop(SymbolicRegexNode<TElement> node, bool isLazy, int lower = 0, int upper = int.MaxValue) { // If the lower and upper bound are both 1, then the node would be processed once and only once, so we can just return that node. if (lower == 1 && upper == 1) { return node; } // If the lower and upper bound are both 0, this is actually empty. if (lower == 0 && upper == 0) { return Epsilon; } // If this is equivalent to any*, return that. if (!isLazy && lower == 0 && upper == int.MaxValue && node._kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(node._set is not null); if (_solver.AreEquivalent(_solver.True, node._set)) { return _anyStar; } } // Otherwise, create the loop. return SymbolicRegexNode<TElement>.CreateLoop(this, node, lower, upper, isLazy); } /// <summary>Creates a "singleton", which matches a single character.</summary> internal SymbolicRegexNode<TElement> CreateSingleton(TElement set) { // We maintain a cache of singletons, under the assumption that it's likely the same one/notone/set appears // multiple times in the same pattern. First consult the cache, and then create a new singleton if one didn't exist. ref SymbolicRegexNode<TElement>? result = ref CollectionsMarshal.GetValueRefOrAddDefault(_singletonCache, set, out _); return result ??= SymbolicRegexNode<TElement>.CreateSingleton(this, set); } /// <summary>Creates a fixed length marker for the end of a sequence.</summary> internal SymbolicRegexNode<TElement> CreateFixedLengthMarker(int length) => SymbolicRegexNode<TElement>.CreateFixedLengthMarker(this, length); /// <summary> /// Make a complemented node /// </summary> /// <param name="node">node to be complemented</param> /// <returns></returns> internal SymbolicRegexNode<TElement> Not(SymbolicRegexNode<TElement> node) => SymbolicRegexNode<TElement>.Not(this, node); internal SymbolicRegexNode<TElement> CreateCapture(SymbolicRegexNode<TElement> child, int captureNum) => CreateConcat(CreateCaptureStart(captureNum), CreateConcat(child, CreateCaptureEnd(captureNum))); internal SymbolicRegexNode<TElement> CreateCaptureStart(int captureNum) => SymbolicRegexNode<TElement>.CreateCaptureStart(this, captureNum); internal SymbolicRegexNode<TElement> CreateCaptureEnd(int captureNum) => SymbolicRegexNode<TElement>.CreateCaptureEnd(this, captureNum); internal SymbolicRegexNode<TElement> CreateDisableBacktrackingSimulation(SymbolicRegexNode<TElement> child) { if (child == _nothing) return _nothing; return SymbolicRegexNode<TElement>.CreateDisableBacktrackingSimulation(this, child); } internal SymbolicRegexNode<T> Transform<T>(SymbolicRegexNode<TElement> sr, SymbolicRegexBuilder<T> builder, Func<TElement, T> predicateTransformer) where T : notnull { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(Transform, sr, builder, predicateTransformer); } switch (sr._kind) { case SymbolicRegexNodeKind.BeginningAnchor: return builder.BeginningAnchor; case SymbolicRegexNodeKind.EndAnchor: return builder.EndAnchor; case SymbolicRegexNodeKind.EndAnchorZ: return builder.EndAnchorZ; case SymbolicRegexNodeKind.EndAnchorZReverse: return builder.EndAnchorZReverse; case SymbolicRegexNodeKind.BOLAnchor: return builder.BolAnchor; case SymbolicRegexNodeKind.EOLAnchor: return builder.EolAnchor; case SymbolicRegexNodeKind.BoundaryAnchor: return builder.BoundaryAnchor; case SymbolicRegexNodeKind.NonBoundaryAnchor: return builder.NonBoundaryAnchor; case SymbolicRegexNodeKind.FixedLengthMarker: return builder.CreateFixedLengthMarker(sr._lower); case SymbolicRegexNodeKind.Epsilon: return builder.Epsilon; case SymbolicRegexNodeKind.Singleton: Debug.Assert(sr._set is not null); return builder.CreateSingleton(predicateTransformer(sr._set)); case SymbolicRegexNodeKind.Loop: Debug.Assert(sr._left is not null); return builder.CreateLoop(Transform(sr._left, builder, predicateTransformer), sr.IsLazy, sr._lower, sr._upper); case SymbolicRegexNodeKind.Or: Debug.Assert(sr._alts is not null); return builder.Or(sr._alts.Transform(builder, predicateTransformer)); case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(sr._left is not null && sr._right is not null); return builder.OrderedOr(Transform(sr._left, builder, predicateTransformer), Transform(sr._right, builder, predicateTransformer)); case SymbolicRegexNodeKind.And: Debug.Assert(sr._alts is not null); return builder.And(sr._alts.Transform(builder, predicateTransformer)); case SymbolicRegexNodeKind.CaptureStart: return builder.CreateCaptureStart(sr._lower); case SymbolicRegexNodeKind.CaptureEnd: return builder.CreateCaptureEnd(sr._lower); case SymbolicRegexNodeKind.Concat: { List<SymbolicRegexNode<TElement>> sr_elems = sr.ToList(); SymbolicRegexNode<T>[] sr_elems_trasformed = new SymbolicRegexNode<T>[sr_elems.Count]; for (int i = 0; i < sr_elems.Count; i++) { sr_elems_trasformed[i] = Transform(sr_elems[i], builder, predicateTransformer); } return builder.CreateConcat(sr_elems_trasformed, false); } case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(sr._left is not null); return builder.CreateDisableBacktrackingSimulation(Transform(sr._left, builder, predicateTransformer)); default: Debug.Assert(sr._kind == SymbolicRegexNodeKind.Not); Debug.Assert(sr._left is not null); return builder.Not(Transform(sr._left, builder, predicateTransformer)); } } /// <summary> /// Create a state with given node and previous character context. /// </summary> /// <param name="node">the pattern that this state will represent</param> /// <param name="prevCharKind">the kind of the character that led to this state</param> /// <param name="disableCaching">if true, then state won't be cached</param> /// <param name="capturing">whether to use the separate space of states with capturing transitions or not</param> /// <returns></returns> public DfaMatchingState<TElement> CreateState(SymbolicRegexNode<TElement> node, uint prevCharKind, bool disableCaching = false, bool capturing = false) { //first prune the anchors in the node TElement WLpred = _wordLetterPredicateForAnchors; TElement startSet = node.GetStartSet(); //true if the startset of the node overlaps with some wordletter or the node can be nullable bool contWithWL = node.CanBeNullable || _solver.IsSatisfiable(_solver.And(WLpred, startSet)); //true if the startset of the node overlaps with some nonwordletter or the node can be nullable bool contWithNWL = node.CanBeNullable || _solver.IsSatisfiable(_solver.And(_solver.Not(WLpred), startSet)); SymbolicRegexNode<TElement> pruned_node = node.PruneAnchors(prevCharKind, contWithWL, contWithNWL); var s = new DfaMatchingState<TElement>(pruned_node, prevCharKind); if (!(capturing ? _capturingStateCache : _stateCache).TryGetValue(s, out DfaMatchingState<TElement>? state)) { // do not cache set of states as states in NFA mode if (disableCaching && pruned_node.Kind == SymbolicRegexNodeKind.Or) { s.Id = -1; // mark the Id as invalid state = s; } else { state = MakeNewState(s, capturing); } } return state; } private DfaMatchingState<TElement> MakeNewState(DfaMatchingState<TElement> state, bool capturing) { lock (this) { HashSet<DfaMatchingState<TElement>> cache = capturing ? _capturingStateCache : _stateCache; state.Id = cache.Count; cache.Add(state); Debug.Assert(_stateArray is not null && _capturingStateArray is not null); const int GrowthSize = 1024; if (capturing) { if (state.Id == _capturingStateArray.Length) { int newsize = _capturingStateArray.Length + GrowthSize; Array.Resize(ref _capturingStateArray, newsize); Array.Resize(ref _capturingDelta, newsize << _mintermsLog); } _capturingStateArray[state.Id] = state; } else { if (state.Id == _stateArray.Length) { int newsize = _stateArray.Length + GrowthSize; Array.Resize(ref _stateArray, newsize); Array.Resize(ref _delta, newsize << _mintermsLog); } _stateArray[state.Id] = state; } return state; } } /// <summary> /// Make an NFA state for the given node and previous character kind. /// </summary> public int CreateNfaState(SymbolicRegexNode<TElement> node, uint prevCharKind) { // TBD: OrderedOr Debug.Assert(node.Kind != SymbolicRegexNodeKind.Or); // First make the underlying core state DfaMatchingState<TElement> coreState = CreateState(node, prevCharKind); if (!_nfaStateArrayInverse.TryGetValue(coreState.Id, out int nfaStateId)) { nfaStateId = MakeNewNfaState(coreState.Id); } return nfaStateId; } /// <summary>Critical region that creates a new NFA state for the underlying core state</summary> private int MakeNewNfaState(int coreStateId) { lock (this) { if (NfaStateCount == _nfaStateArray.Length) { // TBD: is 1024 reasonable? int newsize = _nfaStateArray.Length + 1024; Array.Resize(ref _nfaStateArray, newsize); Array.Resize(ref _nfaDelta, newsize << _mintermsLog); // TBD: capturing } int nfaStateId = NfaStateCount; _nfaStateArray[nfaStateId] = coreStateId; _nfaStateArrayInverse[coreStateId] = nfaStateId; return nfaStateId; } } /// <summary>Gets the core state corresponding to the NFA state</summary> public DfaMatchingState<TElement> GetCoreState(int nfaStateId) { Debug.Assert(_stateArray is not null); Debug.Assert(nfaStateId < _nfaStateArray.Length); Debug.Assert(_nfaStateArray[nfaStateId] < _stateArray.Length); return _stateArray[_nfaStateArray[nfaStateId]]; } /// <summary>Critical region for defining a new core transition</summary> public DfaMatchingState<TElement> CreateNewTransition(DfaMatchingState<TElement> sourceState, int mintermId, int offset) { TryCreateNewTransition(sourceState, mintermId, offset, checkThreshold: false, out DfaMatchingState<TElement>? nextState); Debug.Assert(nextState is not null); return nextState; } /// <summary>Gets or creates a new DFA transition.</summary> public bool TryCreateNewTransition( DfaMatchingState<TElement> sourceState, int mintermId, int offset, bool checkThreshold, [NotNullWhen(true)] out DfaMatchingState<TElement>? nextState) { Debug.Assert(_delta is not null); lock (this) { Debug.Assert(offset < _delta.Length); // check if meanwhile delta[offset] has become defined possibly by another thread DfaMatchingState<TElement>? targetState = _delta[offset]; if (targetState is null) { if (checkThreshold && _stateCache.Count >= SymbolicRegexMatcher<TElement>.NfaThreshold) { nextState = null; return false; } targetState = sourceState.Next(GetMinterm(mintermId)); Volatile.Write(ref _delta[offset], targetState); } nextState = targetState; return true; } } /// <summary>Gets or creates a new NFA transition.</summary> public int[] CreateNewNfaTransition(int nfaStateId, int mintermId, int nfaOffset) { Debug.Assert(_delta is not null); lock (this) { Debug.Assert(nfaOffset < _nfaDelta.Length); // check if meanwhile the nfaoffset has become defined possibly by another thread int[]? targets = _nfaDelta[nfaOffset]; if (targets is null) { // Create the underlying transition from the core state corresponding to the nfa state DfaMatchingState<TElement> coreState = GetCoreState(nfaStateId); int coreOffset = (coreState.Id << _mintermsLog) | mintermId; DfaMatchingState<TElement>? coreTarget = _delta[coreOffset] ?? CreateNewTransition(coreState, mintermId, coreOffset); // TBD: OrderedOr if (coreTarget.Node.Kind == SymbolicRegexNodeKind.Or) { // Create separate NFA states for all members of a disjunction // Here duplicate NFA states cannot arise because there are no duplicate nodes in the disjunction SymbolicRegexSet<TElement>? alts = coreTarget.Node._alts; Debug.Assert(alts is not null); targets = new int[alts.Count]; int targetIndex = 0; foreach (SymbolicRegexNode<TElement> q in alts) { Debug.Assert(!q.IsNothing); targets[targetIndex++] = CreateNfaState(q, coreTarget.PrevCharKind); } Debug.Assert(targetIndex == targets.Length); } else if (coreTarget.IsDeadend) { // Omit deadend states from the target list of states // target list being empty means that the NFA state itself is a deadend targets = Array.Empty<int>(); } else { // Add the single NFA target state correponding to the core target state if (!_nfaStateArrayInverse.TryGetValue(coreTarget.Id, out int nfaTargetId)) { nfaTargetId = MakeNewNfaState(coreTarget.Id); } targets = new[] { nfaTargetId }; } Volatile.Write(ref _nfaDelta[nfaOffset], targets); } return targets; } } } }
1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexKind.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.RegularExpressions.Symbolic { /// <summary>Kinds of <see cref="SymbolicRegexNode{S}"/>.</summary> internal enum SymbolicRegexNodeKind { /// <summary>An empty node that matches a zero-width input (e.g. <see cref="RegexNodeKind.Empty"/>).</summary> Epsilon, /// <summary>A node that matches a single character (i.e. <see cref="RegexNodeKind.One"/>, <see cref="RegexNodeKind.Notone"/>, or <see cref="RegexNodeKind.Set"/>).</summary> Singleton, /// <summary>A node that matches a sequence of nodes (i.e. <see cref="RegexNodeKind.Concatenate"/>).</summary> Concat, /// <summary>A node that matches a loop (e.g. <see cref="RegexNodeKind.Loop"/>, <see cref="RegexNodeKind.Lazyloop"/>, <see cref="RegexNodeKind.Setloop"/>, etc.).</summary> Loop, /// <summary>A node that matches if any of its nodes match.</summary> /// <remarks>This is typically used to combine singletons.</remarks> Or, /// <summary>A node that matches if any of its nodes match and that matches them in a fixed order that mirrors how the backtracking engines operate (e.g. <see cref="RegexNodeKind.Alternate"/>).</summary> OrderedOr, /// <summary>A node that matches if all of its nodes match.</summary> /// <remarks>This is typically used to combine singletons.</remarks> And, /// <summary>A node that matches if its node doesn't (e.g. <see cref="RegexNodeKind.Notone"/>).</summary> Not, /// <summary>A node that represents a beginning anchor (i.e. <see cref="RegexNodeKind.Beginning"/>).</summary> BeginningAnchor, /// <summary>A node that represents an ending anchor (i.e. <see cref="RegexNodeKind.End"/>).</summary> EndAnchor, /// <summary>A node that represents an ending \Z anchor (i.e. <see cref="RegexNodeKind.EndZ"/>).</summary> EndAnchorZ, /// <summary>A node that represents an anchor for the very first line or start-line after the very first \n arises as the reverse of <see cref="EndAnchorZ"/>.</summary> EndAnchorZReverse, /// <summary>A node that represents a beginning-of-line anchor (i.e. <see cref="RegexNodeKind.Bol"/>).</summary> BOLAnchor, /// <summary>A node that represents a end-of-line anchor (i.e. <see cref="RegexNodeKind.Eol"/>).</summary> EOLAnchor, /// <summary>A node that represents a word boundary anchor (i.e. <see cref="RegexNodeKind.Boundary"/>).</summary> BoundaryAnchor, /// <summary>A node that represents a word non-boundary anchor (i.e. <see cref="RegexNodeKind.NonBoundary"/>).</summary> NonBoundaryAnchor, /// <summary>Marker node that carries with it an indication of how long the fixed-length sequence is until that point.</summary> /// <remarks> /// <see cref="SymbolicRegexNode{S}._lower"/> stores the fixed length. This node is used to avoid the second phase /// of matching (for non-IsMatch operations, which only have the first phase). The first phase determines whether /// there is a match and its possible ending position, at which point the second phase matches in reverse to find /// the starting position, and then a third phase again matches forward from the now known starting position to /// find the guaranteed ending position of the match. If we have a <see cref="FixedLengthMarker"/>, we can use it /// to avoid the second phase of matching by simply jumping backwards the fixed length to the starting position. /// </remarks> FixedLengthMarker, /// <summary>Indicates the start of a subcapture.</summary> /// <remarks><see cref="SymbolicRegexNode{S}._lower"/> stores the associated capture number.</remarks> CaptureStart, /// <summary>Indicates the end of a subcapture.</summary> /// <remarks><see cref="SymbolicRegexNode{S}._lower"/> stores the associated capture number.</remarks> CaptureEnd, } }
// 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.RegularExpressions.Symbolic { /// <summary>Kinds of <see cref="SymbolicRegexNode{S}"/>.</summary> internal enum SymbolicRegexNodeKind { /// <summary>An empty node that matches a zero-width input (e.g. <see cref="RegexNodeKind.Empty"/>).</summary> Epsilon, /// <summary>A node that matches a single character (i.e. <see cref="RegexNodeKind.One"/>, <see cref="RegexNodeKind.Notone"/>, or <see cref="RegexNodeKind.Set"/>).</summary> Singleton, /// <summary>A node that matches a sequence of nodes (i.e. <see cref="RegexNodeKind.Concatenate"/>).</summary> Concat, /// <summary>A node that matches a loop (e.g. <see cref="RegexNodeKind.Loop"/>, <see cref="RegexNodeKind.Lazyloop"/>, <see cref="RegexNodeKind.Setloop"/>, etc.).</summary> Loop, /// <summary>A node that matches if any of its nodes match.</summary> /// <remarks>This is typically used to combine singletons.</remarks> Or, /// <summary>A node that matches if any of its nodes match and that matches them in a fixed order that mirrors how the backtracking engines operate (e.g. <see cref="RegexNodeKind.Alternate"/>).</summary> OrderedOr, /// <summary>A node that matches if all of its nodes match.</summary> /// <remarks>This is typically used to combine singletons.</remarks> And, /// <summary>A node that matches if its node doesn't (e.g. <see cref="RegexNodeKind.Notone"/>).</summary> Not, /// <summary>A node that represents a beginning anchor (i.e. <see cref="RegexNodeKind.Beginning"/>).</summary> BeginningAnchor, /// <summary>A node that represents an ending anchor (i.e. <see cref="RegexNodeKind.End"/>).</summary> EndAnchor, /// <summary>A node that represents an ending \Z anchor (i.e. <see cref="RegexNodeKind.EndZ"/>).</summary> EndAnchorZ, /// <summary>A node that represents an anchor for the very first line or start-line after the very first \n arises as the reverse of <see cref="EndAnchorZ"/>.</summary> EndAnchorZReverse, /// <summary>A node that represents a beginning-of-line anchor (i.e. <see cref="RegexNodeKind.Bol"/>).</summary> BOLAnchor, /// <summary>A node that represents a end-of-line anchor (i.e. <see cref="RegexNodeKind.Eol"/>).</summary> EOLAnchor, /// <summary>A node that represents a word boundary anchor (i.e. <see cref="RegexNodeKind.Boundary"/>).</summary> BoundaryAnchor, /// <summary>A node that represents a word non-boundary anchor (i.e. <see cref="RegexNodeKind.NonBoundary"/>).</summary> NonBoundaryAnchor, /// <summary>Marker node that carries with it an indication of how long the fixed-length sequence is until that point.</summary> /// <remarks> /// <see cref="SymbolicRegexNode{S}._lower"/> stores the fixed length. This node is used to avoid the second phase /// of matching (for non-IsMatch operations, which only have the first phase). The first phase determines whether /// there is a match and its possible ending position, at which point the second phase matches in reverse to find /// the starting position, and then a third phase again matches forward from the now known starting position to /// find the guaranteed ending position of the match. If we have a <see cref="FixedLengthMarker"/>, we can use it /// to avoid the second phase of matching by simply jumping backwards the fixed length to the starting position. /// </remarks> FixedLengthMarker, /// <summary>Indicates the start of a subcapture.</summary> /// <remarks><see cref="SymbolicRegexNode{S}._lower"/> stores the associated capture number.</remarks> CaptureStart, /// <summary>Indicates the end of a subcapture.</summary> /// <remarks><see cref="SymbolicRegexNode{S}._lower"/> stores the associated capture number.</remarks> CaptureEnd, /// <summary> /// This node disables backtracking simulation in derivatives for the pattern it contains. This is used for the the /// second reverse phase of the match generation algorithm, where its needed to ensure all paths are considered when /// walking backwards from a known final state. /// </summary> /// <remarks> /// If any other metadata nodes are needed that would have the same structure, having just one node kind for this and /// the other uses might make sense. /// </remarks> DisableBacktrackingSimulation, } }
1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./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)) { // 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. _dotStarredPattern = _builder.CreateConcat(_builder._anyStar, _pattern); 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. Also disable backtracking simulation to ensure the reverse path from // the final state that was found is followed. Not doing so might cause the earliest // starting point to not be found. _reversePattern = _builder.CreateDisableBacktrackingSimulation(_pattern.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>, 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>, DerivativeEffect[])>? p = _builder._capturingDelta[offset]; if (p is null) { // Build the new state and store it into the array. p = state.NfaNextWithEffects(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>, 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, 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, args) => args.Registers.ApplyEffect(effect, args.Pos), CharKind.Context(endState.PrevCharKind, GetCharKind(input, i_end + 1)), (Registers: endRegisters, Pos: 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(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,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexNode.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.Runtime.CompilerServices; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents an AST node of a symbolic regex.</summary> internal sealed class SymbolicRegexNode<S> where S : notnull { internal const string EmptyCharClass = "[]"; /// <summary>Some byte other than 0 to represent true</summary> internal const byte TrueByte = 1; /// <summary>Some byte other than 0 to represent false</summary> internal const byte FalseByte = 2; /// <summary>The undefined value is the default value 0</summary> internal const byte UndefinedByte = 0; internal readonly SymbolicRegexBuilder<S> _builder; internal readonly SymbolicRegexNodeKind _kind; internal readonly int _lower; internal readonly int _upper; internal readonly S? _set; internal readonly SymbolicRegexNode<S>? _left; internal readonly SymbolicRegexNode<S>? _right; internal readonly SymbolicRegexSet<S>? _alts; /// <summary> /// Caches nullability of this node for any given context (0 &lt;= context &lt; ContextLimit) /// when _info.StartsWithSomeAnchor and _info.CanBeNullable are true. Otherwise the cache is null. /// </summary> private byte[]? _nullabilityCache; private S _startSet; /// <summary>AST node of a symbolic regex</summary> /// <param name="builder">the builder</param> /// <param name="kind">what kind of node</param> /// <param name="left">left child</param> /// <param name="right">right child</param> /// <param name="lower">lower bound of a loop</param> /// <param name="upper">upper boubd of a loop</param> /// <param name="set">singelton set</param> /// <param name="alts">alternatives set of a disjunction or conjunction</param> /// <param name="info">misc flags including laziness</param> private SymbolicRegexNode(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind, SymbolicRegexNode<S>? left, SymbolicRegexNode<S>? right, int lower, int upper, S? set, SymbolicRegexSet<S>? alts, SymbolicRegexInfo info) { _builder = builder; _kind = kind; _left = left; _right = right; _lower = lower; _upper = upper; _set = set; _alts = alts; _info = info; _hashcode = ComputeHashCode(); _startSet = ComputeStartSet(); _nullabilityCache = info.StartsWithSomeAnchor && info.CanBeNullable ? new byte[CharKind.ContextLimit] : null; } private bool _isInternalizedUnion; /// <summary> Create a new node or retrieve one from the builder _nodeCache</summary> private static SymbolicRegexNode<S> Create(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind, SymbolicRegexNode<S>? left, SymbolicRegexNode<S>? right, int lower, int upper, S? set, SymbolicRegexSet<S>? alts, SymbolicRegexInfo info) { SymbolicRegexNode<S>? node; var key = (kind, left, right, lower, upper, set, alts, info); if (!builder._nodeCache.TryGetValue(key, out node)) { // Do not internalize top level Or-nodes or else NFA mode will become ineffective if (kind == SymbolicRegexNodeKind.Or) { node = new(builder, kind, left, right, lower, upper, set, alts, info); return node; } left = left == null || left._kind != SymbolicRegexNodeKind.Or || left._isInternalizedUnion ? left : Internalize(left); right = right == null || right._kind != SymbolicRegexNodeKind.Or || right._isInternalizedUnion ? right : Internalize(right); node = new(builder, kind, left, right, lower, upper, set, alts, info); builder._nodeCache[key] = node; } Debug.Assert(node is not null); return node; } /// <summary> Internalize an Or-node that is not yet internalized</summary> private static SymbolicRegexNode<S> Internalize(SymbolicRegexNode<S> node) { Debug.Assert(node._kind == SymbolicRegexNodeKind.Or && !node._isInternalizedUnion); (SymbolicRegexNodeKind, SymbolicRegexNode<S>?, SymbolicRegexNode<S>?, int, int, S?, SymbolicRegexSet<S>?, SymbolicRegexInfo) node_key = (SymbolicRegexNodeKind.Or, null, null, -1, -1, default(S), node._alts, node._info); SymbolicRegexNode<S>? node1; if (node._builder._nodeCache.TryGetValue(node_key, out node1)) { Debug.Assert(node1 is not null && node1._isInternalizedUnion); return node1; } else { node._isInternalizedUnion = true; node._builder._nodeCache[node_key] = node; return node; } } /// <summary>True if this node only involves lazy loops</summary> internal bool IsLazy => _info.IsLazy; /// <summary>True if this node accepts the empty string unconditionally.</summary> internal bool IsNullable => _info.IsNullable; /// <summary>True if this node can potentially accept the empty string depending on anchors and immediate context.</summary> internal bool CanBeNullable { get { Debug.Assert(_info.CanBeNullable || !_info.IsNullable); return _info.CanBeNullable; } } internal SymbolicRegexInfo _info; private readonly int _hashcode; /// <summary>Converts a Concat or OrderdOr into an array, returns anything else in a singleton array.</summary> /// <param name="list">a list to insert the elements into, or null to return results in a new list</param> /// <param name="listKind">kind of node to consider as the list builder</param> public List<SymbolicRegexNode<S>> ToList(List<SymbolicRegexNode<S>>? list = null, SymbolicRegexNodeKind listKind = SymbolicRegexNodeKind.Concat) { Debug.Assert(listKind == SymbolicRegexNodeKind.Concat || listKind == SymbolicRegexNodeKind.OrderedOr); list ??= new List<SymbolicRegexNode<S>>(); AppendToList(this, list, listKind); return list; static void AppendToList(SymbolicRegexNode<S> concat, List<SymbolicRegexNode<S>> list, SymbolicRegexNodeKind listKind) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(AppendToList, concat, list, listKind); return; } SymbolicRegexNode<S> node = concat; while (node._kind == listKind) { Debug.Assert(node._left is not null && node._right is not null); if (node._left._kind == listKind) { AppendToList(node._left, list, listKind); } else { list.Add(node._left); } node = node._right; } list.Add(node); } } /// <summary> /// Relative nullability that takes into account the immediate character context /// in order to resolve nullability of anchors /// </summary> /// <param name="context">kind info for previous and next characters</param> internal bool IsNullableFor(uint context) { // if _nullabilityCache is null then IsNullable==CanBeNullable // Observe that if IsNullable==true then CanBeNullable==true. // but when the node does not start with an anchor // and IsNullable==false then CanBeNullable==false. return _nullabilityCache is null ? _info.IsNullable : WithCache(context); // Separated out to enable the common case (no nullability cache) to be inlined // and to avoid zero-init costs for generally unused state. bool WithCache(uint context) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(IsNullableFor, context); } Debug.Assert(context < CharKind.ContextLimit); // If nullablity has been computed for the given context then return it byte b = Volatile.Read(ref _nullabilityCache[context]); if (b != UndefinedByte) { return b == TrueByte; } // Otherwise compute the nullability recursively for the given context bool is_nullable; switch (_kind) { case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); is_nullable = _lower == 0 || _left.IsNullableFor(context); break; case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); is_nullable = _left.IsNullableFor(context) && _right.IsNullableFor(context); break; case SymbolicRegexNodeKind.Or: case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); is_nullable = _alts.IsNullableFor(context); break; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); is_nullable = _left.IsNullableFor(context) || _right.IsNullableFor(context); break; case SymbolicRegexNodeKind.Not: Debug.Assert(_left is not null); is_nullable = !_left.IsNullableFor(context); break; case SymbolicRegexNodeKind.BeginningAnchor: is_nullable = CharKind.Prev(context) == CharKind.BeginningEnd; break; case SymbolicRegexNodeKind.EndAnchor: is_nullable = CharKind.Next(context) == CharKind.BeginningEnd; break; case SymbolicRegexNodeKind.BOLAnchor: // Beg-Of-Line anchor is nullable when the previous character is Newline or Start // note: at least one of the bits must be 1, but both could also be 1 in case of very first newline is_nullable = (CharKind.Prev(context) & CharKind.NewLineS) != 0; break; case SymbolicRegexNodeKind.EOLAnchor: // End-Of-Line anchor is nullable when the next character is Newline or Stop // note: at least one of the bits must be 1, but both could also be 1 in case of \Z is_nullable = (CharKind.Next(context) & CharKind.NewLineS) != 0; break; case SymbolicRegexNodeKind.BoundaryAnchor: // test that prev char is word letter iff next is not not word letter is_nullable = ((CharKind.Prev(context) & CharKind.WordLetter) ^ (CharKind.Next(context) & CharKind.WordLetter)) != 0; break; case SymbolicRegexNodeKind.NonBoundaryAnchor: // test that prev char is word letter iff next is word letter is_nullable = ((CharKind.Prev(context) & CharKind.WordLetter) ^ (CharKind.Next(context) & CharKind.WordLetter)) == 0; break; case SymbolicRegexNodeKind.EndAnchorZ: // \Z anchor is nullable when the next character is either the last Newline or Stop // note: CharKind.NewLineS == CharKind.Newline|CharKind.StartStop is_nullable = (CharKind.Next(context) & CharKind.BeginningEnd) != 0; break; case SymbolicRegexNodeKind.CaptureStart: case SymbolicRegexNodeKind.CaptureEnd: is_nullable = true; break; default: // SymbolicRegexKind.EndAnchorZReverse: // EndAnchorZRev (rev(\Z)) anchor is nullable when the prev character is either the first Newline or Start // note: CharKind.NewLineS == CharKind.Newline|CharKind.StartStop Debug.Assert(_kind == SymbolicRegexNodeKind.EndAnchorZReverse); is_nullable = (CharKind.Prev(context) & CharKind.BeginningEnd) != 0; break; } Volatile.Write(ref _nullabilityCache[context], is_nullable ? TrueByte : FalseByte); return is_nullable; } } /// <summary>Returns true if this is equivalent to .* (the node must be eager also)</summary> public bool IsAnyStar { get { if (IsStar) { Debug.Assert(_left is not null); if (_left._kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(_left._set is not null); return !IsLazy && _builder._solver.True.Equals(_left._set); } } return false; } } /// <summary>Returns true if this is equivalent to .+ (the node must be eager also)</summary> public bool IsAnyPlus { get { if (IsPlus) { Debug.Assert(_left is not null); if (_left._kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(_left._set is not null); return !IsLazy && _builder._solver.True.Equals(_left._set); } } return false; } } /// <summary>Returns true if this is equivalent to [\0-\xFFFF] </summary> public bool IsAnyChar { get { if (_kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(_set is not null); return _builder._solver.AreEquivalent(_builder._solver.True, _set); } return false; } } /// <summary>Returns true if this is equivalent to [0-[0]]</summary> public bool IsNothing { get { if (_kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(_set is not null); return !_builder._solver.IsSatisfiable(_set); } return false; } } /// <summary>Returns true iff this is a loop whose lower bound is 0 and upper bound is max</summary> public bool IsStar => _lower == 0 && _upper == int.MaxValue; /// <summary>Returns true if this is Epsilon</summary> public bool IsEpsilon => _kind == SymbolicRegexNodeKind.Epsilon; /// <summary>Gets the kind of the regex</summary> internal SymbolicRegexNodeKind Kind => _kind; /// <summary> /// Returns true iff this is a loop whose lower bound is 1 and upper bound is max /// </summary> public bool IsPlus => _lower == 1 && _upper == int.MaxValue; #region called only once, in the constructor of SymbolicRegexBuilder internal static SymbolicRegexNode<S> CreateFalse(SymbolicRegexBuilder<S> builder) => Create(builder, SymbolicRegexNodeKind.Singleton, null, null, -1, -1, builder._solver.False, null, SymbolicRegexInfo.Create()); internal static SymbolicRegexNode<S> CreateTrue(SymbolicRegexBuilder<S> builder) => Create(builder, SymbolicRegexNodeKind.Singleton, null, null, -1, -1, builder._solver.True, null, SymbolicRegexInfo.Create(containsSomeCharacter: true)); internal static SymbolicRegexNode<S> CreateFixedLengthMarker(SymbolicRegexBuilder<S> builder, int length) => Create(builder, SymbolicRegexNodeKind.FixedLengthMarker, null, null, length, -1, default, null, SymbolicRegexInfo.Create(isAlwaysNullable: true)); internal static SymbolicRegexNode<S> CreateEpsilon(SymbolicRegexBuilder<S> builder) => Create(builder, SymbolicRegexNodeKind.Epsilon, null, null, -1, -1, default, null, SymbolicRegexInfo.Create(isAlwaysNullable: true)); internal static SymbolicRegexNode<S> CreateEagerEmptyLoop(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> body) => Create(builder, SymbolicRegexNodeKind.Loop, body, null, 0, 0, default, null, SymbolicRegexInfo.Create(isAlwaysNullable: true, isLazy: false)); internal static SymbolicRegexNode<S> CreateBeginEndAnchor(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind) { Debug.Assert(kind is SymbolicRegexNodeKind.BeginningAnchor or SymbolicRegexNodeKind.EndAnchor or SymbolicRegexNodeKind.EndAnchorZ or SymbolicRegexNodeKind.EndAnchorZReverse or SymbolicRegexNodeKind.EOLAnchor or SymbolicRegexNodeKind.BOLAnchor); return Create(builder, kind, null, null, -1, -1, default, null, SymbolicRegexInfo.Create(startsWithLineAnchor: true, canBeNullable: true)); } internal static SymbolicRegexNode<S> CreateBoundaryAnchor(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind) { Debug.Assert(kind is SymbolicRegexNodeKind.BoundaryAnchor or SymbolicRegexNodeKind.NonBoundaryAnchor); return Create(builder, kind, null, null, -1, -1, default, null, SymbolicRegexInfo.Create(startsWithBoundaryAnchor: true, canBeNullable: true)); } #endregion internal static SymbolicRegexNode<S> CreateSingleton(SymbolicRegexBuilder<S> builder, S set) => Create(builder, SymbolicRegexNodeKind.Singleton, null, null, -1, -1, set, null, SymbolicRegexInfo.Create(containsSomeCharacter: !set.Equals(builder._solver.False))); internal static SymbolicRegexNode<S> CreateLoop(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> body, int lower, int upper, bool isLazy) { Debug.Assert(lower >= 0 && lower <= upper); return Create(builder, SymbolicRegexNodeKind.Loop, body, null, lower, upper, default, null, SymbolicRegexInfo.Loop(body._info, lower, isLazy)); } internal static SymbolicRegexNode<S> Or(SymbolicRegexBuilder<S> builder, params SymbolicRegexNode<S>[] disjuncts) => CreateCollection(builder, SymbolicRegexNodeKind.Or, SymbolicRegexSet<S>.CreateMulti(builder, disjuncts, SymbolicRegexNodeKind.Or), SymbolicRegexInfo.Or(GetInfos(disjuncts))); internal static SymbolicRegexNode<S> Or(SymbolicRegexBuilder<S> builder, SymbolicRegexSet<S> disjuncts) { Debug.Assert(disjuncts._kind == SymbolicRegexNodeKind.Or || disjuncts.IsEverything); return CreateCollection(builder, SymbolicRegexNodeKind.Or, disjuncts, SymbolicRegexInfo.Or(GetInfos(disjuncts))); } internal static SymbolicRegexNode<S> And(SymbolicRegexBuilder<S> builder, params SymbolicRegexNode<S>[] conjuncts) => CreateCollection(builder, SymbolicRegexNodeKind.And, SymbolicRegexSet<S>.CreateMulti(builder, conjuncts, SymbolicRegexNodeKind.And), SymbolicRegexInfo.And(GetInfos(conjuncts))); internal static SymbolicRegexNode<S> And(SymbolicRegexBuilder<S> builder, SymbolicRegexSet<S> conjuncts) { Debug.Assert(conjuncts.IsNothing || conjuncts._kind == SymbolicRegexNodeKind.And); return CreateCollection(builder, SymbolicRegexNodeKind.And, conjuncts, SymbolicRegexInfo.And(GetInfos(conjuncts))); } internal static SymbolicRegexNode<S> CreateCaptureStart(SymbolicRegexBuilder<S> builder, int captureNum) => Create(builder, SymbolicRegexNodeKind.CaptureStart, null, null, captureNum, -1, default, null, SymbolicRegexInfo.Create(isAlwaysNullable: true)); internal static SymbolicRegexNode<S> CreateCaptureEnd(SymbolicRegexBuilder<S> builder, int captureNum) => Create(builder, SymbolicRegexNodeKind.CaptureEnd, null, null, captureNum, -1, default, null, SymbolicRegexInfo.Create(isAlwaysNullable: true)); private static SymbolicRegexNode<S> CreateCollection(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind, SymbolicRegexSet<S> alts, SymbolicRegexInfo info) => alts.IsNothing ? builder._nothing : alts.IsEverything ? builder._anyStar : alts.IsSingleton ? alts.GetSingletonElement() : Create(builder, kind, null, null, -1, -1, default, alts, info); private static SymbolicRegexInfo[] GetInfos(SymbolicRegexNode<S>[] nodes) { var infos = new SymbolicRegexInfo[nodes.Length]; for (int i = 0; i < nodes.Length; i++) { infos[i] = nodes[i]._info; } return infos; } private static SymbolicRegexInfo[] GetInfos(SymbolicRegexSet<S> nodes) { var infos = new SymbolicRegexInfo[nodes.Count]; int i = 0; foreach (SymbolicRegexNode<S> node in nodes) { Debug.Assert(i < nodes.Count); infos[i++] = node._info; } Debug.Assert(i == nodes.Count); return infos; } /// <summary>Make a concatenation of the supplied regex nodes.</summary> internal static SymbolicRegexNode<S> CreateConcat(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> left, SymbolicRegexNode<S> right) { // Concatenating anything with a nothing means the entire concatenation can't match if (left == builder._nothing || right == builder._nothing) return builder._nothing; // If the left or right is empty, just return the other. if (left.IsEpsilon) return right; if (right.IsEpsilon) return left; // If the left isn't a concatenation, then proceed to concatenation the left with the right. if (left._kind != SymbolicRegexNodeKind.Concat) { return Create(builder, SymbolicRegexNodeKind.Concat, left, right, -1, -1, default, null, SymbolicRegexInfo.Concat(left._info, right._info)); } // The left is a concatenation. We want to flatten it out and maintain a right-associative form. SymbolicRegexNode<S> concat = right; List<SymbolicRegexNode<S>> leftNodes = left.ToList(); for (int i = leftNodes.Count - 1; i >= 0; i--) { concat = Create(builder, SymbolicRegexNodeKind.Concat, leftNodes[i], concat, -1, -1, default, null, SymbolicRegexInfo.Concat(leftNodes[i]._info, concat._info)); } return concat; } /// <summary> /// Make an ordered or of given regexes, eliminate nothing regexes and treat .* as consuming element. /// Keep the or flat, assuming both right and left are flat. /// Apply a counber subsumption/combining optimization, such that e.g. a{2,5}|a{3,10} will be combined to a{2,10}. /// </summary> internal static SymbolicRegexNode<S> OrderedOr(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> left, SymbolicRegexNode<S> right) { if (left.IsAnyStar || right == builder._nothing || left == right) return left; if (left == builder._nothing) return right; if (left._kind != SymbolicRegexNodeKind.OrderedOr) { // Apply the counter subsumption/combining optimization if possible (SymbolicRegexNode<S> loop, SymbolicRegexNode<S> rest) = left.FirstCounterInfo(); if (loop != builder._nothing) { Debug.Assert(loop._kind == SymbolicRegexNodeKind.Loop && loop._left is not null); (SymbolicRegexNode<S> otherLoop, SymbolicRegexNode<S> otherRest) = right.FirstCounterInfo(); if (otherLoop != builder._nothing && rest == otherRest) { // Found two adjacent counters with the same continuation, check that the loops are equivalent apart from bounds // and that the bounds form a contiguous interval. Two integer intervals [x1,x2] and [y1,y2] overlap when // x1 <= y2 and y1 <= x2. The union of intervals that just touch is still contiguous, e.g. [2,5] and [6,10] make // [2,10], so the lower bounds are decremented by 1 in the check. Debug.Assert(otherLoop._kind == SymbolicRegexNodeKind.Loop && otherLoop._left is not null); if (loop._left == otherLoop._left && loop.IsLazy == otherLoop.IsLazy && loop._lower - 1 <= otherLoop._upper && otherLoop._lower - 1 <= loop._upper) { // Loops are equivalent apart from bounds, and the union of the bounds is a contiguous interval // Build a new counter for the union of the ranges SymbolicRegexNode<S> newCounter = CreateConcat(builder, CreateLoop(builder, loop._left, Math.Min(loop._lower, otherLoop._lower), Math.Max(loop._upper, otherLoop._upper), loop.IsLazy), rest); if (right._kind == SymbolicRegexNodeKind.OrderedOr) { // The right counter came from an or, so include the rest of that or Debug.Assert(right._right is not null); return OrderedOr(builder, newCounter, right._right); } else { return newCounter; } } } } // No need for flattening and counter optimization did not apply, just build the or return Create(builder, SymbolicRegexNodeKind.OrderedOr, left, right, -1, -1, default, null, SymbolicRegexInfo.Or(left._info, right._info)); } // If the left side was an or, then it has to be flattened, gather the elements from both sides List<SymbolicRegexNode<S>> elems = left.ToList(listKind: SymbolicRegexNodeKind.OrderedOr); int firstRightElem = elems.Count; right.ToList(elems, listKind: SymbolicRegexNodeKind.OrderedOr); // Eliminate any duplicate elements, keeping the leftmost element HashSet<SymbolicRegexNode<S>> seenElems = new(); // Keep track of if any elements from the right side need to be eliminated bool rightChanged = false; for (int i = 0; i < elems.Count; i++) { if (!seenElems.Contains(elems[i])) { seenElems.Add(elems[i]); } else { // Nothing will be eliminated in the next step elems[i] = builder._nothing; rightChanged |= i >= firstRightElem; } } // Build the flattened or, avoiding rebuilding the right side if possible if (rightChanged) { SymbolicRegexNode<S> or = builder._nothing; for (int i = elems.Count - 1; i >= 0; i--) { or = OrderedOr(builder, elems[i], or); } return or; } else { SymbolicRegexNode<S> or = right; for (int i = firstRightElem - 1; i >= 0; i--) { or = OrderedOr(builder, elems[i], or); } return or; } } /// <summary> /// Extract a counter as a loop followed by its continuation. For example, a*b returns (a*,b). /// Also look into the first element of an or, so a+|xyz returns (a+,()). /// If no counter is found returns ([],[]). /// </summary> /// <returns>a tuple of the loop and its continuation</returns> private (SymbolicRegexNode<S>, SymbolicRegexNode<S>) FirstCounterInfo() { if (_kind == SymbolicRegexNodeKind.Loop) return (this, _builder.Epsilon); if (_kind == SymbolicRegexNodeKind.Concat) { Debug.Assert(_left is not null && _right is not null); if (_left.Kind == SymbolicRegexNodeKind.Loop) return (_left, _right); } if (_kind == SymbolicRegexNodeKind.OrderedOr) { Debug.Assert(_left is not null); return _left.FirstCounterInfo(); } return (_builder._nothing, _builder._nothing); } internal static SymbolicRegexNode<S> Not(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> root) { // Instead of just creating a negated root node // Convert ~root to Negation Normal Form (NNF) by using deMorgan's laws and push ~ to the leaves // This may avoid rather large overhead (such case was discovered with unit test PasswordSearchDual) // Do this transformation in-line without recursion, to avoid any chance of deep recursion // OBSERVE: NNF[node] represents the Negation Normal Form of ~node Dictionary<SymbolicRegexNode<S>, SymbolicRegexNode<S>> NNF = new(); Stack<(SymbolicRegexNode<S>, bool)> todo = new(); todo.Push((root, false)); while (todo.Count > 0) { (SymbolicRegexNode<S>, bool) top = todo.Pop(); bool secondTimePushed = top.Item2; SymbolicRegexNode<S> node = top.Item1; if (secondTimePushed) { Debug.Assert((node._kind == SymbolicRegexNodeKind.Or || node._kind == SymbolicRegexNodeKind.And) && node._alts is not null); // Here all members of _alts have been processed List<SymbolicRegexNode<S>> alts_nnf = new(); foreach (SymbolicRegexNode<S> elem in node._alts) { alts_nnf.Add(NNF[elem]); } // Using deMorgan's laws, flip the kind: Or becomes And, And becomes Or SymbolicRegexNode<S> node_nnf = node._kind == SymbolicRegexNodeKind.Or ? And(builder, alts_nnf.ToArray()) : Or(builder, alts_nnf.ToArray()); NNF[node] = node_nnf; } else { switch (node._kind) { case SymbolicRegexNodeKind.Not: Debug.Assert(node._left is not null); // Here we assume that top._left is already in NNF, double negation is cancelled out NNF[node] = node._left; break; case SymbolicRegexNodeKind.Or or SymbolicRegexNodeKind.And: Debug.Assert(node._alts is not null); // Push the node for the second time todo.Push((node, true)); // Compute the negation normal form of all the members // Their computation is actually the same independent from being inside an 'Or' or 'And' node foreach (SymbolicRegexNode<S> elem in node._alts) { todo.Push((elem, false)); } break; case SymbolicRegexNodeKind.Epsilon: // ~() = .+ NNF[node] = SymbolicRegexNode<S>.CreateLoop(builder, builder._anyChar, 1, int.MaxValue, isLazy: false); break; case SymbolicRegexNodeKind.Singleton: Debug.Assert(node._set is not null); // ~[] = .* if (node.IsNothing) { NNF[node] = builder._anyStar; break; } goto default; case SymbolicRegexNodeKind.Loop: Debug.Assert(node._left is not null); // ~(.*) = [] and ~(.+) = () if (node.IsAnyStar) { NNF[node] = builder._nothing; break; } else if (node.IsPlus && node._left.IsAnyChar) { NNF[node] = builder.Epsilon; break; } goto default; default: // In all other cases construct the complement NNF[node] = Create(builder, SymbolicRegexNodeKind.Not, node, null, -1, -1, default, null, SymbolicRegexInfo.Not(node._info)); break; } } } return NNF[root]; } /// <summary> /// Returns the fixed matching length of the regex or -1 if the regex does not have a fixed matching length. /// </summary> public int GetFixedLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume no fixed length. return -1; } switch (_kind) { case SymbolicRegexNodeKind.FixedLengthMarker: case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.BOLAnchor: case SymbolicRegexNodeKind.EOLAnchor: case SymbolicRegexNodeKind.EndAnchor: case SymbolicRegexNodeKind.BeginningAnchor: case SymbolicRegexNodeKind.EndAnchorZ: case SymbolicRegexNodeKind.EndAnchorZReverse: case SymbolicRegexNodeKind.BoundaryAnchor: case SymbolicRegexNodeKind.NonBoundaryAnchor: case SymbolicRegexNodeKind.CaptureStart: case SymbolicRegexNodeKind.CaptureEnd: return 0; case SymbolicRegexNodeKind.Singleton: return 1; case SymbolicRegexNodeKind.Loop: { Debug.Assert(_left is not null); if (_lower == _upper) { long length = _left.GetFixedLength(); if (length >= 0) { length *= _lower; if (length <= int.MaxValue) { return (int)length; } } } break; } case SymbolicRegexNodeKind.Concat: { Debug.Assert(_left is not null && _right is not null); int leftLength = _left.GetFixedLength(); if (leftLength >= 0) { int rightLength = _right.GetFixedLength(); if (rightLength >= 0) { long length = (long)leftLength + rightLength; if (length <= int.MaxValue) { return (int)length; } } } break; } case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); return _alts.GetFixedLength(); case SymbolicRegexNodeKind.OrderedOr: { Debug.Assert(_left is not null && _right is not null); int length = _left.GetFixedLength(); if (length >= 0) { if (_right.GetFixedLength() == length) { return length; } } break; } } return -1; } private Dictionary<(S, uint), SymbolicRegexNode<S>>? _MkDerivative_Cache; /// <summary> /// Takes the derivative of the symbolic regex wrt elem. /// Assumes that elem is either a minterm wrt the predicates of the whole regex or a singleton set. /// </summary> /// <param name="elem">given element wrt which the derivative is taken</param> /// <param name="context">immediately surrounding character context that affects nullability of anchors</param> /// <returns></returns> internal SymbolicRegexNode<S> CreateDerivative(S elem, uint context) { // Guard against stack overflow due to deep recursion if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(CreateDerivative, elem, context); } if (this == _builder._anyStar || this == _builder._nothing) { return this; } if (Kind == SymbolicRegexNodeKind.Or && !_isInternalizedUnion) { // Internalize the node before proceeding // this node could end up being internalized or replaced by // an already previously created object (!= this) SymbolicRegexNode<S> this_internalized = Internalize(this); Debug.Assert(this_internalized._isInternalizedUnion); if (this_internalized != this) { return this_internalized.CreateDerivative(elem, context); } } _MkDerivative_Cache ??= new(); (S, uint) key = (elem, context); SymbolicRegexNode<S>? deriv; if (_MkDerivative_Cache.TryGetValue(key, out deriv)) { Debug.Assert(deriv != null); return deriv; } switch (_kind) { case SymbolicRegexNodeKind.Singleton: Debug.Assert(_set is not null); deriv = _builder._solver.IsSatisfiable(_builder._solver.And(elem, _set)) ? _builder.Epsilon : _builder._nothing; break; case SymbolicRegexNodeKind.Loop: { #region d(a, R*) = d(a,R)R* Debug.Assert(_left is not null); SymbolicRegexNode<S> step = _left.CreateDerivative(elem, context); if (step == _builder._nothing || _upper == 0) { deriv = _builder._nothing; break; } if (IsStar) { deriv = _builder.CreateConcat(step, this); break; } if (IsPlus) { SymbolicRegexNode<S> star = _builder.CreateLoop(_left, IsLazy); deriv = _builder.CreateConcat(step, star); break; } int newupper = _upper == int.MaxValue ? int.MaxValue : _upper - 1; int newlower = _lower == 0 ? 0 : _lower - 1; SymbolicRegexNode<S> rest = _builder.CreateLoop(_left, IsLazy, newlower, newupper); deriv = _builder.CreateConcat(step, rest); break; #endregion } case SymbolicRegexNodeKind.Concat: { #region d(a, AB) = d(a,A)B | (if A nullable then d(a,B)) Debug.Assert(_left is not null && _right is not null); SymbolicRegexNode<S> leftd = _left.CreateDerivative(elem, context); SymbolicRegexNode<S> first = _builder.CreateConcat(leftd, _right); if (_left.IsNullableFor(context)) { SymbolicRegexNode<S> second = _right.CreateDerivative(elem, context); deriv = _builder.Or(first, second); break; } deriv = first; break; #endregion } case SymbolicRegexNodeKind.Or: { #region d(a,A|B) = d(a,A)|d(a,B) Debug.Assert(_alts is not null && _alts._kind == SymbolicRegexNodeKind.Or); SymbolicRegexSet<S> alts_deriv = _alts.CreateDerivative(elem, context); // At this point alts_deriv can be the empty conjunction denoting .* deriv = _builder.Or(alts_deriv); break; #endregion } case SymbolicRegexNodeKind.OrderedOr: { #region d(a,A|B) = d(a,A)|d(a,B) Debug.Assert(_left is not null && _right is not null); SymbolicRegexNode<S> leftd = _left.CreateDerivative(elem, context); SymbolicRegexNode<S> rightd = _right.CreateDerivative(elem, context); deriv = _builder.OrderedOr(leftd, rightd); break; #endregion } case SymbolicRegexNodeKind.And: { #region d(a,A & B) = d(a,A) & d(a,B) Debug.Assert(_alts is not null && _alts._kind == SymbolicRegexNodeKind.And); SymbolicRegexSet<S> alts_deriv = _alts.CreateDerivative(elem, context); // At this point alts_deriv can be the empty disjunction denoting nothing deriv = _builder.And(alts_deriv); break; #endregion } case SymbolicRegexNodeKind.Not: { #region d(a,~(A)) = ~(d(a,A)) Debug.Assert(_left is not null); SymbolicRegexNode<S> leftD = _left.CreateDerivative(elem, context); deriv = _builder.Not(leftD); break; #endregion } default: deriv = _builder._nothing; break; } _MkDerivative_Cache[key] = deriv; return deriv; } private TransitionRegex<S>? _transitionRegex; /// <summary> /// Computes the symbolic derivative as a transition regex. /// Transitions are in the tree left to right in the order the backtracking engine would explore them. /// </summary> internal TransitionRegex<S> CreateDerivative() { if (_transitionRegex is not null) { return _transitionRegex; } if (IsNothing || IsEpsilon) { _transitionRegex = TransitionRegex<S>.Leaf(_builder._nothing); return _transitionRegex; } if (IsAnyStar || IsAnyPlus) { _transitionRegex = TransitionRegex<S>.Leaf(_builder._anyStar); return _transitionRegex; } if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(CreateDerivative); } switch (_kind) { case SymbolicRegexNodeKind.Singleton: Debug.Assert(_set is not null); _transitionRegex = TransitionRegex<S>.Conditional(_set, TransitionRegex<S>.Leaf(_builder.Epsilon), TransitionRegex<S>.Leaf(_builder._nothing)); break; case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); TransitionRegex<S> mainTransition = _left.CreateDerivative().Concat(_right); if (!_left.CanBeNullable) { // If _left is never nullable _transitionRegex = mainTransition; } else if (_left.IsNullable) { // If _left is unconditionally nullable _transitionRegex = TransitionRegex<S>.Union(mainTransition, _right.CreateDerivative()); } else { // The left side contains anchors and can be nullable in some context // Extract the nullability as the lookaround condition SymbolicRegexNode<S> leftNullabilityTest = _left.ExtractNullabilityTest(); _transitionRegex = TransitionRegex<S>.Lookaround(leftNullabilityTest, TransitionRegex<S>.Union(mainTransition, _right.CreateDerivative()), mainTransition); } break; case SymbolicRegexNodeKind.Loop: // d(R*) = d(R+) = d(R)R* Debug.Assert(_left is not null); Debug.Assert(_upper > 0); TransitionRegex<S> step = _left.CreateDerivative(); if (IsStar || IsPlus) { _transitionRegex = step.Concat(_builder.CreateLoop(_left, IsLazy)); } else { int newupper = _upper == int.MaxValue ? int.MaxValue : _upper - 1; int newlower = _lower == 0 ? 0 : _lower - 1; SymbolicRegexNode<S> rest = _builder.CreateLoop(_left, IsLazy, newlower, newupper); _transitionRegex = step.Concat(rest); } break; case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); _transitionRegex = TransitionRegex<S>.Leaf(_builder._nothing); foreach (SymbolicRegexNode<S> elem in _alts) { _transitionRegex = TransitionRegex<S>.Union(_transitionRegex, elem.CreateDerivative()); } break; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); _transitionRegex = TransitionRegex<S>.Union(_left.CreateDerivative(), _right.CreateDerivative()); break; case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); _transitionRegex = TransitionRegex<S>.Leaf(_builder._anyStar); foreach (SymbolicRegexNode<S> elem in _alts) { _transitionRegex = TransitionRegex<S>.Intersect(_transitionRegex, elem.CreateDerivative()); } break; case SymbolicRegexNodeKind.Not: Debug.Assert(_left is not null); _transitionRegex = _left.CreateDerivative().Complement(); break; default: _transitionRegex = TransitionRegex<S>.Leaf(_builder._nothing); break; } return _transitionRegex; } // These are the cache for transition regexes with effects private TransitionRegex<S>? _transitionRegexWithEffectsEager; private TransitionRegex<S>? _transitionRegexWithEffectsAny; private ref TransitionRegex<S>? TransitionRegexWithEffects(bool eager) => ref eager ? ref _transitionRegexWithEffectsEager : ref _transitionRegexWithEffectsAny; /// <summary> /// Computes the symbolic derivative as a transition regex. /// Transitions are in the tree left to right in the order the backtracking engine would explore them. /// The transitions also include the effects (e.g. capture starts and ends) along their paths. /// </summary> /// <param name="eager">whether to only include paths before the first time the backtracking matchers would hit nullability</param> /// <returns>the derivative as a TransitionRegex/></returns> internal TransitionRegex<S> CreateDerivativeWithEffects(bool eager) { // Get a reference to the correct variable to cache on based on eagerness ref TransitionRegex<S>? transition = ref TransitionRegexWithEffects(eager); if (transition is not null) { return transition; } if (IsNothing || IsEpsilon) { transition = TransitionRegex<S>.Leaf(_builder._nothing); return transition; } if (IsAnyStar || IsAnyPlus) { transition = TransitionRegex<S>.Leaf(_builder._anyStar); return transition; } if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(CreateDerivativeWithEffects, eager); } switch (_kind) { case SymbolicRegexNodeKind.Singleton: Debug.Assert(_set is not null); transition = TransitionRegex<S>.Conditional(_set, TransitionRegex<S>.Leaf(_builder.Epsilon), TransitionRegex<S>.Leaf(_builder._nothing)); break; case SymbolicRegexNodeKind.Concat: { // The Concat case below explicitly handles cases where the left side is an alternation or a loop. // This is required for properly maintaining transition ordering and handling eagerness. Debug.Assert(_left is not null && _right is not null); TransitionRegex<S> leftTransition = _left.CreateDerivativeWithEffects(eager).Concat(_right); if (!_left.CanBeNullable) { // If the left side can't be nullable then the character must be consumed there transition = leftTransition; } else if (_left._kind == SymbolicRegexNodeKind.OrderedOr) { Debug.Assert(_left._left is not null && _left._right is not null); // This pattern is for the path where the backtracking matcher would find the match from the first alternative SymbolicRegexNode<S> leftLeftPath = _builder.CreateConcat(_left._left, _right); // The eager derivative of that path will be used when the pattern is nullable, i.e., the backtracking matcher // would end the match rather than go onto paths in the second alternative. TransitionRegex<S> leftLeftTransition = leftLeftPath.CreateDerivativeWithEffects(eager); // When the path through the first alternative is not nullable, this transition that includes all derivatives from // it is used. TransitionRegex<S> orTransition = TransitionRegex<S>.Union(leftLeftPath.CreateDerivativeWithEffects(false), _builder.CreateConcat(_left._right, _right).CreateDerivativeWithEffects(eager), ordered: true); // Based on the nullability of the path thorugh the first alternative, select or construct the transition for when // the left side of the concatenation is nullable. TransitionRegex<S> leftNullableTransition = eager && leftLeftPath.CanBeNullable ? (leftLeftPath.IsNullable ? leftLeftTransition : TransitionRegex<S>.Lookaround(leftLeftPath.ExtractNullabilityTest(), leftLeftTransition, orTransition)) : orTransition; // Select or construct the transition based on whether the left side is nullable transition = _left.IsNullable ? leftNullableTransition : TransitionRegex<S>.Lookaround(_left.ExtractNullabilityTest(), leftNullableTransition, leftTransition); } else { // The full derivative through the left side is used when the right side is not nullable or the derivative is not eager TransitionRegex<S> leftAnyTransition = _left.CreateDerivativeWithEffects(false).Concat(_right); // Select or construct the case where the left side consumes the character TransitionRegex<S> mainTransition = eager ? (_right.CanBeNullable ? (_right.IsNullable ? leftTransition : TransitionRegex<S>.Lookaround(_right.ExtractNullabilityTest(), leftTransition, leftAnyTransition)) : leftAnyTransition) : leftAnyTransition; // Construct the case where the right side consumes the character. Any effects from the left side are applied TransitionRegex<S> nullTransition = _left.WrapEffects(_right.CreateDerivativeWithEffects(eager)); // Order the transitions. If the left side is a lazy loop that is nullable due to its lower bound then prefer the right side TransitionRegex<S> orTransition = _left._kind == SymbolicRegexNodeKind.Loop && _left.IsLazy && _left._lower == 0 ? TransitionRegex<S>.Union(nullTransition, mainTransition, ordered: true) : TransitionRegex<S>.Union(mainTransition, nullTransition, ordered: true); // Select or construct the transition based on whether the left side is nullable transition = _left.IsNullable ? orTransition : TransitionRegex<S>.Lookaround(_left.ExtractNullabilityTest(), orTransition, leftTransition); } break; } case SymbolicRegexNodeKind.Loop: // d(R*) = d(R+) = d(R)R* Debug.Assert(_left is not null); Debug.Assert(_upper > 0); if (eager && IsLazy && _lower == 0) { // This is nothing because the backtracking matcher would prefer to exit the loop transition = TransitionRegex<S>.Leaf(_builder._nothing); } else { TransitionRegex<S> step = _left.CreateDerivativeWithEffects(eager); if (IsStar || IsPlus) { transition = step.Concat(_builder.CreateLoop(_left, IsLazy)); } else { int newupper = _upper == int.MaxValue ? int.MaxValue : _upper - 1; int newlower = _lower == 0 ? 0 : _lower - 1; SymbolicRegexNode<S> rest = _builder.CreateLoop(_left, IsLazy, newlower, newupper); transition = step.Concat(rest); } } break; case SymbolicRegexNodeKind.OrderedOr: { Debug.Assert(_left is not null && _right is not null); // The transition when the first alternative is nullable TransitionRegex<S> leftTransition = _left.CreateDerivativeWithEffects(eager); // The transition when the backtracking engines could continue to the second alternative TransitionRegex<S> orTransition = TransitionRegex<S>.Union(_left.CreateDerivativeWithEffects(false), _right.CreateDerivativeWithEffects(eager), ordered: true); // Select or construct the transition based on whether the first alternative is nullable transition = eager && _left.CanBeNullable ? (_left.IsNullable ? leftTransition : TransitionRegex<S>.Lookaround(_left.ExtractNullabilityTest(), leftTransition, orTransition)) : orTransition; break; } case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); transition = TransitionRegex<S>.Leaf(_builder._nothing); foreach (SymbolicRegexNode<S> elem in _alts) { transition = TransitionRegex<S>.Union(transition, elem.CreateDerivativeWithEffects(eager)); } break; case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); transition = TransitionRegex<S>.Leaf(_builder._anyStar); foreach (SymbolicRegexNode<S> elem in _alts) { transition = TransitionRegex<S>.Intersect(transition, elem.CreateDerivativeWithEffects(eager)); } break; case SymbolicRegexNodeKind.Not: Debug.Assert(_left is not null); transition = _left.CreateDerivativeWithEffects(eager).Complement(); break; default: transition = TransitionRegex<S>.Leaf(_builder._nothing); break; } return transition; } /// <summary> /// Wrap a TransitionRegex with the effects under this node. The effects are valid when this node is nullable. /// </summary> /// <remarks> /// The construction follows the paths that the backtracking matcher would take. For example in ()|() only the effects for the first /// alternative will be included. /// </remarks> internal TransitionRegex<S> WrapEffects(TransitionRegex<S> transition) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(WrapEffects, transition); } switch (_kind) { case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); Debug.Assert(_left.CanBeNullable && _right.CanBeNullable); transition = _left.WrapEffects(transition); transition = _right.WrapEffects(transition); break; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); // Apply effect when backtracking engine would enter loop if (_lower != 0) { Debug.Assert(_left.CanBeNullable); transition = _left.WrapEffects(transition); } else if (_upper != 0 && !IsLazy && _left.CanBeNullable) { TransitionRegex<S> bodyTransition = _left.WrapEffects(transition); transition = _left.IsNullable ? bodyTransition : TransitionRegex<S>.Lookaround(_left.ExtractNullabilityTest(), bodyTransition, transition); } break; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); if (!_left.CanBeNullable) { // Left can't be nullable so right must be visited Debug.Assert(_right.CanBeNullable); transition = _right.WrapEffects(transition); } else if (!_right.CanBeNullable) { // Right can't be nullable so left must be visited Debug.Assert(_left.CanBeNullable); transition = _left.WrapEffects(transition); } else { // Prefer left side if it is nullable, otherwise right side TransitionRegex<S> leftTransition = _left.WrapEffects(transition); transition = _left.IsNullable ? leftTransition : TransitionRegex<S>.Lookaround(_left.ExtractNullabilityTest(), leftTransition, _right.WrapEffects(transition)); } break; case SymbolicRegexNodeKind.CaptureStart: // Add the effect to record the capture start transition = TransitionRegex<S>.Effect(transition, new DerivativeEffect(DerivativeEffectKind.CaptureStart, _lower)); break; case SymbolicRegexNodeKind.CaptureEnd: // Add the effect to record the capture start transition = TransitionRegex<S>.Effect(transition, new DerivativeEffect(DerivativeEffectKind.CaptureEnd, _lower)); break; case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); foreach (SymbolicRegexNode<S> elem in _alts) { if (elem.CanBeNullable) transition = elem.IsNullable ? elem.WrapEffects(transition) : TransitionRegex<S>.Lookaround(elem.ExtractNullabilityTest(), elem.WrapEffects(transition), transition); } break; case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); foreach (SymbolicRegexNode<S> elem in _alts) { Debug.Assert(elem.CanBeNullable); transition = elem.WrapEffects(transition); } break; } return transition; } /// <summary> /// Find all effects under this node and supply them to the callback. /// </summary> /// <remarks> /// The construction is similar to WrapEffects. /// </remarks> /// <param name="apply">action called for each effect</param> /// <param name="context">the current context to determine nullability</param> internal void ApplyEffects(Action<DerivativeEffect> apply, uint context) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(ApplyEffects, apply, context); return; } switch (_kind) { case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); Debug.Assert(_left.IsNullableFor(context) && _right.IsNullableFor(context)); _left.ApplyEffects(apply, context); _right.ApplyEffects(apply, context); break; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); // Apply effect when backtracking engine would enter loop if (_lower != 0 || (_upper != 0 && !IsLazy && _left.IsNullableFor(context))) { Debug.Assert(_left.IsNullableFor(context)); _left.ApplyEffects(apply, context); } break; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); if (_left.IsNullableFor(context)) { // Prefer the left side _left.ApplyEffects(apply, context); } else { // Otherwise right side must be nullable Debug.Assert(_right.IsNullableFor(context)); _right.ApplyEffects(apply, context); } break; case SymbolicRegexNodeKind.CaptureStart: apply(new DerivativeEffect(DerivativeEffectKind.CaptureStart, _lower)); break; case SymbolicRegexNodeKind.CaptureEnd: apply(new DerivativeEffect(DerivativeEffectKind.CaptureEnd, _lower)); break; case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); foreach (SymbolicRegexNode<S> elem in _alts) { if (elem.IsNullableFor(context)) elem.ApplyEffects(apply, context); } break; case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); foreach (SymbolicRegexNode<S> elem in _alts) { Debug.Assert(elem.IsNullableFor(context)); elem.ApplyEffects(apply, context); } break; } } /// <summary> /// Computes the closure of CreateDerivative, by exploring all the leaves /// of the transition regex until no more new leaves are found. /// Converts the resulting transition system into a symbolic NFA. /// If the exploration remains incomplete due to the given state bound /// being reached then the InComplete property of the constructed NFA is true. /// </summary> internal SymbolicNFA<S> Explore(int bound) => SymbolicNFA<S>.Explore(this, bound); /// <summary>Extracts the nullability test as a Boolean combination of anchors</summary> public SymbolicRegexNode<S> ExtractNullabilityTest() { if (IsNullable) { return _builder._anyStar; } if (!CanBeNullable) { return _builder._nothing; } if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(ExtractNullabilityTest); } switch (_kind) { case SymbolicRegexNodeKind.BeginningAnchor: case SymbolicRegexNodeKind.EndAnchor: case SymbolicRegexNodeKind.BOLAnchor: case SymbolicRegexNodeKind.EOLAnchor: case SymbolicRegexNodeKind.BoundaryAnchor: case SymbolicRegexNodeKind.NonBoundaryAnchor: case SymbolicRegexNodeKind.EndAnchorZ: case SymbolicRegexNodeKind.EndAnchorZReverse: return this; case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); return _builder.And(_left.ExtractNullabilityTest(), _right.ExtractNullabilityTest()); case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); SymbolicRegexNode<S> disjunction = _builder._nothing; foreach (SymbolicRegexNode<S> elem in _alts) { disjunction = _builder.Or(disjunction, elem.ExtractNullabilityTest()); } return disjunction; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); return _builder.OrderedOr(_left.ExtractNullabilityTest(), _right.ExtractNullabilityTest()); case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); SymbolicRegexNode<S> conjunction = _builder._anyStar; foreach (SymbolicRegexNode<S> elem in _alts) { conjunction = _builder.And(conjunction, elem.ExtractNullabilityTest()); } return conjunction; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); return _left.ExtractNullabilityTest(); default: // All remaining cases could not be nullable or were trivially nullable // Singleton cannot be nullable and Epsilon and FixedLengthMarker are trivially nullable Debug.Assert(_kind == SymbolicRegexNodeKind.Not && _left is not null); return _builder.Not(_left.ExtractNullabilityTest()); } } public override int GetHashCode() { return _hashcode; } private int ComputeHashCode() { switch (_kind) { case SymbolicRegexNodeKind.EndAnchor: case SymbolicRegexNodeKind.BeginningAnchor: case SymbolicRegexNodeKind.BOLAnchor: case SymbolicRegexNodeKind.EOLAnchor: case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.BoundaryAnchor: case SymbolicRegexNodeKind.NonBoundaryAnchor: case SymbolicRegexNodeKind.EndAnchorZ: case SymbolicRegexNodeKind.EndAnchorZReverse: return HashCode.Combine(_kind, _info); case SymbolicRegexNodeKind.FixedLengthMarker: case SymbolicRegexNodeKind.CaptureStart: case SymbolicRegexNodeKind.CaptureEnd: return HashCode.Combine(_kind, _lower); case SymbolicRegexNodeKind.Loop: return HashCode.Combine(_kind, _left, _lower, _upper, _info); case SymbolicRegexNodeKind.Or or SymbolicRegexNodeKind.And: return HashCode.Combine(_kind, _alts, _info); case SymbolicRegexNodeKind.Concat: case SymbolicRegexNodeKind.OrderedOr: return HashCode.Combine(_left, _right, _info); case SymbolicRegexNodeKind.Singleton: return HashCode.Combine(_kind, _set); default: Debug.Assert(_kind == SymbolicRegexNodeKind.Not); return HashCode.Combine(_kind, _left, _info); }; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is not SymbolicRegexNode<S> that) { return false; } if (this == that) { return true; } if (_kind != that._kind) { return false; } if (_kind == SymbolicRegexNodeKind.Or) { if (_isInternalizedUnion && that._isInternalizedUnion) { // Internalized nodes that are not identical are not equal return false; } // Check equality of the sets of regexes Debug.Assert(_alts is not null && that._alts is not null); if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(_alts.Equals, that._alts); } return _alts.Equals(that._alts); } return false; } private void ToStringForLoop(StringBuilder sb) { if (_kind == SymbolicRegexNodeKind.Singleton) { ToString(sb); } else { sb.Append('('); ToString(sb); sb.Append(')'); } } public override string ToString() { StringBuilder sb = new(); ToString(sb); return sb.ToString(); } internal void ToString(StringBuilder sb) { // Guard against stack overflow due to deep recursion if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(ToString, sb); return; } switch (_kind) { case SymbolicRegexNodeKind.EndAnchor: sb.Append("\\z"); return; case SymbolicRegexNodeKind.BeginningAnchor: sb.Append("\\A"); return; case SymbolicRegexNodeKind.BOLAnchor: sb.Append('^'); return; case SymbolicRegexNodeKind.EOLAnchor: sb.Append('$'); return; case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.FixedLengthMarker: return; case SymbolicRegexNodeKind.BoundaryAnchor: sb.Append("\\b"); return; case SymbolicRegexNodeKind.NonBoundaryAnchor: sb.Append("\\B"); return; case SymbolicRegexNodeKind.EndAnchorZ: sb.Append("\\Z"); return; case SymbolicRegexNodeKind.EndAnchorZReverse: sb.Append("\\a"); return; case SymbolicRegexNodeKind.Or: case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); _alts.ToString(sb); return; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); _left.ToString(sb); sb.Append('|'); _right.ToString(sb); return; case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); _left.ToString(sb); _right.ToString(sb); return; case SymbolicRegexNodeKind.Singleton: Debug.Assert(_set is not null); sb.Append(_builder._solver.PrettyPrint(_set)); return; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); if (IsAnyStar) { sb.Append(".*"); } else if (_lower == 0 && _upper == 1) { _left.ToStringForLoop(sb); sb.Append('?'); } else if (IsStar) { _left.ToStringForLoop(sb); sb.Append('*'); if (IsLazy) { sb.Append('?'); } } else if (IsPlus) { _left.ToStringForLoop(sb); sb.Append('+'); if (IsLazy) { sb.Append('?'); } } else if (_lower == 0 && _upper == 0) { sb.Append("()"); } else { _left.ToStringForLoop(sb); sb.Append('{'); sb.Append(_lower); if (!IsBoundedLoop) { sb.Append(','); } else if (_lower != _upper) { sb.Append(','); sb.Append(_upper); } sb.Append('}'); if (IsLazy) sb.Append('?'); } return; case SymbolicRegexNodeKind.CaptureStart: sb.Append('('); // The group number may be wrong return; case SymbolicRegexNodeKind.CaptureEnd: sb.Append(')'); return; default: // Using the operator ~ for complement Debug.Assert(_kind == SymbolicRegexNodeKind.Not); Debug.Assert(_left is not null); sb.Append("~("); _left.ToString(sb); sb.Append(')'); return; } } /// <summary> /// Returns the set of all predicates that occur in the regex or /// the set containing True if there are no precidates in the regex, e.g., if the regex is "^" /// </summary> public HashSet<S> GetPredicates() { var predicates = new HashSet<S>(); CollectPredicates_helper(predicates); return predicates; } /// <summary> /// Collects all predicates that occur in the regex into the given set predicates /// </summary> private void CollectPredicates_helper(HashSet<S> predicates) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(CollectPredicates_helper, predicates); return; } switch (_kind) { case SymbolicRegexNodeKind.BOLAnchor: case SymbolicRegexNodeKind.EOLAnchor: case SymbolicRegexNodeKind.EndAnchorZ: case SymbolicRegexNodeKind.EndAnchorZReverse: predicates.Add(_builder._newLinePredicate); return; case SymbolicRegexNodeKind.BeginningAnchor: case SymbolicRegexNodeKind.EndAnchor: case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.FixedLengthMarker: case SymbolicRegexNodeKind.CaptureStart: case SymbolicRegexNodeKind.CaptureEnd: return; case SymbolicRegexNodeKind.Singleton: Debug.Assert(_set is not null); predicates.Add(_set); return; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); _left.CollectPredicates_helper(predicates); return; case SymbolicRegexNodeKind.Or: case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); foreach (SymbolicRegexNode<S> sr in _alts) { sr.CollectPredicates_helper(predicates); } return; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); _left.CollectPredicates_helper(predicates); _right.CollectPredicates_helper(predicates); return; case SymbolicRegexNodeKind.Concat: // avoid deep nested recursion over long concat nodes SymbolicRegexNode<S> conc = this; while (conc._kind == SymbolicRegexNodeKind.Concat) { Debug.Assert(conc._left is not null && conc._right is not null); conc._left.CollectPredicates_helper(predicates); conc = conc._right; } conc.CollectPredicates_helper(predicates); return; case SymbolicRegexNodeKind.Not: Debug.Assert(_left is not null); _left.CollectPredicates_helper(predicates); return; case SymbolicRegexNodeKind.NonBoundaryAnchor: case SymbolicRegexNodeKind.BoundaryAnchor: predicates.Add(_builder._wordLetterPredicateForAnchors); return; default: Debug.Fail($"{nameof(CollectPredicates_helper)}:{_kind}"); break; } } /// <summary> /// Compute all the minterms from the predicates in this regex. /// If S implements IComparable then sort the result in increasing order. /// </summary> public S[] ComputeMinterms() { Debug.Assert(typeof(S).IsAssignableTo(typeof(IComparable<S>))); HashSet<S> predicates = GetPredicates(); List<S> mt = _builder._solver.GenerateMinterms(predicates); mt.Sort(); return mt.ToArray(); } /// <summary> /// Create the reverse of this regex /// </summary> public SymbolicRegexNode<S> Reverse() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(Reverse); } switch (_kind) { case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); return _builder.CreateLoop(_left.Reverse(), IsLazy, _lower, _upper); case SymbolicRegexNodeKind.Concat: { Debug.Assert(_left is not null && _right is not null); SymbolicRegexNode<S> rev = _left.Reverse(); SymbolicRegexNode<S> rest = _right; while (rest._kind == SymbolicRegexNodeKind.Concat) { Debug.Assert(rest._left is not null && rest._right is not null); SymbolicRegexNode<S> rev1 = rest._left.Reverse(); rev = _builder.CreateConcat(rev1, rev); rest = rest._right; } SymbolicRegexNode<S> restr = rest.Reverse(); rev = _builder.CreateConcat(restr, rev); return rev; } case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); return _builder.Or(_alts.Reverse()); case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); return _builder.OrderedOr(_left.Reverse(), _right.Reverse()); case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); return _builder.And(_alts.Reverse()); case SymbolicRegexNodeKind.Not: Debug.Assert(_left is not null); return _builder.Not(_left.Reverse()); case SymbolicRegexNodeKind.FixedLengthMarker: // Fixed length markers are omitted in reverse return _builder.Epsilon; case SymbolicRegexNodeKind.BeginningAnchor: // The reverse of BeginningAnchor is EndAnchor return _builder.EndAnchor; case SymbolicRegexNodeKind.EndAnchor: return _builder.BeginningAnchor; case SymbolicRegexNodeKind.BOLAnchor: // The reverse of BOLanchor is EOLanchor return _builder.EolAnchor; case SymbolicRegexNodeKind.EOLAnchor: return _builder.BolAnchor; case SymbolicRegexNodeKind.EndAnchorZ: // The reversal of the \Z anchor return _builder.EndAnchorZReverse; case SymbolicRegexNodeKind.EndAnchorZReverse: // This can potentially only happen if a reversed regex is reversed again. // Thus, this case is unreachable here, but included for completeness. return _builder.EndAnchorZ; case SymbolicRegexNodeKind.CaptureStart: return CreateCaptureEnd(_builder, _lower); case SymbolicRegexNodeKind.CaptureEnd: return CreateCaptureStart(_builder, _lower); // Remaining cases map to themselves: case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.Singleton: case SymbolicRegexNodeKind.BoundaryAnchor: case SymbolicRegexNodeKind.NonBoundaryAnchor: default: return this; } } /// <summary> /// Transform OrderdOr to Or nodes and any lazy loops to eager ones. /// </summary> /// <remarks> /// This transformation allows the second reverse pass to use the same derivative function as the third pass, /// which must respect the backtracking engines alternation and lazyness semantics. /// </remarks> public SymbolicRegexNode<S> IgnoreOrOrderAndLazyness() { // Guard against stack overflow due to deep recursion if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(IgnoreOrOrderAndLazyness); } switch (_kind) { case SymbolicRegexNodeKind.Loop: { Debug.Assert(_left is not null); SymbolicRegexNode<S> body = _left.IgnoreOrOrderAndLazyness(); return body == _left && !IsLazy ? this : CreateLoop(_builder, body, _lower, _upper, isLazy: false); } case SymbolicRegexNodeKind.Concat: { Debug.Assert(_left is not null && _right is not null); SymbolicRegexNode<S> left1 = _left.IgnoreOrOrderAndLazyness(); SymbolicRegexNode<S> right1 = _right.IgnoreOrOrderAndLazyness(); Debug.Assert(left1 is not null && right1 is not null); return left1 == _left && right1 == _right ? this : CreateConcat(_builder, left1, right1); } case SymbolicRegexNodeKind.Or: case SymbolicRegexNodeKind.And: { Debug.Assert(_alts != null); var elements = new SymbolicRegexNode<S>[_alts.Count]; int i = 0; bool someChanged = false; foreach (SymbolicRegexNode<S> alt in _alts) { elements[i] = alt.IgnoreOrOrderAndLazyness(); someChanged |= alt != elements[i]; i += 1; } Debug.Assert(i == elements.Length); return !someChanged ? this : _kind == SymbolicRegexNodeKind.Or ? Or(_builder, elements) : And(_builder, elements); } case SymbolicRegexNodeKind.Not: { Debug.Assert(_left is not null); SymbolicRegexNode<S> body = _left.IgnoreOrOrderAndLazyness(); return body == _left ? this : Not(_builder, body); } case SymbolicRegexNodeKind.OrderedOr: { Debug.Assert(_left is not null && _right is not null); return Or(_builder, _left.IgnoreOrOrderAndLazyness(), _right.IgnoreOrOrderAndLazyness()); } default: return this; } } internal bool StartsWithLoop(int upperBoundLowestValue = 1) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(StartsWithLoop, upperBoundLowestValue); } switch (_kind) { case SymbolicRegexNodeKind.Loop: return (_upper < int.MaxValue) && (_upper > upperBoundLowestValue); case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); return _left.StartsWithLoop(upperBoundLowestValue) || (_left.IsNullable && _right.StartsWithLoop(upperBoundLowestValue)); case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); return _alts.StartsWithLoop(upperBoundLowestValue); case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); return _left.StartsWithLoop(upperBoundLowestValue) || _right.StartsWithLoop(upperBoundLowestValue); default: return false; }; } /// <summary>Get the predicate that covers all elements that make some progress.</summary> internal S GetStartSet() => _startSet; /// <summary>Compute the predicate that covers all elements that make some progress.</summary> private S ComputeStartSet() { switch (_kind) { // Anchors and () do not contribute to the startset case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.FixedLengthMarker: case SymbolicRegexNodeKind.EndAnchor: case SymbolicRegexNodeKind.BeginningAnchor: case SymbolicRegexNodeKind.BoundaryAnchor: case SymbolicRegexNodeKind.NonBoundaryAnchor: case SymbolicRegexNodeKind.EOLAnchor: case SymbolicRegexNodeKind.EndAnchorZ: case SymbolicRegexNodeKind.EndAnchorZReverse: case SymbolicRegexNodeKind.BOLAnchor: case SymbolicRegexNodeKind.CaptureStart: case SymbolicRegexNodeKind.CaptureEnd: return _builder._solver.False; case SymbolicRegexNodeKind.Singleton: Debug.Assert(_set is not null); return _set; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); return _left._startSet; case SymbolicRegexNodeKind.Concat: { Debug.Assert(_left is not null && _right is not null); S startSet = _left.CanBeNullable ? _builder._solver.Or(_left._startSet, _right._startSet) : _left._startSet; return startSet; } case SymbolicRegexNodeKind.Or: { Debug.Assert(_alts is not null); S startSet = _builder._solver.False; foreach (SymbolicRegexNode<S> alt in _alts) { startSet = _builder._solver.Or(startSet, alt._startSet); } return startSet; } case SymbolicRegexNodeKind.OrderedOr: { Debug.Assert(_left is not null && _right is not null); return _builder._solver.Or(_left._startSet, _right._startSet); } case SymbolicRegexNodeKind.And: { Debug.Assert(_alts is not null); S startSet = _builder._solver.True; foreach (SymbolicRegexNode<S> alt in _alts) { startSet = _builder._solver.And(startSet, alt._startSet); } return startSet; } default: Debug.Assert(_kind == SymbolicRegexNodeKind.Not); return _builder._solver.True; } } /// <summary> /// Returns true if this is a loop with an upper bound /// </summary> public bool IsBoundedLoop => _kind == SymbolicRegexNodeKind.Loop && _upper < int.MaxValue; /// <summary> /// Replace anchors that are infeasible by [] wrt the given previous character kind and what continuation is possible. /// </summary> /// <param name="prevKind">previous character kind</param> /// <param name="contWithWL">if true the continuation can start with wordletter or stop</param> /// <param name="contWithNWL">if true the continuation can start with nonwordletter or stop</param> internal SymbolicRegexNode<S> PruneAnchors(uint prevKind, bool contWithWL, bool contWithNWL) { // Guard against stack overflow due to deep recursion if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(PruneAnchors, prevKind, contWithWL, contWithNWL); } if (!_info.StartsWithSomeAnchor) return this; switch (_kind) { case SymbolicRegexNodeKind.BeginningAnchor: return prevKind == CharKind.BeginningEnd ? this : _builder._nothing; //start anchor is only nullable if the previous character is Start case SymbolicRegexNodeKind.EndAnchorZReverse: return ((prevKind & CharKind.BeginningEnd) != 0) ? this : _builder._nothing; //rev(\Z) is only nullable if the previous characters is Start or the very first \n case SymbolicRegexNodeKind.BoundaryAnchor: return (prevKind == CharKind.WordLetter ? contWithNWL : contWithWL) ? this : // \b is impossible when the previous character is \w but no continuation matches \W // or the previous character is \W but no continuation matches \w _builder._nothing; case SymbolicRegexNodeKind.NonBoundaryAnchor: return (prevKind == CharKind.WordLetter ? contWithWL : contWithNWL) ? this : // \B is impossible when the previous character is \w but no continuation matches \w // or the previous character is \W but no continuation matches \W _builder._nothing; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); SymbolicRegexNode<S> body = _left.PruneAnchors(prevKind, contWithWL, contWithNWL); return body == _left ? this : CreateLoop(_builder, body, _lower, _upper, IsLazy); case SymbolicRegexNodeKind.Concat: { Debug.Assert(_left is not null && _right is not null); SymbolicRegexNode<S> left1 = _left.PruneAnchors(prevKind, contWithWL, contWithNWL); SymbolicRegexNode<S> right1 = _left.IsNullable ? _right.PruneAnchors(prevKind, contWithWL, contWithNWL) : _right; Debug.Assert(left1 is not null && right1 is not null); return left1 == _left && right1 == _right ? this : CreateConcat(_builder, left1, right1); } case SymbolicRegexNodeKind.Or: { Debug.Assert(_alts != null); var elements = new SymbolicRegexNode<S>[_alts.Count]; int i = 0; foreach (SymbolicRegexNode<S> alt in _alts) { elements[i++] = alt.PruneAnchors(prevKind, contWithWL, contWithNWL); } Debug.Assert(i == elements.Length); return Or(_builder, elements); } case SymbolicRegexNodeKind.OrderedOr: { Debug.Assert(_left is not null && _right is not null); SymbolicRegexNode<S> left1 = _left.PruneAnchors(prevKind, contWithWL, contWithNWL); SymbolicRegexNode<S> right1 = _right.PruneAnchors(prevKind, contWithWL, contWithNWL); Debug.Assert(left1 is not null && right1 is not null); return left1 == _left && right1 == _right ? this : OrderedOr(_builder, left1, right1); } default: return 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.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents an AST node of a symbolic regex.</summary> internal sealed class SymbolicRegexNode<S> where S : notnull { internal const string EmptyCharClass = "[]"; /// <summary>Some byte other than 0 to represent true</summary> internal const byte TrueByte = 1; /// <summary>Some byte other than 0 to represent false</summary> internal const byte FalseByte = 2; /// <summary>The undefined value is the default value 0</summary> internal const byte UndefinedByte = 0; internal readonly SymbolicRegexBuilder<S> _builder; internal readonly SymbolicRegexNodeKind _kind; internal readonly int _lower; internal readonly int _upper; internal readonly S? _set; internal readonly SymbolicRegexNode<S>? _left; internal readonly SymbolicRegexNode<S>? _right; internal readonly SymbolicRegexSet<S>? _alts; /// <summary> /// Caches nullability of this node for any given context (0 &lt;= context &lt; ContextLimit) /// when _info.StartsWithSomeAnchor and _info.CanBeNullable are true. Otherwise the cache is null. /// </summary> private byte[]? _nullabilityCache; private S _startSet; /// <summary>AST node of a symbolic regex</summary> /// <param name="builder">the builder</param> /// <param name="kind">what kind of node</param> /// <param name="left">left child</param> /// <param name="right">right child</param> /// <param name="lower">lower bound of a loop</param> /// <param name="upper">upper boubd of a loop</param> /// <param name="set">singelton set</param> /// <param name="alts">alternatives set of a disjunction or conjunction</param> /// <param name="info">misc flags including laziness</param> private SymbolicRegexNode(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind, SymbolicRegexNode<S>? left, SymbolicRegexNode<S>? right, int lower, int upper, S? set, SymbolicRegexSet<S>? alts, SymbolicRegexInfo info) { _builder = builder; _kind = kind; _left = left; _right = right; _lower = lower; _upper = upper; _set = set; _alts = alts; _info = info; _hashcode = ComputeHashCode(); _startSet = ComputeStartSet(); _nullabilityCache = info.StartsWithSomeAnchor && info.CanBeNullable ? new byte[CharKind.ContextLimit] : null; } private bool _isInternalizedUnion; /// <summary> Create a new node or retrieve one from the builder _nodeCache</summary> private static SymbolicRegexNode<S> Create(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind, SymbolicRegexNode<S>? left, SymbolicRegexNode<S>? right, int lower, int upper, S? set, SymbolicRegexSet<S>? alts, SymbolicRegexInfo info) { SymbolicRegexNode<S>? node; var key = (kind, left, right, lower, upper, set, alts, info); if (!builder._nodeCache.TryGetValue(key, out node)) { // Do not internalize top level Or-nodes or else NFA mode will become ineffective if (kind == SymbolicRegexNodeKind.Or) { node = new(builder, kind, left, right, lower, upper, set, alts, info); return node; } left = left == null || left._kind != SymbolicRegexNodeKind.Or || left._isInternalizedUnion ? left : Internalize(left); right = right == null || right._kind != SymbolicRegexNodeKind.Or || right._isInternalizedUnion ? right : Internalize(right); node = new(builder, kind, left, right, lower, upper, set, alts, info); builder._nodeCache[key] = node; } Debug.Assert(node is not null); return node; } /// <summary> Internalize an Or-node that is not yet internalized</summary> private static SymbolicRegexNode<S> Internalize(SymbolicRegexNode<S> node) { Debug.Assert(node._kind == SymbolicRegexNodeKind.Or && !node._isInternalizedUnion); (SymbolicRegexNodeKind, SymbolicRegexNode<S>?, SymbolicRegexNode<S>?, int, int, S?, SymbolicRegexSet<S>?, SymbolicRegexInfo) node_key = (SymbolicRegexNodeKind.Or, null, null, -1, -1, default(S), node._alts, node._info); SymbolicRegexNode<S>? node1; if (node._builder._nodeCache.TryGetValue(node_key, out node1)) { Debug.Assert(node1 is not null && node1._isInternalizedUnion); return node1; } else { node._isInternalizedUnion = true; node._builder._nodeCache[node_key] = node; return node; } } /// <summary>True if this node only involves lazy loops</summary> internal bool IsLazy => _info.IsLazy; /// <summary>True if this node accepts the empty string unconditionally.</summary> internal bool IsNullable => _info.IsNullable; /// <summary>True if this node can potentially accept the empty string depending on anchors and immediate context.</summary> internal bool CanBeNullable { get { Debug.Assert(_info.CanBeNullable || !_info.IsNullable); return _info.CanBeNullable; } } internal SymbolicRegexInfo _info; private readonly int _hashcode; /// <summary>Converts a Concat or OrderdOr into an array, returns anything else in a singleton array.</summary> /// <param name="list">a list to insert the elements into, or null to return results in a new list</param> /// <param name="listKind">kind of node to consider as the list builder</param> public List<SymbolicRegexNode<S>> ToList(List<SymbolicRegexNode<S>>? list = null, SymbolicRegexNodeKind listKind = SymbolicRegexNodeKind.Concat) { Debug.Assert(listKind == SymbolicRegexNodeKind.Concat || listKind == SymbolicRegexNodeKind.OrderedOr); list ??= new List<SymbolicRegexNode<S>>(); AppendToList(this, list, listKind); return list; static void AppendToList(SymbolicRegexNode<S> concat, List<SymbolicRegexNode<S>> list, SymbolicRegexNodeKind listKind) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(AppendToList, concat, list, listKind); return; } SymbolicRegexNode<S> node = concat; while (node._kind == listKind) { Debug.Assert(node._left is not null && node._right is not null); if (node._left._kind == listKind) { AppendToList(node._left, list, listKind); } else { list.Add(node._left); } node = node._right; } list.Add(node); } } /// <summary> /// Relative nullability that takes into account the immediate character context /// in order to resolve nullability of anchors /// </summary> /// <param name="context">kind info for previous and next characters</param> internal bool IsNullableFor(uint context) { // if _nullabilityCache is null then IsNullable==CanBeNullable // Observe that if IsNullable==true then CanBeNullable==true. // but when the node does not start with an anchor // and IsNullable==false then CanBeNullable==false. return _nullabilityCache is null ? _info.IsNullable : WithCache(context); // Separated out to enable the common case (no nullability cache) to be inlined // and to avoid zero-init costs for generally unused state. bool WithCache(uint context) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(IsNullableFor, context); } Debug.Assert(context < CharKind.ContextLimit); // If nullablity has been computed for the given context then return it byte b = Volatile.Read(ref _nullabilityCache[context]); if (b != UndefinedByte) { return b == TrueByte; } // Otherwise compute the nullability recursively for the given context bool is_nullable; switch (_kind) { case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); is_nullable = _lower == 0 || _left.IsNullableFor(context); break; case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); is_nullable = _left.IsNullableFor(context) && _right.IsNullableFor(context); break; case SymbolicRegexNodeKind.Or: case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); is_nullable = _alts.IsNullableFor(context); break; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); is_nullable = _left.IsNullableFor(context) || _right.IsNullableFor(context); break; case SymbolicRegexNodeKind.Not: Debug.Assert(_left is not null); is_nullable = !_left.IsNullableFor(context); break; case SymbolicRegexNodeKind.BeginningAnchor: is_nullable = CharKind.Prev(context) == CharKind.BeginningEnd; break; case SymbolicRegexNodeKind.EndAnchor: is_nullable = CharKind.Next(context) == CharKind.BeginningEnd; break; case SymbolicRegexNodeKind.BOLAnchor: // Beg-Of-Line anchor is nullable when the previous character is Newline or Start // note: at least one of the bits must be 1, but both could also be 1 in case of very first newline is_nullable = (CharKind.Prev(context) & CharKind.NewLineS) != 0; break; case SymbolicRegexNodeKind.EOLAnchor: // End-Of-Line anchor is nullable when the next character is Newline or Stop // note: at least one of the bits must be 1, but both could also be 1 in case of \Z is_nullable = (CharKind.Next(context) & CharKind.NewLineS) != 0; break; case SymbolicRegexNodeKind.BoundaryAnchor: // test that prev char is word letter iff next is not not word letter is_nullable = ((CharKind.Prev(context) & CharKind.WordLetter) ^ (CharKind.Next(context) & CharKind.WordLetter)) != 0; break; case SymbolicRegexNodeKind.NonBoundaryAnchor: // test that prev char is word letter iff next is word letter is_nullable = ((CharKind.Prev(context) & CharKind.WordLetter) ^ (CharKind.Next(context) & CharKind.WordLetter)) == 0; break; case SymbolicRegexNodeKind.EndAnchorZ: // \Z anchor is nullable when the next character is either the last Newline or Stop // note: CharKind.NewLineS == CharKind.Newline|CharKind.StartStop is_nullable = (CharKind.Next(context) & CharKind.BeginningEnd) != 0; break; case SymbolicRegexNodeKind.CaptureStart: case SymbolicRegexNodeKind.CaptureEnd: is_nullable = true; break; case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(_left is not null); is_nullable = _left.IsNullableFor(context); break; default: // SymbolicRegexNodeKind.EndAnchorZReverse: // EndAnchorZRev (rev(\Z)) anchor is nullable when the prev character is either the first Newline or Start // note: CharKind.NewLineS == CharKind.Newline|CharKind.StartStop Debug.Assert(_kind == SymbolicRegexNodeKind.EndAnchorZReverse); is_nullable = (CharKind.Prev(context) & CharKind.BeginningEnd) != 0; break; } Volatile.Write(ref _nullabilityCache[context], is_nullable ? TrueByte : FalseByte); return is_nullable; } } /// <summary>Returns true if this is equivalent to .* (the node must be eager also)</summary> public bool IsAnyStar { get { if (IsStar) { Debug.Assert(_left is not null); if (_left._kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(_left._set is not null); return !IsLazy && _builder._solver.True.Equals(_left._set); } } return false; } } /// <summary>Returns true if this is equivalent to .+ (the node must be eager also)</summary> public bool IsAnyPlus { get { if (IsPlus) { Debug.Assert(_left is not null); if (_left._kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(_left._set is not null); return !IsLazy && _builder._solver.True.Equals(_left._set); } } return false; } } /// <summary>Returns true if this is equivalent to [\0-\xFFFF] </summary> public bool IsAnyChar { get { if (_kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(_set is not null); return _builder._solver.AreEquivalent(_builder._solver.True, _set); } return false; } } /// <summary>Returns true if this is equivalent to [0-[0]]</summary> public bool IsNothing { get { if (_kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(_set is not null); return !_builder._solver.IsSatisfiable(_set); } return false; } } /// <summary>Returns true iff this is a loop whose lower bound is 0 and upper bound is max</summary> public bool IsStar => _lower == 0 && _upper == int.MaxValue; /// <summary>Returns true if this is Epsilon</summary> public bool IsEpsilon => _kind == SymbolicRegexNodeKind.Epsilon; /// <summary>Gets the kind of the regex</summary> internal SymbolicRegexNodeKind Kind => _kind; /// <summary> /// Returns true iff this is a loop whose lower bound is 1 and upper bound is max /// </summary> public bool IsPlus => _lower == 1 && _upper == int.MaxValue; #region called only once, in the constructor of SymbolicRegexBuilder internal static SymbolicRegexNode<S> CreateFalse(SymbolicRegexBuilder<S> builder) => Create(builder, SymbolicRegexNodeKind.Singleton, null, null, -1, -1, builder._solver.False, null, SymbolicRegexInfo.Create()); internal static SymbolicRegexNode<S> CreateTrue(SymbolicRegexBuilder<S> builder) => Create(builder, SymbolicRegexNodeKind.Singleton, null, null, -1, -1, builder._solver.True, null, SymbolicRegexInfo.Create(containsSomeCharacter: true)); internal static SymbolicRegexNode<S> CreateFixedLengthMarker(SymbolicRegexBuilder<S> builder, int length) => Create(builder, SymbolicRegexNodeKind.FixedLengthMarker, null, null, length, -1, default, null, SymbolicRegexInfo.Create(isAlwaysNullable: true)); internal static SymbolicRegexNode<S> CreateEpsilon(SymbolicRegexBuilder<S> builder) => Create(builder, SymbolicRegexNodeKind.Epsilon, null, null, -1, -1, default, null, SymbolicRegexInfo.Create(isAlwaysNullable: true)); internal static SymbolicRegexNode<S> CreateEagerEmptyLoop(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> body) => Create(builder, SymbolicRegexNodeKind.Loop, body, null, 0, 0, default, null, SymbolicRegexInfo.Create(isAlwaysNullable: true, isLazy: false)); internal static SymbolicRegexNode<S> CreateBeginEndAnchor(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind) { Debug.Assert(kind is SymbolicRegexNodeKind.BeginningAnchor or SymbolicRegexNodeKind.EndAnchor or SymbolicRegexNodeKind.EndAnchorZ or SymbolicRegexNodeKind.EndAnchorZReverse or SymbolicRegexNodeKind.EOLAnchor or SymbolicRegexNodeKind.BOLAnchor); return Create(builder, kind, null, null, -1, -1, default, null, SymbolicRegexInfo.Create(startsWithLineAnchor: true, canBeNullable: true)); } internal static SymbolicRegexNode<S> CreateBoundaryAnchor(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind) { Debug.Assert(kind is SymbolicRegexNodeKind.BoundaryAnchor or SymbolicRegexNodeKind.NonBoundaryAnchor); return Create(builder, kind, null, null, -1, -1, default, null, SymbolicRegexInfo.Create(startsWithBoundaryAnchor: true, canBeNullable: true)); } #endregion internal static SymbolicRegexNode<S> CreateSingleton(SymbolicRegexBuilder<S> builder, S set) => Create(builder, SymbolicRegexNodeKind.Singleton, null, null, -1, -1, set, null, SymbolicRegexInfo.Create(containsSomeCharacter: !set.Equals(builder._solver.False))); internal static SymbolicRegexNode<S> CreateLoop(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> body, int lower, int upper, bool isLazy) { Debug.Assert(lower >= 0 && lower <= upper); return Create(builder, SymbolicRegexNodeKind.Loop, body, null, lower, upper, default, null, SymbolicRegexInfo.Loop(body._info, lower, isLazy)); } internal static SymbolicRegexNode<S> Or(SymbolicRegexBuilder<S> builder, params SymbolicRegexNode<S>[] disjuncts) => CreateCollection(builder, SymbolicRegexNodeKind.Or, SymbolicRegexSet<S>.CreateMulti(builder, disjuncts, SymbolicRegexNodeKind.Or), SymbolicRegexInfo.Or(GetInfos(disjuncts))); internal static SymbolicRegexNode<S> Or(SymbolicRegexBuilder<S> builder, SymbolicRegexSet<S> disjuncts) { Debug.Assert(disjuncts._kind == SymbolicRegexNodeKind.Or || disjuncts.IsEverything); return CreateCollection(builder, SymbolicRegexNodeKind.Or, disjuncts, SymbolicRegexInfo.Or(GetInfos(disjuncts))); } internal static SymbolicRegexNode<S> And(SymbolicRegexBuilder<S> builder, params SymbolicRegexNode<S>[] conjuncts) => CreateCollection(builder, SymbolicRegexNodeKind.And, SymbolicRegexSet<S>.CreateMulti(builder, conjuncts, SymbolicRegexNodeKind.And), SymbolicRegexInfo.And(GetInfos(conjuncts))); internal static SymbolicRegexNode<S> And(SymbolicRegexBuilder<S> builder, SymbolicRegexSet<S> conjuncts) { Debug.Assert(conjuncts.IsNothing || conjuncts._kind == SymbolicRegexNodeKind.And); return CreateCollection(builder, SymbolicRegexNodeKind.And, conjuncts, SymbolicRegexInfo.And(GetInfos(conjuncts))); } internal static SymbolicRegexNode<S> CreateCaptureStart(SymbolicRegexBuilder<S> builder, int captureNum) => Create(builder, SymbolicRegexNodeKind.CaptureStart, null, null, captureNum, -1, default, null, SymbolicRegexInfo.Create(isAlwaysNullable: true)); internal static SymbolicRegexNode<S> CreateCaptureEnd(SymbolicRegexBuilder<S> builder, int captureNum) => Create(builder, SymbolicRegexNodeKind.CaptureEnd, null, null, captureNum, -1, default, null, SymbolicRegexInfo.Create(isAlwaysNullable: true)); internal static SymbolicRegexNode<S> CreateDisableBacktrackingSimulation(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> child) => Create(builder, SymbolicRegexNodeKind.DisableBacktrackingSimulation, child, null, -1, -1, default, null, child._info); private static SymbolicRegexNode<S> CreateCollection(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind, SymbolicRegexSet<S> alts, SymbolicRegexInfo info) => alts.IsNothing ? builder._nothing : alts.IsEverything ? builder._anyStar : alts.IsSingleton ? alts.GetSingletonElement() : Create(builder, kind, null, null, -1, -1, default, alts, info); private static SymbolicRegexInfo[] GetInfos(SymbolicRegexNode<S>[] nodes) { var infos = new SymbolicRegexInfo[nodes.Length]; for (int i = 0; i < nodes.Length; i++) { infos[i] = nodes[i]._info; } return infos; } private static SymbolicRegexInfo[] GetInfos(SymbolicRegexSet<S> nodes) { var infos = new SymbolicRegexInfo[nodes.Count]; int i = 0; foreach (SymbolicRegexNode<S> node in nodes) { Debug.Assert(i < nodes.Count); infos[i++] = node._info; } Debug.Assert(i == nodes.Count); return infos; } /// <summary>Make a concatenation of the supplied regex nodes.</summary> internal static SymbolicRegexNode<S> CreateConcat(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> left, SymbolicRegexNode<S> right) { // Concatenating anything with a nothing means the entire concatenation can't match if (left == builder._nothing || right == builder._nothing) return builder._nothing; // If the left or right is empty, just return the other. if (left.IsEpsilon) return right; if (right.IsEpsilon) return left; // If the left isn't a concatenation, then proceed to concatenation the left with the right. if (left._kind != SymbolicRegexNodeKind.Concat) { return Create(builder, SymbolicRegexNodeKind.Concat, left, right, -1, -1, default, null, SymbolicRegexInfo.Concat(left._info, right._info)); } // The left is a concatenation. We want to flatten it out and maintain a right-associative form. SymbolicRegexNode<S> concat = right; List<SymbolicRegexNode<S>> leftNodes = left.ToList(); for (int i = leftNodes.Count - 1; i >= 0; i--) { concat = Create(builder, SymbolicRegexNodeKind.Concat, leftNodes[i], concat, -1, -1, default, null, SymbolicRegexInfo.Concat(leftNodes[i]._info, concat._info)); } return concat; } /// <summary> /// Make an ordered or of given regexes, eliminate nothing regexes and treat .* as consuming element. /// Keep the or flat, assuming both right and left are flat. /// Apply a counber subsumption/combining optimization, such that e.g. a{2,5}|a{3,10} will be combined to a{2,10}. /// </summary> internal static SymbolicRegexNode<S> OrderedOr(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> left, SymbolicRegexNode<S> right, bool deduplicated = false) { if (left.IsAnyStar || right == builder._nothing || left == right) return left; if (left == builder._nothing) return right; // If left is not an Or, try to avoid allocation by checking if deduplication is necessary if (!deduplicated && left._kind != SymbolicRegexNodeKind.OrderedOr) { SymbolicRegexNode<S> current = right; // Initially assume there are no duplicates deduplicated = true; while (current._kind == SymbolicRegexNodeKind.OrderedOr) { Debug.Assert(current._left is not null && current._right is not null); // All Ors are supposed to be in a right associative normal form Debug.Assert(current._left._kind != SymbolicRegexNodeKind.OrderedOr); if (current._left == left) { // Duplicate found, mark that and exit early deduplicated = false; break; } current = current._right; } // If the loop above got to the end, current is the last element. Check that too if (deduplicated) deduplicated = (current != left); } if (!deduplicated || left._kind == SymbolicRegexNodeKind.OrderedOr) { // If the left side was an or, then it has to be flattened, gather the elements from both sides List<SymbolicRegexNode<S>> elems = left.ToList(listKind: SymbolicRegexNodeKind.OrderedOr); int firstRightElem = elems.Count; right.ToList(elems, listKind: SymbolicRegexNodeKind.OrderedOr); // Eliminate any duplicate elements, keeping the leftmost element HashSet<SymbolicRegexNode<S>> seenElems = new(); // Keep track of if any elements from the right side need to be eliminated bool rightChanged = false; for (int i = 0; i < elems.Count; i++) { if (!seenElems.Contains(elems[i])) { seenElems.Add(elems[i]); } else { // Nothing will be eliminated in the next step elems[i] = builder._nothing; rightChanged |= i >= firstRightElem; } } // Build the flattened or, avoiding rebuilding the right side if possible if (rightChanged) { SymbolicRegexNode<S> or = builder._nothing; for (int i = elems.Count - 1; i >= 0; i--) { or = OrderedOr(builder, elems[i], or, deduplicated: true); } return or; } else { SymbolicRegexNode<S> or = right; for (int i = firstRightElem - 1; i >= 0; i--) { or = OrderedOr(builder, elems[i], or, deduplicated: true); } return or; } } Debug.Assert(left._kind != SymbolicRegexNodeKind.OrderedOr); Debug.Assert(deduplicated); // Apply the counter subsumption/combining optimization if possible (SymbolicRegexNode<S> loop, SymbolicRegexNode<S> rest) = left.FirstCounterInfo(); if (loop != builder._nothing) { Debug.Assert(loop._kind == SymbolicRegexNodeKind.Loop && loop._left is not null); (SymbolicRegexNode<S> otherLoop, SymbolicRegexNode<S> otherRest) = right.FirstCounterInfo(); if (otherLoop != builder._nothing && rest == otherRest) { // Found two adjacent counters with the same continuation, check that the loops are equivalent apart from bounds // and that the bounds form a contiguous interval. Two integer intervals [x1,x2] and [y1,y2] overlap when // x1 <= y2 and y1 <= x2. The union of intervals that just touch is still contiguous, e.g. [2,5] and [6,10] make // [2,10], so the lower bounds are decremented by 1 in the check. Debug.Assert(otherLoop._kind == SymbolicRegexNodeKind.Loop && otherLoop._left is not null); if (loop._left == otherLoop._left && loop.IsLazy == otherLoop.IsLazy && loop._lower - 1 <= otherLoop._upper && otherLoop._lower - 1 <= loop._upper) { // Loops are equivalent apart from bounds, and the union of the bounds is a contiguous interval // Build a new counter for the union of the ranges SymbolicRegexNode<S> newCounter = CreateConcat(builder, CreateLoop(builder, loop._left, Math.Min(loop._lower, otherLoop._lower), Math.Max(loop._upper, otherLoop._upper), loop.IsLazy), rest); if (right._kind == SymbolicRegexNodeKind.OrderedOr) { // The right counter came from an or, so include the rest of that or Debug.Assert(right._right is not null); return OrderedOr(builder, newCounter, right._right, deduplicated: true); } else { return newCounter; } } } } // Counter optimization did not apply, just build the or return Create(builder, SymbolicRegexNodeKind.OrderedOr, left, right, -1, -1, default, null, SymbolicRegexInfo.Or(left._info, right._info)); } /// <summary> /// Extract a counter as a loop followed by its continuation. For example, a*b returns (a*,b). /// Also look into the first element of an or, so a+|xyz returns (a+,()). /// If no counter is found returns ([],[]). /// </summary> /// <returns>a tuple of the loop and its continuation</returns> private (SymbolicRegexNode<S>, SymbolicRegexNode<S>) FirstCounterInfo() { if (_kind == SymbolicRegexNodeKind.Loop) return (this, _builder.Epsilon); if (_kind == SymbolicRegexNodeKind.Concat) { Debug.Assert(_left is not null && _right is not null); if (_left.Kind == SymbolicRegexNodeKind.Loop) return (_left, _right); } if (_kind == SymbolicRegexNodeKind.OrderedOr) { Debug.Assert(_left is not null); return _left.FirstCounterInfo(); } return (_builder._nothing, _builder._nothing); } internal static SymbolicRegexNode<S> Not(SymbolicRegexBuilder<S> builder, SymbolicRegexNode<S> root) { // Instead of just creating a negated root node // Convert ~root to Negation Normal Form (NNF) by using deMorgan's laws and push ~ to the leaves // This may avoid rather large overhead (such case was discovered with unit test PasswordSearchDual) // Do this transformation in-line without recursion, to avoid any chance of deep recursion // OBSERVE: NNF[node] represents the Negation Normal Form of ~node Dictionary<SymbolicRegexNode<S>, SymbolicRegexNode<S>> NNF = new(); Stack<(SymbolicRegexNode<S>, bool)> todo = new(); todo.Push((root, false)); while (todo.Count > 0) { (SymbolicRegexNode<S>, bool) top = todo.Pop(); bool secondTimePushed = top.Item2; SymbolicRegexNode<S> node = top.Item1; if (secondTimePushed) { Debug.Assert((node._kind == SymbolicRegexNodeKind.Or || node._kind == SymbolicRegexNodeKind.And) && node._alts is not null); // Here all members of _alts have been processed List<SymbolicRegexNode<S>> alts_nnf = new(); foreach (SymbolicRegexNode<S> elem in node._alts) { alts_nnf.Add(NNF[elem]); } // Using deMorgan's laws, flip the kind: Or becomes And, And becomes Or SymbolicRegexNode<S> node_nnf = node._kind == SymbolicRegexNodeKind.Or ? And(builder, alts_nnf.ToArray()) : Or(builder, alts_nnf.ToArray()); NNF[node] = node_nnf; } else { switch (node._kind) { case SymbolicRegexNodeKind.Not: Debug.Assert(node._left is not null); // Here we assume that top._left is already in NNF, double negation is cancelled out NNF[node] = node._left; break; case SymbolicRegexNodeKind.Or or SymbolicRegexNodeKind.And: Debug.Assert(node._alts is not null); // Push the node for the second time todo.Push((node, true)); // Compute the negation normal form of all the members // Their computation is actually the same independent from being inside an 'Or' or 'And' node foreach (SymbolicRegexNode<S> elem in node._alts) { todo.Push((elem, false)); } break; case SymbolicRegexNodeKind.Epsilon: // ~() = .+ NNF[node] = SymbolicRegexNode<S>.CreateLoop(builder, builder._anyChar, 1, int.MaxValue, isLazy: false); break; case SymbolicRegexNodeKind.Singleton: Debug.Assert(node._set is not null); // ~[] = .* if (node.IsNothing) { NNF[node] = builder._anyStar; break; } goto default; case SymbolicRegexNodeKind.Loop: Debug.Assert(node._left is not null); // ~(.*) = [] and ~(.+) = () if (node.IsAnyStar) { NNF[node] = builder._nothing; break; } else if (node.IsPlus && node._left.IsAnyChar) { NNF[node] = builder.Epsilon; break; } goto default; default: // In all other cases construct the complement NNF[node] = Create(builder, SymbolicRegexNodeKind.Not, node, null, -1, -1, default, null, SymbolicRegexInfo.Not(node._info)); break; } } } return NNF[root]; } /// <summary> /// Returns the fixed matching length of the regex or -1 if the regex does not have a fixed matching length. /// </summary> public int GetFixedLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume no fixed length. return -1; } switch (_kind) { case SymbolicRegexNodeKind.FixedLengthMarker: case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.BOLAnchor: case SymbolicRegexNodeKind.EOLAnchor: case SymbolicRegexNodeKind.EndAnchor: case SymbolicRegexNodeKind.BeginningAnchor: case SymbolicRegexNodeKind.EndAnchorZ: case SymbolicRegexNodeKind.EndAnchorZReverse: case SymbolicRegexNodeKind.BoundaryAnchor: case SymbolicRegexNodeKind.NonBoundaryAnchor: case SymbolicRegexNodeKind.CaptureStart: case SymbolicRegexNodeKind.CaptureEnd: return 0; case SymbolicRegexNodeKind.Singleton: return 1; case SymbolicRegexNodeKind.Loop: { Debug.Assert(_left is not null); if (_lower == _upper) { long length = _left.GetFixedLength(); if (length >= 0) { length *= _lower; if (length <= int.MaxValue) { return (int)length; } } } break; } case SymbolicRegexNodeKind.Concat: { Debug.Assert(_left is not null && _right is not null); int leftLength = _left.GetFixedLength(); if (leftLength >= 0) { int rightLength = _right.GetFixedLength(); if (rightLength >= 0) { long length = (long)leftLength + rightLength; if (length <= int.MaxValue) { return (int)length; } } } break; } case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); return _alts.GetFixedLength(); case SymbolicRegexNodeKind.OrderedOr: { Debug.Assert(_left is not null && _right is not null); int length = _left.GetFixedLength(); if (length >= 0) { if (_right.GetFixedLength() == length) { return length; } } break; } case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(_left is not null); return _left.GetFixedLength(); } return -1; } #if DEBUG private TransitionRegex<S>? _transitionRegex; /// <summary> /// Computes the symbolic derivative as a transition regex. /// Transitions are in the tree left to right in the order the backtracking engine would explore them. /// </summary> internal TransitionRegex<S> CreateDerivative() { if (_transitionRegex is not null) { return _transitionRegex; } if (IsNothing || IsEpsilon) { _transitionRegex = TransitionRegex<S>.Leaf(_builder._nothing); return _transitionRegex; } if (IsAnyStar || IsAnyPlus) { _transitionRegex = TransitionRegex<S>.Leaf(_builder._anyStar); return _transitionRegex; } if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(CreateDerivative); } switch (_kind) { case SymbolicRegexNodeKind.Singleton: Debug.Assert(_set is not null); _transitionRegex = TransitionRegex<S>.Conditional(_set, TransitionRegex<S>.Leaf(_builder.Epsilon), TransitionRegex<S>.Leaf(_builder._nothing)); break; case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); TransitionRegex<S> mainTransition = _left.CreateDerivative().Concat(_right); if (!_left.CanBeNullable) { // If _left is never nullable _transitionRegex = mainTransition; } else if (_left.IsNullable) { // If _left is unconditionally nullable _transitionRegex = TransitionRegex<S>.Union(mainTransition, _right.CreateDerivative()); } else { // The left side contains anchors and can be nullable in some context // Extract the nullability as the lookaround condition SymbolicRegexNode<S> leftNullabilityTest = _left.ExtractNullabilityTest(); _transitionRegex = TransitionRegex<S>.Lookaround(leftNullabilityTest, TransitionRegex<S>.Union(mainTransition, _right.CreateDerivative()), mainTransition); } break; case SymbolicRegexNodeKind.Loop: // d(R*) = d(R+) = d(R)R* Debug.Assert(_left is not null); Debug.Assert(_upper > 0); TransitionRegex<S> step = _left.CreateDerivative(); if (IsStar || IsPlus) { _transitionRegex = step.Concat(_builder.CreateLoop(_left, IsLazy)); } else { int newupper = _upper == int.MaxValue ? int.MaxValue : _upper - 1; int newlower = _lower == 0 ? 0 : _lower - 1; SymbolicRegexNode<S> rest = _builder.CreateLoop(_left, IsLazy, newlower, newupper); _transitionRegex = step.Concat(rest); } break; case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); _transitionRegex = TransitionRegex<S>.Leaf(_builder._nothing); foreach (SymbolicRegexNode<S> elem in _alts) { _transitionRegex = TransitionRegex<S>.Union(_transitionRegex, elem.CreateDerivative()); } break; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); _transitionRegex = TransitionRegex<S>.Union(_left.CreateDerivative(), _right.CreateDerivative()); break; case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(_left is not null); // The derivative to TransitionRegex does not support backtracking simulation, so ignore this node _transitionRegex = _left.CreateDerivative(); break; case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); _transitionRegex = TransitionRegex<S>.Leaf(_builder._anyStar); foreach (SymbolicRegexNode<S> elem in _alts) { _transitionRegex = TransitionRegex<S>.Intersect(_transitionRegex, elem.CreateDerivative()); } break; case SymbolicRegexNodeKind.Not: Debug.Assert(_left is not null); _transitionRegex = _left.CreateDerivative().Complement(); break; default: _transitionRegex = TransitionRegex<S>.Leaf(_builder._nothing); break; } return _transitionRegex; } #endif /// <summary> /// Takes the derivative of the symbolic regex for the given element, which must be either /// a minterm (i.e. a class of characters that have identical behavior for all predicates in the pattern) /// or a singleton set. This derivative simulates backtracking, i.e. it only considers paths that backtracking would /// take before accepting the empty string for this pattern and returns the pattern ordered in the order backtracking /// would explore paths. For example the derivative of a*ab for a is a*ab|b, while for a*?ab it is b|a*?ab. /// </summary> /// <param name="elem">given element wrt which the derivative is taken</param> /// <param name="context">immediately surrounding character context that affects nullability of anchors</param> /// <returns>the derivative</returns> internal SymbolicRegexNode<S> CreateDerivative(S elem, uint context) { List<(SymbolicRegexNode<S> Node, DerivativeEffect[])> transitions = new(); if (_kind == SymbolicRegexNodeKind.DisableBacktrackingSimulation) { // Since this node disables backtracking simulation, unwrap the node and pass the corresponding flag as // false to AddTransitions. Debug.Assert(_left is not null); _left.AddTransitions(elem, context, transitions, new List<SymbolicRegexNode<S>>(), null, simulateBacktracking: false); } else { AddTransitions(elem, context, transitions, new List<SymbolicRegexNode<S>>(), null, simulateBacktracking: true); } SymbolicRegexNode<S> derivative = _builder._nothing; // Iterate backwards to avoid quadratic rebuilding of the Or nodes, which are always simplified to // right associative form. Concretely: // In (a|(b|c)) | d -> (a|(b|(c|d)) the first argument is not a subtree of the result. // In a | (b|(c|d)) -> (a|(b|(c|d)) the second argument is a subtree of the result. // The first case performs linear work for each element, leading to a quadratic blowup. for (int i = transitions.Count - 1; i >= 0; --i) { SymbolicRegexNode<S> node = transitions[i].Node; Debug.Assert(node._kind != SymbolicRegexNodeKind.DisableBacktrackingSimulation); derivative = _builder.OrderedOr(node, derivative); } if (_kind == SymbolicRegexNodeKind.DisableBacktrackingSimulation) // Make future derivatives disable backtracking simulation too derivative = _builder.CreateDisableBacktrackingSimulation(derivative); return derivative; } /// <summary> /// Takes the derivative of the symbolic regex for the given element, which must be either /// a minterm (i.e. a class of characters that have identical behavior for all predicates in the pattern) /// or a singleton set. This derivative simulates backtracking, i.e. it only considers paths that backtracking would /// take before accepting the empty string for this pattern and returns the pattern ordered in the order backtracking /// would explore paths. For example the derivative of a*ab places a*ab before b, while for a*?ab the order is reversed. /// </summary> /// <remarks> /// The differences of this to <see cref="CreateDerivative(S,uint)"/> are that (1) effects (e.g. capture starts and ends) /// are considered and (2) the different elements that would form a top level union are instead returned as separate /// nodes (paired with their associated effects). This function is meant to be used for NFA simulation, where top level /// unions would be broken up into separate states anyway, so nodes are not combined even if they have the same effects. /// </remarks> /// <param name="elem">given element wrt which the derivative is taken</param> /// <param name="context">immediately surrounding character context that affects nullability of anchors</param> /// <returns>the derivative</returns> internal List<(SymbolicRegexNode<S>, DerivativeEffect[])> CreateNfaDerivativeWithEffects(S elem, uint context) { List<(SymbolicRegexNode<S>, DerivativeEffect[])> transitions = new(); if (_kind == SymbolicRegexNodeKind.DisableBacktrackingSimulation) { // Since this node disables backtracking simulation, unwrap the node and pass the corresponding flag as // false to AddTransitions. Debug.Assert(_left is not null); _left.AddTransitions(elem, context, transitions, new List<SymbolicRegexNode<S>>(), new Stack<DerivativeEffect>(), simulateBacktracking: false); // Make future derivatives disable backtracking simulation too for (int i = 0; i < transitions.Count; ++i) { var (node, effects) = transitions[i]; Debug.Assert(node._kind != SymbolicRegexNodeKind.DisableBacktrackingSimulation); transitions[i] = (_builder.CreateDisableBacktrackingSimulation(node), effects); } } else { AddTransitions(elem, context, transitions, new List<SymbolicRegexNode<S>>(), new Stack<DerivativeEffect>(), simulateBacktracking: true); } return transitions; } /// <summary> /// Base function used to implement derivative functions. Given an element and a context this will add all patterns /// whose union makes up the derivative to the given <paramref name="transitions"/> list. If the <paramref name="effects"/> /// stack is null, then effects are not tracked and all effects arrays in the result will be null. Transitions are added /// in an order that is consistent with backtracking. /// </summary> /// <param name="elem">given element wrt which the derivative is taken</param> /// <param name="context">immediately surrounding character context that affects nullability of anchors</param> /// <param name="transitions">a list to add transitions to</param> /// <param name="continuation">a list used in recursive calls to track nodes to concatenate, should be an empty list at the root call</param> /// <param name="effects">a stack used in recursive calls to track effects, should be an empty stack at the root call</param> /// <param name="simulateBacktracking">whether the derivative should only consider paths that backtracking would take, true by default</param> private void AddTransitions(S elem, uint context, List<(SymbolicRegexNode<S>, DerivativeEffect[])> transitions, List<SymbolicRegexNode<S>> continuation, Stack<DerivativeEffect>? effects, bool simulateBacktracking) { // Helper function for concatenating a head node and a list of continuation nodes. The continuation nodes // are added in reverse order and the function below uses the list as a stack, so the nodes added to the // stack first end up at the tail of the concatenation. static SymbolicRegexNode<S> BuildLeaf(SymbolicRegexNode<S> head, List<SymbolicRegexNode<S>> continuation) { SymbolicRegexNode<S> leaf = head._builder.Epsilon; for (int i = 0; i < continuation.Count; ++i) { leaf = head._builder.CreateConcat(continuation[i], leaf); } return head._builder.CreateConcat(head, leaf); } // Helper function for detecting when an unconditionally nullable pattern is in the transitions and no // more transitions need to be considered. If the derivative simulates backtracking, then in the next // step nothing after an unconditionally nullable state would be considered. // For example, d_a( a|ab ) under backtracking simulation transitions to just epsilon, while without // backtracking simulation it would transition to epsilon|b. // All parts of the function below should consider IsDone and return early when it is true. static bool IsDone(List<(SymbolicRegexNode<S> Node, DerivativeEffect[])> transitions, bool simulateBacktracking) => simulateBacktracking && transitions.Count > 0 && transitions[transitions.Count - 1].Node.IsNullable; // Nothing and epsilon can't consume a character so they generate no transition if (IsNothing || IsEpsilon) { return; } // For both .* and .+ the derivative is .* for any character if (IsAnyStar || IsAnyPlus) { Debug.Assert(!IsDone(transitions, simulateBacktracking)); SymbolicRegexNode<S> leaf = BuildLeaf(_builder._anyStar, continuation); transitions.Add((leaf, effects?.ToArray() ?? Array.Empty<DerivativeEffect>())); // Signal early exit if the leaf is unconditionally nullable return; } if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(AddTransitions, elem, context, transitions, continuation, effects, simulateBacktracking); return; } switch (_kind) { case SymbolicRegexNodeKind.Singleton: Debug.Assert(!IsDone(transitions, simulateBacktracking)); Debug.Assert(_set is not null); // The following check assumes that either (1) the element and predicate are minterms, in which case // the element is exactly the predicate if the intersection is satisfiable, or (2) the element is a singleton // set in which case it is fully contained in the predicate if the intersection is satisfiable. if (_builder._solver.IsSatisfiable(_builder._solver.And(elem, _set))) { SymbolicRegexNode<S> leaf = BuildLeaf(_builder.Epsilon, continuation); transitions.Add((leaf, effects?.ToArray() ?? Array.Empty<DerivativeEffect>())); // Signal early exit if the leaf is unconditionally nullable return; } break; case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); if (!_left.IsNullableFor(context)) { // If the left side can't be nullable then the character must be consumed there. // For example, d(ab) = d(a)b. continuation.Add(_right); _left.AddTransitions(elem, context, transitions, continuation, effects, simulateBacktracking); continuation.RemoveAt(continuation.Count - 1); } else if (_left._kind == SymbolicRegexNodeKind.OrderedOr) { Debug.Assert(_left._left is not null && _left._right is not null); // The case of a concatenation with an alternation on the left side, i.e. (R|T)S, is handled // separately by applying the rewrite to push the concatenation in, i.e. (R|T)S -> RS|TS. // This is done to support the rule for concatenations with a lazy loop on the left side, // i.e. R{m,n}?T, which have to be handled as part of the concatenation case to properly order // the paths in a way that matches the backtracking engines preference. By pushing the // concatenation into the alternation any loops inside the alternation are guaranteed to show up // directly on the left side of a concatenation. // This pattern is for the path where the backtracking matcher would find the match from the first alternative SymbolicRegexNode<S> leftLeftPath = _builder.CreateConcat(_left._left, _right); // The backtracking-simulating derivative of the left path will be used when the pattern is nullable, // i.e. the backtracking matcher would end the match rather than go onto paths in the second // alternative. When the path through the first alternative is not nullable or the derivative is not // backtracking-simulating, then all paths through it are considered. bool leftLeftSimulateBacktracking = simulateBacktracking && leftLeftPath.IsNullableFor(context); leftLeftPath.AddTransitions(elem, context, transitions, continuation, effects, leftLeftSimulateBacktracking); // Include the path through the right side only if the left side is not nullable or the derivative // is not simulating backtracking. // For example, d( (a|b)c* ) = d(ac) | d(bc), while on the other hand d( (a?|b)c* ) = d(a?c*). // In the latter case the second alternative is omitted because the backtracking matcher would rather // accept an empty string for a?c* than anything for bc*. if (!IsDone(transitions, simulateBacktracking) && !leftLeftSimulateBacktracking) _builder.CreateConcat(_left._right, _right).AddTransitions(elem, context, transitions, continuation, effects, simulateBacktracking); } else { // Helper function for the case where the right side consumes the character static void RightTransition(SymbolicRegexNode<S> node, S elem, uint context, List<(SymbolicRegexNode<S>, DerivativeEffect[])> transitions, List<SymbolicRegexNode<S>> continuation, Stack<DerivativeEffect>? effects, bool simulateBacktracking) { Debug.Assert(node._left is not null && node._right is not null); // Remember current number of effects so that we know how many to pop int oldEffectsCount = effects?.Count ?? 0; if (effects is not null) { // Push all effects onto the effects stack node._left.ApplyEffects((effect, stack) => stack.Push(effect), context, effects); } node._right.AddTransitions(elem, context, transitions, continuation, effects, simulateBacktracking); if (effects is not null) { // Pop all effects that were added here while (effects.Count > oldEffectsCount) effects.Pop(); } } // Helper function for the case where the left side consumes the character static void LeftTransition(SymbolicRegexNode<S> node, S elem, uint context, List<(SymbolicRegexNode<S>, DerivativeEffect[])> transitions, List<SymbolicRegexNode<S>> continuation, Stack<DerivativeEffect>? effects, bool simulateBacktracking) { Debug.Assert(node._left is not null && node._right is not null); continuation.Add(node._right); // Disable backtracking simulation for the left side if the right side is not nullable here. // The intuition is that if the right side is not nullable, then backtracking would not accept the empty // string here even when it hits a nullable path for the left side, so all paths through the left side // need to be considered. bool leftSimulateBacktracking = simulateBacktracking && node._right.IsNullableFor(context); node._left.AddTransitions(elem, context, transitions, continuation, effects, leftSimulateBacktracking); continuation.RemoveAt(continuation.Count - 1); } // Order the transitions. If the left side is a lazy loop that is nullable due to its lower bound then prefer the right side. // This is done to match the order that backtracking engines would explore different alternatives, where for a lazy loop // matches that consume as few characters into the loop as possible are preferred. // For example, d(a*?b) = d(b) | d(a*?)b while without the lazy loop d(a*b) = d(a*)b | d(b). if (_left._kind == SymbolicRegexNodeKind.Loop && _left.IsLazy && _left._lower == 0) { RightTransition(this, elem, context, transitions, continuation, effects, simulateBacktracking); if (!IsDone(transitions, simulateBacktracking)) LeftTransition(this, elem, context, transitions, continuation, effects, simulateBacktracking); } else { LeftTransition(this, elem, context, transitions, continuation, effects, simulateBacktracking); if (!IsDone(transitions, simulateBacktracking)) RightTransition(this, elem, context, transitions, continuation, effects, simulateBacktracking); } } break; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); Debug.Assert(_upper > 0); // Add transitions only when the backtracking engines would prefer to enter the loop if (!simulateBacktracking || !IsLazy || _lower != 0) { // The loop derivative peels out one iteration and concatenates the body's derivative with the decremented loop, // so d(R{m,n}) = d(R)R{max(0,m-1),n-1}. Note that n is guaranteed to be greater than zero, since otherwise the // loop would have been simplified to nothing, and int.MaxValue is treated as infinity. int newupper = _upper == int.MaxValue ? int.MaxValue : _upper - 1; int newlower = _lower == 0 ? 0 : _lower - 1; SymbolicRegexNode<S> rest = _builder.CreateLoop(_left, IsLazy, newlower, newupper); continuation.Add(rest); _left.AddTransitions(elem, context, transitions, continuation, effects, simulateBacktracking); continuation.RemoveAt(continuation.Count - 1); } break; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); // The backtracking derivative for the first alternative will be used when it is nullable, i.e. the // backtracking matcher would end the match rather than go onto paths in the right side. When // the path through the left side is not nullable or the derivative doesn't simulate backtracking, // then all paths through it are considered. bool leftSimulateBacktracking = simulateBacktracking && _left.IsNullableFor(context); _left.AddTransitions(elem, context, transitions, continuation, effects, simulateBacktracking && _left.IsNullableFor(context)); // Include the path through the right side only if the left side is not nullable or the derivative // is not simulating backtracking. // For example, d(a|b) = d(a) | d(b) while d(a*|b) = d(a*). if (!IsDone(transitions, simulateBacktracking) && !leftSimulateBacktracking) _right.AddTransitions(elem, context, transitions, continuation, effects, simulateBacktracking); break; case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Fail($"{nameof(AddTransitions)}: DisableBacktrackingSimulation should have been handled outside this function."); break; case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); foreach (SymbolicRegexNode<S> alt in _alts) { alt.AddTransitions(elem, context, transitions, continuation, effects, simulateBacktracking); } break; case SymbolicRegexNodeKind.And: case SymbolicRegexNodeKind.Not: Debug.Fail($"{nameof(AddTransitions)}:{_kind}"); break; } } /// <summary> /// Find all effects under this node and supply them to the callback. /// </summary> /// <remarks> /// The construction follows the paths that the backtracking matcher would take. For example in ()|() only the /// effects for the first alternative will be included. /// </remarks> /// <param name="apply">action called for each effect</param> /// <param name="context">the current context to determine nullability</param> /// <param name="arg">an additional argument passed through to all callbacks</param> internal void ApplyEffects<TArg>(Action<DerivativeEffect, TArg> apply, uint context, TArg arg) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(ApplyEffects, apply, context, arg); return; } switch (_kind) { case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); Debug.Assert(_left.IsNullableFor(context) && _right.IsNullableFor(context)); _left.ApplyEffects(apply, context, arg); _right.ApplyEffects(apply, context, arg); break; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); // Apply effect when backtracking engine would enter loop if (_lower != 0 || (_upper != 0 && !IsLazy && _left.IsNullableFor(context))) { Debug.Assert(_left.IsNullableFor(context)); _left.ApplyEffects(apply, context, arg); } break; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); if (_left.IsNullableFor(context)) { // Prefer the left side _left.ApplyEffects(apply, context, arg); } else { // Otherwise right side must be nullable Debug.Assert(_right.IsNullableFor(context)); _right.ApplyEffects(apply, context, arg); } break; case SymbolicRegexNodeKind.CaptureStart: apply(new DerivativeEffect(DerivativeEffectKind.CaptureStart, _lower), arg); break; case SymbolicRegexNodeKind.CaptureEnd: apply(new DerivativeEffect(DerivativeEffectKind.CaptureEnd, _lower), arg); break; case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(_left is not null); _left.ApplyEffects(apply, context, arg); break; case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); foreach (SymbolicRegexNode<S> elem in _alts) { if (elem.IsNullableFor(context)) elem.ApplyEffects(apply, context, arg); } break; case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); foreach (SymbolicRegexNode<S> elem in _alts) { Debug.Assert(elem.IsNullableFor(context)); elem.ApplyEffects(apply, context, arg); } break; } } #if DEBUG /// <summary> /// Computes the closure of CreateDerivative, by exploring all the leaves /// of the transition regex until no more new leaves are found. /// Converts the resulting transition system into a symbolic NFA. /// If the exploration remains incomplete due to the given state bound /// being reached then the InComplete property of the constructed NFA is true. /// </summary> internal SymbolicNFA<S> Explore(int bound) => SymbolicNFA<S>.Explore(this, bound); /// <summary>Extracts the nullability test as a Boolean combination of anchors</summary> public SymbolicRegexNode<S> ExtractNullabilityTest() { if (IsNullable) { return _builder._anyStar; } if (!CanBeNullable) { return _builder._nothing; } if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(ExtractNullabilityTest); } switch (_kind) { case SymbolicRegexNodeKind.BeginningAnchor: case SymbolicRegexNodeKind.EndAnchor: case SymbolicRegexNodeKind.BOLAnchor: case SymbolicRegexNodeKind.EOLAnchor: case SymbolicRegexNodeKind.BoundaryAnchor: case SymbolicRegexNodeKind.NonBoundaryAnchor: case SymbolicRegexNodeKind.EndAnchorZ: case SymbolicRegexNodeKind.EndAnchorZReverse: return this; case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); return _builder.And(_left.ExtractNullabilityTest(), _right.ExtractNullabilityTest()); case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); SymbolicRegexNode<S> disjunction = _builder._nothing; foreach (SymbolicRegexNode<S> elem in _alts) { disjunction = _builder.Or(disjunction, elem.ExtractNullabilityTest()); } return disjunction; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); return _builder.OrderedOr(_left.ExtractNullabilityTest(), _right.ExtractNullabilityTest()); case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); SymbolicRegexNode<S> conjunction = _builder._anyStar; foreach (SymbolicRegexNode<S> elem in _alts) { conjunction = _builder.And(conjunction, elem.ExtractNullabilityTest()); } return conjunction; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); return _left.ExtractNullabilityTest(); default: // All remaining cases could not be nullable or were trivially nullable // Singleton cannot be nullable and Epsilon and FixedLengthMarker are trivially nullable Debug.Assert(_kind == SymbolicRegexNodeKind.Not && _left is not null); return _builder.Not(_left.ExtractNullabilityTest()); } } #endif public override int GetHashCode() { return _hashcode; } private int ComputeHashCode() { switch (_kind) { case SymbolicRegexNodeKind.EndAnchor: case SymbolicRegexNodeKind.BeginningAnchor: case SymbolicRegexNodeKind.BOLAnchor: case SymbolicRegexNodeKind.EOLAnchor: case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.BoundaryAnchor: case SymbolicRegexNodeKind.NonBoundaryAnchor: case SymbolicRegexNodeKind.EndAnchorZ: case SymbolicRegexNodeKind.EndAnchorZReverse: return HashCode.Combine(_kind, _info); case SymbolicRegexNodeKind.FixedLengthMarker: case SymbolicRegexNodeKind.CaptureStart: case SymbolicRegexNodeKind.CaptureEnd: return HashCode.Combine(_kind, _lower); case SymbolicRegexNodeKind.Loop: return HashCode.Combine(_kind, _left, _lower, _upper, _info); case SymbolicRegexNodeKind.Or or SymbolicRegexNodeKind.And: return HashCode.Combine(_kind, _alts, _info); case SymbolicRegexNodeKind.Concat: case SymbolicRegexNodeKind.OrderedOr: return HashCode.Combine(_left, _right, _info); case SymbolicRegexNodeKind.DisableBacktrackingSimulation: return HashCode.Combine(_left, _info); case SymbolicRegexNodeKind.Singleton: return HashCode.Combine(_kind, _set); default: Debug.Assert(_kind == SymbolicRegexNodeKind.Not); return HashCode.Combine(_kind, _left, _info); }; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is not SymbolicRegexNode<S> that) { return false; } if (this == that) { return true; } if (_kind != that._kind) { return false; } if (_kind == SymbolicRegexNodeKind.Or) { if (_isInternalizedUnion && that._isInternalizedUnion) { // Internalized nodes that are not identical are not equal return false; } // Check equality of the sets of regexes Debug.Assert(_alts is not null && that._alts is not null); if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(_alts.Equals, that._alts); } return _alts.Equals(that._alts); } return false; } private void ToStringForLoop(StringBuilder sb) { if (_kind == SymbolicRegexNodeKind.Singleton) { ToString(sb); } else { sb.Append('('); ToString(sb); sb.Append(')'); } } public override string ToString() { StringBuilder sb = new(); ToString(sb); return sb.ToString(); } internal void ToString(StringBuilder sb) { // Guard against stack overflow due to deep recursion if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(ToString, sb); return; } switch (_kind) { case SymbolicRegexNodeKind.EndAnchor: sb.Append("\\z"); return; case SymbolicRegexNodeKind.BeginningAnchor: sb.Append("\\A"); return; case SymbolicRegexNodeKind.BOLAnchor: sb.Append('^'); return; case SymbolicRegexNodeKind.EOLAnchor: sb.Append('$'); return; case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.FixedLengthMarker: return; case SymbolicRegexNodeKind.BoundaryAnchor: sb.Append("\\b"); return; case SymbolicRegexNodeKind.NonBoundaryAnchor: sb.Append("\\B"); return; case SymbolicRegexNodeKind.EndAnchorZ: sb.Append("\\Z"); return; case SymbolicRegexNodeKind.EndAnchorZReverse: sb.Append("\\a"); return; case SymbolicRegexNodeKind.Or: case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); _alts.ToString(sb); return; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); _left.ToString(sb); sb.Append('|'); _right.ToString(sb); return; case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); _left.ToString(sb); _right.ToString(sb); return; case SymbolicRegexNodeKind.Singleton: Debug.Assert(_set is not null); sb.Append(_builder._solver.PrettyPrint(_set)); return; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); if (IsAnyStar) { sb.Append(".*"); } else if (_lower == 0 && _upper == 1) { _left.ToStringForLoop(sb); sb.Append('?'); } else if (IsStar) { _left.ToStringForLoop(sb); sb.Append('*'); if (IsLazy) { sb.Append('?'); } } else if (IsPlus) { _left.ToStringForLoop(sb); sb.Append('+'); if (IsLazy) { sb.Append('?'); } } else if (_lower == 0 && _upper == 0) { sb.Append("()"); } else { _left.ToStringForLoop(sb); sb.Append('{'); sb.Append(_lower); if (!IsBoundedLoop) { sb.Append(','); } else if (_lower != _upper) { sb.Append(','); sb.Append(_upper); } sb.Append('}'); if (IsLazy) sb.Append('?'); } return; case SymbolicRegexNodeKind.CaptureStart: sb.Append('\u230A'); // Left floor // Include group number as a subscript Debug.Assert(_lower >= 0); foreach (char c in _lower.ToString()) { sb.Append((char)('\u2080' + (c - '0'))); } return; case SymbolicRegexNodeKind.CaptureEnd: // Include group number as a superscript Debug.Assert(_lower >= 0); foreach (char c in _lower.ToString()) { switch (c) { case '1': sb.Append('\u00B9'); break; case '2': sb.Append('\u00B2'); break; case '3': sb.Append('\u00B3'); break; default: sb.Append((char)('\u2070' + (c - '0'))); break; } } sb.Append('\u2309'); // Right ceiling return; case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(_left is not null); _left.ToString(sb); return; default: // Using the operator ~ for complement Debug.Assert(_kind == SymbolicRegexNodeKind.Not); Debug.Assert(_left is not null); sb.Append("~("); _left.ToString(sb); sb.Append(')'); return; } } /// <summary> /// Returns the set of all predicates that occur in the regex or /// the set containing True if there are no precidates in the regex, e.g., if the regex is "^" /// </summary> public HashSet<S> GetPredicates() { var predicates = new HashSet<S>(); CollectPredicates_helper(predicates); return predicates; } /// <summary> /// Collects all predicates that occur in the regex into the given set predicates /// </summary> private void CollectPredicates_helper(HashSet<S> predicates) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(CollectPredicates_helper, predicates); return; } switch (_kind) { case SymbolicRegexNodeKind.BOLAnchor: case SymbolicRegexNodeKind.EOLAnchor: case SymbolicRegexNodeKind.EndAnchorZ: case SymbolicRegexNodeKind.EndAnchorZReverse: predicates.Add(_builder._newLinePredicate); return; case SymbolicRegexNodeKind.BeginningAnchor: case SymbolicRegexNodeKind.EndAnchor: case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.FixedLengthMarker: case SymbolicRegexNodeKind.CaptureStart: case SymbolicRegexNodeKind.CaptureEnd: return; case SymbolicRegexNodeKind.Singleton: Debug.Assert(_set is not null); predicates.Add(_set); return; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); _left.CollectPredicates_helper(predicates); return; case SymbolicRegexNodeKind.Or: case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); foreach (SymbolicRegexNode<S> sr in _alts) { sr.CollectPredicates_helper(predicates); } return; case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); _left.CollectPredicates_helper(predicates); _right.CollectPredicates_helper(predicates); return; case SymbolicRegexNodeKind.Concat: // avoid deep nested recursion over long concat nodes SymbolicRegexNode<S> conc = this; while (conc._kind == SymbolicRegexNodeKind.Concat) { Debug.Assert(conc._left is not null && conc._right is not null); conc._left.CollectPredicates_helper(predicates); conc = conc._right; } conc.CollectPredicates_helper(predicates); return; case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(_left is not null); _left.CollectPredicates_helper(predicates); return; case SymbolicRegexNodeKind.Not: Debug.Assert(_left is not null); _left.CollectPredicates_helper(predicates); return; case SymbolicRegexNodeKind.NonBoundaryAnchor: case SymbolicRegexNodeKind.BoundaryAnchor: predicates.Add(_builder._wordLetterPredicateForAnchors); return; default: Debug.Fail($"{nameof(CollectPredicates_helper)}:{_kind}"); break; } } /// <summary> /// Compute all the minterms from the predicates in this regex. /// If S implements IComparable then sort the result in increasing order. /// </summary> public S[] ComputeMinterms() { Debug.Assert(typeof(S).IsAssignableTo(typeof(IComparable<S>))); HashSet<S> predicates = GetPredicates(); List<S> mt = _builder._solver.GenerateMinterms(predicates); mt.Sort(); return mt.ToArray(); } /// <summary> /// Create the reverse of this regex /// </summary> public SymbolicRegexNode<S> Reverse() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(Reverse); } switch (_kind) { case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); return _builder.CreateLoop(_left.Reverse(), IsLazy, _lower, _upper); case SymbolicRegexNodeKind.Concat: { Debug.Assert(_left is not null && _right is not null); SymbolicRegexNode<S> rev = _left.Reverse(); SymbolicRegexNode<S> rest = _right; while (rest._kind == SymbolicRegexNodeKind.Concat) { Debug.Assert(rest._left is not null && rest._right is not null); SymbolicRegexNode<S> rev1 = rest._left.Reverse(); rev = _builder.CreateConcat(rev1, rev); rest = rest._right; } SymbolicRegexNode<S> restr = rest.Reverse(); rev = _builder.CreateConcat(restr, rev); return rev; } case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); return _builder.Or(_alts.Reverse()); case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); return _builder.OrderedOr(_left.Reverse(), _right.Reverse()); case SymbolicRegexNodeKind.And: Debug.Assert(_alts is not null); return _builder.And(_alts.Reverse()); case SymbolicRegexNodeKind.Not: Debug.Assert(_left is not null); return _builder.Not(_left.Reverse()); case SymbolicRegexNodeKind.FixedLengthMarker: // Fixed length markers are omitted in reverse return _builder.Epsilon; case SymbolicRegexNodeKind.BeginningAnchor: // The reverse of BeginningAnchor is EndAnchor return _builder.EndAnchor; case SymbolicRegexNodeKind.EndAnchor: return _builder.BeginningAnchor; case SymbolicRegexNodeKind.BOLAnchor: // The reverse of BOLanchor is EOLanchor return _builder.EolAnchor; case SymbolicRegexNodeKind.EOLAnchor: return _builder.BolAnchor; case SymbolicRegexNodeKind.EndAnchorZ: // The reversal of the \Z anchor return _builder.EndAnchorZReverse; case SymbolicRegexNodeKind.EndAnchorZReverse: // This can potentially only happen if a reversed regex is reversed again. // Thus, this case is unreachable here, but included for completeness. return _builder.EndAnchorZ; case SymbolicRegexNodeKind.CaptureStart: return CreateCaptureEnd(_builder, _lower); case SymbolicRegexNodeKind.CaptureEnd: return CreateCaptureStart(_builder, _lower); case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(_left is not null); return _builder.CreateDisableBacktrackingSimulation(_left.Reverse()); // Remaining cases map to themselves: case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.Singleton: case SymbolicRegexNodeKind.BoundaryAnchor: case SymbolicRegexNodeKind.NonBoundaryAnchor: default: return this; } } internal bool StartsWithLoop(int upperBoundLowestValue = 1) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(StartsWithLoop, upperBoundLowestValue); } switch (_kind) { case SymbolicRegexNodeKind.Loop: return (_upper < int.MaxValue) && (_upper > upperBoundLowestValue); case SymbolicRegexNodeKind.Concat: Debug.Assert(_left is not null && _right is not null); return _left.StartsWithLoop(upperBoundLowestValue) || (_left.IsNullable && _right.StartsWithLoop(upperBoundLowestValue)); case SymbolicRegexNodeKind.Or: Debug.Assert(_alts is not null); return _alts.StartsWithLoop(upperBoundLowestValue); case SymbolicRegexNodeKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); return _left.StartsWithLoop(upperBoundLowestValue) || _right.StartsWithLoop(upperBoundLowestValue); case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(_left is not null); return _left.StartsWithLoop(upperBoundLowestValue); default: return false; }; } /// <summary>Get the predicate that covers all elements that make some progress.</summary> internal S GetStartSet() => _startSet; /// <summary>Compute the predicate that covers all elements that make some progress.</summary> private S ComputeStartSet() { switch (_kind) { // Anchors and () do not contribute to the startset case SymbolicRegexNodeKind.Epsilon: case SymbolicRegexNodeKind.FixedLengthMarker: case SymbolicRegexNodeKind.EndAnchor: case SymbolicRegexNodeKind.BeginningAnchor: case SymbolicRegexNodeKind.BoundaryAnchor: case SymbolicRegexNodeKind.NonBoundaryAnchor: case SymbolicRegexNodeKind.EOLAnchor: case SymbolicRegexNodeKind.EndAnchorZ: case SymbolicRegexNodeKind.EndAnchorZReverse: case SymbolicRegexNodeKind.BOLAnchor: case SymbolicRegexNodeKind.CaptureStart: case SymbolicRegexNodeKind.CaptureEnd: return _builder._solver.False; case SymbolicRegexNodeKind.Singleton: Debug.Assert(_set is not null); return _set; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); return _left._startSet; case SymbolicRegexNodeKind.Concat: { Debug.Assert(_left is not null && _right is not null); S startSet = _left.CanBeNullable ? _builder._solver.Or(_left._startSet, _right._startSet) : _left._startSet; return startSet; } case SymbolicRegexNodeKind.Or: { Debug.Assert(_alts is not null); S startSet = _builder._solver.False; foreach (SymbolicRegexNode<S> alt in _alts) { startSet = _builder._solver.Or(startSet, alt._startSet); } return startSet; } case SymbolicRegexNodeKind.OrderedOr: { Debug.Assert(_left is not null && _right is not null); return _builder._solver.Or(_left._startSet, _right._startSet); } case SymbolicRegexNodeKind.And: { Debug.Assert(_alts is not null); S startSet = _builder._solver.True; foreach (SymbolicRegexNode<S> alt in _alts) { startSet = _builder._solver.And(startSet, alt._startSet); } return startSet; } case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(_left is not null); return _left._startSet; default: Debug.Assert(_kind == SymbolicRegexNodeKind.Not); return _builder._solver.True; } } /// <summary> /// Returns true if this is a loop with an upper bound /// </summary> public bool IsBoundedLoop => _kind == SymbolicRegexNodeKind.Loop && _upper < int.MaxValue; /// <summary> /// Replace anchors that are infeasible by [] wrt the given previous character kind and what continuation is possible. /// </summary> /// <param name="prevKind">previous character kind</param> /// <param name="contWithWL">if true the continuation can start with wordletter or stop</param> /// <param name="contWithNWL">if true the continuation can start with nonwordletter or stop</param> internal SymbolicRegexNode<S> PruneAnchors(uint prevKind, bool contWithWL, bool contWithNWL) { // Guard against stack overflow due to deep recursion if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(PruneAnchors, prevKind, contWithWL, contWithNWL); } if (!_info.StartsWithSomeAnchor) return this; switch (_kind) { case SymbolicRegexNodeKind.BeginningAnchor: return prevKind == CharKind.BeginningEnd ? this : _builder._nothing; //start anchor is only nullable if the previous character is Start case SymbolicRegexNodeKind.EndAnchorZReverse: return ((prevKind & CharKind.BeginningEnd) != 0) ? this : _builder._nothing; //rev(\Z) is only nullable if the previous characters is Start or the very first \n case SymbolicRegexNodeKind.BoundaryAnchor: return (prevKind == CharKind.WordLetter ? contWithNWL : contWithWL) ? this : // \b is impossible when the previous character is \w but no continuation matches \W // or the previous character is \W but no continuation matches \w _builder._nothing; case SymbolicRegexNodeKind.NonBoundaryAnchor: return (prevKind == CharKind.WordLetter ? contWithWL : contWithNWL) ? this : // \B is impossible when the previous character is \w but no continuation matches \w // or the previous character is \W but no continuation matches \W _builder._nothing; case SymbolicRegexNodeKind.Loop: Debug.Assert(_left is not null); SymbolicRegexNode<S> body = _left.PruneAnchors(prevKind, contWithWL, contWithNWL); return body == _left ? this : CreateLoop(_builder, body, _lower, _upper, IsLazy); case SymbolicRegexNodeKind.Concat: { Debug.Assert(_left is not null && _right is not null); SymbolicRegexNode<S> left1 = _left.PruneAnchors(prevKind, contWithWL, contWithNWL); SymbolicRegexNode<S> right1 = _left.IsNullable ? _right.PruneAnchors(prevKind, contWithWL, contWithNWL) : _right; Debug.Assert(left1 is not null && right1 is not null); return left1 == _left && right1 == _right ? this : CreateConcat(_builder, left1, right1); } case SymbolicRegexNodeKind.Or: { Debug.Assert(_alts != null); var elements = new SymbolicRegexNode<S>[_alts.Count]; int i = 0; foreach (SymbolicRegexNode<S> alt in _alts) { elements[i++] = alt.PruneAnchors(prevKind, contWithWL, contWithNWL); } Debug.Assert(i == elements.Length); return Or(_builder, elements); } case SymbolicRegexNodeKind.OrderedOr: { Debug.Assert(_left is not null && _right is not null); SymbolicRegexNode<S> left1 = _left.PruneAnchors(prevKind, contWithWL, contWithNWL); SymbolicRegexNode<S> right1 = _right.PruneAnchors(prevKind, contWithWL, contWithNWL); Debug.Assert(left1 is not null && right1 is not null); return left1 == _left && right1 == _right ? this : OrderedOr(_builder, left1, right1); } case SymbolicRegexNodeKind.DisableBacktrackingSimulation: Debug.Assert(_left is not null); SymbolicRegexNode<S> child = _left.PruneAnchors(prevKind, contWithWL, contWithNWL); return child == _left ? this : _builder.CreateDisableBacktrackingSimulation(child); default: return this; } } } }
1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexSet.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.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents a set of symbolic regexes that is either a disjunction or a conjunction</summary> internal sealed class SymbolicRegexSet<S> : IEnumerable<SymbolicRegexNode<S>> where S : notnull { internal readonly SymbolicRegexBuilder<S> _builder; private readonly HashSet<SymbolicRegexNode<S>> _set; /// <remarks> /// Symbolic regex A{0,k}?B is stored as (A,B,true) -> k -- lazy /// Symbolic regex A{0,k}? is stored as (A,(),true) -> k -- lazy /// Symbolic regex A{0,k}B is stored as (A,B,false) -> k -- eager /// Symbolic regex A{0,k} is stored as (A,(),false) -> k -- eager /// </remarks> private readonly Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int> _loops; /// <summary> the union (or intersection) of all singletons in the collection if any or null if none</summary> private readonly SymbolicRegexNode<S>? _singleton; internal readonly SymbolicRegexNodeKind _kind; private int _hashCode; /// <summary>If >= 0 then the maximal length of a fixed length markers in the set</summary> internal int _maximumLength = -1; private SymbolicRegexSet(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind, HashSet<SymbolicRegexNode<S>>? set, Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int>? loops, SymbolicRegexNode<S>? singleton) { Debug.Assert(kind is SymbolicRegexNodeKind.And or SymbolicRegexNodeKind.Or); Debug.Assert((set is null) == (loops is null)); _builder = builder; _kind = kind; _set = set ?? new HashSet<SymbolicRegexNode<S>>(); _loops = loops ?? new Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int>(); _singleton = singleton; } /// <summary>Denotes the empty conjunction</summary> public bool IsEverything => _kind == SymbolicRegexNodeKind.And && _set.Count == 0 && _loops.Count == 0 && _singleton == null; /// <summary>Denotes the empty disjunction</summary> public bool IsNothing => _kind == SymbolicRegexNodeKind.Or && _set.Count == 0 && _loops.Count == 0 && _singleton == null; /// <summary>How many elements are there in this set</summary> public int Count => _set.Count + _loops.Count + (_singleton == null ? 0 : 1); /// <summary>True iff the set is a singleton</summary> public bool IsSingleton => Count == 1; internal static SymbolicRegexSet<S> CreateFull(SymbolicRegexBuilder<S> builder) => new SymbolicRegexSet<S>(builder, SymbolicRegexNodeKind.And, null, null, null); internal static SymbolicRegexSet<S> CreateEmpty(SymbolicRegexBuilder<S> builder) => new SymbolicRegexSet<S>(builder, SymbolicRegexNodeKind.Or, null, null, null); internal static SymbolicRegexSet<S> CreateMulti(SymbolicRegexBuilder<S> builder, IEnumerable<SymbolicRegexNode<S>> elems, SymbolicRegexNodeKind kind) { // Loops contains the actual multi-set part of the collection var loops = new Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int>(); // Other represents a normal set var other = new HashSet<SymbolicRegexNode<S>>(); // Combination of singletons (when not null) SymbolicRegexNode<S>? singleton = null; int fixedLength = -1; foreach (SymbolicRegexNode<S> elem in elems) { // Keep track of the maximal fixed length if this is a disjunction // this means for example if the regex is abc(3)|bc(2) and // the input is xxxabcyyy then two fixed length markers will occur (3) and (2) // after reading c and the maximal one is taken // in a conjuctive setting this is undefined and the fixed length remains -1 if (kind == SymbolicRegexNodeKind.Or && elem._kind == SymbolicRegexNodeKind.FixedLengthMarker && elem._lower > fixedLength) { fixedLength = elem._lower; } #region start foreach if (elem == builder._anyStar) { // .* is the absorbing element for disjunction if (kind == SymbolicRegexNodeKind.Or) { return builder.FullSet; } } else if (elem == builder._nothing) { // [] is the absorbing element for conjunction if (kind == SymbolicRegexNodeKind.And) { return builder.EmptySet; } } else { switch (elem._kind) { case SymbolicRegexNodeKind.And: case SymbolicRegexNodeKind.Or: Debug.Assert(elem._alts is not null); if (kind == elem._kind) { // Flatten the inner set foreach (SymbolicRegexNode<S> alt in elem._alts) { if (alt._kind == SymbolicRegexNodeKind.Loop && alt._lower == 0) { AddLoopElement(builder, loops, other, alt, builder.Epsilon, kind); } else { if (alt._kind == SymbolicRegexNodeKind.Concat && alt._left!._kind == SymbolicRegexNodeKind.Loop && alt._left._lower == 0) { Debug.Assert(alt._right is not null); AddLoopElement(builder, loops, other, alt._left, alt._right, kind); } else { if (alt._kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(alt._set is not null); if (singleton is null) { singleton = alt; } else { Debug.Assert(singleton._kind == SymbolicRegexNodeKind.Singleton && singleton._set is not null); // Join the predicates either by Intersecting or Unioning // which at the character predicate level translates to conjunction or disjunction in the underlying character algebra S pred = kind == SymbolicRegexNodeKind.Or ? builder._solver.Or(singleton._set, alt._set) : builder._solver.And(singleton._set, alt._set); singleton = SymbolicRegexNode<S>.CreateSingleton(builder, pred); } } else { other.Add(alt); } } } } } else { other.Add(elem); } break; case SymbolicRegexNodeKind.Loop: if (elem._lower == 0) { AddLoopElement(builder, loops, other, elem, builder.Epsilon, kind); } else { other.Add(elem); } break; case SymbolicRegexNodeKind.Concat: Debug.Assert(elem._left is not null && elem._right is not null); if (elem._kind == SymbolicRegexNodeKind.Concat && elem._left._kind == SymbolicRegexNodeKind.Loop && elem._left._lower == 0) { AddLoopElement(builder, loops, other, elem._left, elem._right, kind); } else { other.Add(elem); } break; case SymbolicRegexNodeKind.Singleton: Debug.Assert(elem._set is not null); if (singleton is null) { singleton = elem; } else { Debug.Assert(singleton._kind == SymbolicRegexNodeKind.Singleton && singleton._set is not null); // Join the predicates either by Intersecting or Unioning // which at the character predicate level translates to conjunction or disjunction in the underlying character algebra S pred = kind == SymbolicRegexNodeKind.Or ? builder._solver.Or(singleton._set, elem._set) : builder._solver.And(singleton._set, elem._set); singleton = SymbolicRegexNode<S>.CreateSingleton(builder, pred); } break; default: other.Add(elem); break; } } #endregion } // This optimization is only valid for a conjunction/intersection if (kind == SymbolicRegexNodeKind.And && singleton is not null && singleton.Equals(builder._solver.False)) { return builder.EmptySet; } // The following is only valid for a disjunction/union if (kind == SymbolicRegexNodeKind.Or) { // If any element of other is covered in loops then omit it var others1 = new HashSet<SymbolicRegexNode<S>>(); foreach (SymbolicRegexNode<S> sr in other) { // If there is an element A{0,m} then A is not needed because // it is included by the loop due to the upper bound m > 0 if (loops.ContainsKey((sr, builder.Epsilon, false))) { others1.Add(sr); } } foreach (KeyValuePair<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int> pair in loops) { // If there is an element A{0,m}B then B is not needed because // it is included by the concatenation due to the lower bound 0 if (other.Contains(pair.Key.Item2)) { others1.Add(pair.Key.Item2); } } other.ExceptWith(others1); } return other.Count != 0 || loops.Count != 0 || singleton is not null ? new SymbolicRegexSet<S>(builder, kind, other, loops, singleton) { _maximumLength = fixedLength } : kind == SymbolicRegexNodeKind.Or ? builder.EmptySet : builder.FullSet; [MethodImpl(MethodImplOptions.AggressiveInlining)] static void AddLoopElement( SymbolicRegexBuilder<S> builder, Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int> loops, HashSet<SymbolicRegexNode<S>> other, SymbolicRegexNode<S> loop, SymbolicRegexNode<S> rest, SymbolicRegexNodeKind kind) { if (loop._upper == 0 && rest.IsEpsilon) { // In a set treat a loop with upper=lower=0 and no rest (no continuation after the loop) // as () independent of whether it is lazy or eager other.Add(builder.Epsilon); } else { Debug.Assert(loop._left is not null); (SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool) key = (loop._left, rest, loop.IsLazy); if (!loops.TryGetValue(key, out int count) || (kind == SymbolicRegexNodeKind.Or ? count < loop._upper : count > loop._upper)) // If disjunction then map to the maximum of the upper bounds else to the minimum { loops[key] = loop._upper; } } } } internal bool IsNullableFor(uint context) { Enumerator e = GetEnumerator(); if (_kind == SymbolicRegexNodeKind.Or) { // Some element must be nullable while (e.MoveNext()) { if (e.Current.IsNullableFor(context)) { return true; } } return false; } else { Debug.Assert(_kind == SymbolicRegexNodeKind.And); // All elements must be nullable while (e.MoveNext()) { if (!e.Current.IsNullableFor(context)) { return false; } } return true; } } public override int GetHashCode() { if (_hashCode == 0) { int hashCode = _kind.GetHashCode(); if (_singleton is not null) { hashCode ^= _singleton.GetHashCode(); } foreach (SymbolicRegexNode<S> n in _set) { hashCode ^= n.GetHashCode(); } foreach (KeyValuePair<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int> entry in _loops) { hashCode ^= entry.Key.GetHashCode() + entry.Value.GetHashCode(); } _hashCode = hashCode; } return _hashCode; } public override bool Equals([NotNullWhen(true)] object? obj) { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance if (obj is not SymbolicRegexSet<S> that || _kind != that._kind || _singleton is null && that._singleton is not null || _singleton is not null && !_singleton.Equals(that._singleton) || _set.Count != that._set.Count || _loops.Count != that._loops.Count || (_set.Count > 0 && !_set.SetEquals(that._set))) { return false; } foreach (KeyValuePair<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int> c in _loops) { if (!that._loops.TryGetValue(c.Key, out int count) || !count.Equals(c.Value)) { return false; } } return true; } public void ToString(StringBuilder sb) { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance if (IsNothing) { sb.Append(SymbolicRegexNode<S>.EmptyCharClass); } else if (IsEverything) { sb.Append(".*"); } else { Enumerator enumerator = GetEnumerator(); bool nonempty = enumerator.MoveNext(); Debug.Assert(nonempty, "Collection must be nonempty because IsNothing is false and IsEverything is false"); SymbolicRegexNode<S> node = enumerator.Current; if (!enumerator.MoveNext()) { // The collection only has one element node.ToString(sb); } else { // Union of two or more elements sb.Append('('); // Append the first two elements node.ToString(sb); // Using the operator & for intersection char op = _kind == SymbolicRegexNodeKind.Or ? '|' : '&'; sb.Append(op); enumerator.Current.ToString(sb); while (enumerator.MoveNext()) { // Append all the remaining elements sb.Append(op); enumerator.Current.ToString(sb); } sb.Append(')'); } } } internal SymbolicRegexSet<S> CreateDerivative(S elem, uint context) { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance return CreateMulti(_builder, CreateDerivativesOfElems(elem, context), _kind); IEnumerable<SymbolicRegexNode<S>> CreateDerivativesOfElems(S elem, uint context) { foreach (SymbolicRegexNode<S> s in this) { yield return s.CreateDerivative(elem, context); } } } internal SymbolicRegexSet<T> Transform<T>(SymbolicRegexBuilder<T> builderT, Func<S, T> predicateTransformer) where T : notnull { // This function is mutually recursive with the one in SymbolicRegexBuilder, which has stack overflow avoidance return SymbolicRegexSet<T>.CreateMulti(builderT, TransformElements(builderT, predicateTransformer), _kind); IEnumerable<SymbolicRegexNode<T>> TransformElements(SymbolicRegexBuilder<T> builderT, Func<S, T> predicateTransformer) { foreach (SymbolicRegexNode<S> sr in this) { yield return _builder.Transform(sr, builderT, predicateTransformer); } } } internal SymbolicRegexNode<S> GetSingletonElement() { Debug.Assert(IsSingleton); Enumerator e = GetEnumerator(); bool success = e.MoveNext(); Debug.Assert(success); return e.Current; } internal SymbolicRegexSet<S> Reverse() { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance return CreateMulti(_builder, ReverseElements(), _kind); IEnumerable<SymbolicRegexNode<S>> ReverseElements() { foreach (SymbolicRegexNode<S> n in this) { yield return n.Reverse(); } } } internal bool StartsWithLoop(int upperBoundLowestValue) { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance foreach (SymbolicRegexNode<S> n in this) { if (n.StartsWithLoop(upperBoundLowestValue)) { return true; } } return false; } public Enumerator GetEnumerator() => new Enumerator(this); IEnumerator<SymbolicRegexNode<S>> IEnumerable<SymbolicRegexNode<S>>.GetEnumerator() => new Enumerator(this); IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); internal int GetFixedLength() { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance if (_loops.Count > 0) { return -1; } int length = -1; foreach (SymbolicRegexNode<S> node in _set) { int nodeLength = node.GetFixedLength(); if (nodeLength == -1) { return -1; } else if (length == -1) { length = nodeLength; } else if (length != nodeLength) { return -1; } } if (_singleton is not null && length != 1) { if (length == -1) { length = 1; } else { length = -1; } } return length; } /// <summary>Enumerates all symbolic regexes in the set</summary> internal struct Enumerator : IEnumerator<SymbolicRegexNode<S>> { private readonly SymbolicRegexSet<S> _set; private int _state; // 0 = return singleton, 1 == iterate set, 2 == iterate loops, 3 == done private SymbolicRegexNode<S>? _current; private HashSet<SymbolicRegexNode<S>>.Enumerator _setEnumerator; private Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int>.Enumerator _loopsEnumerator; internal Enumerator(SymbolicRegexSet<S> symbolicRegexSet) { _state = symbolicRegexSet._singleton is null ? 1 : 0; _set = symbolicRegexSet; _setEnumerator = symbolicRegexSet._set.GetEnumerator(); _loopsEnumerator = symbolicRegexSet._loops.GetEnumerator(); _current = null; } public SymbolicRegexNode<S> Current => _current!; object IEnumerator.Current => Current; public void Dispose() { _state = 3; _setEnumerator.Dispose(); _loopsEnumerator.Dispose(); } public bool MoveNext() { switch (_state) { case 0: Debug.Assert(_set._singleton is not null); _current = _set._singleton; _state = 1; return true; case 1: if (_setEnumerator.MoveNext()) { _current = _setEnumerator.Current; return true; } _state = 2; goto case 2; case 2: if (_loopsEnumerator.MoveNext()) { // Recreate the symbolic regex from (body,rest)->k to body{0,k}rest (SymbolicRegexNode<S> body, SymbolicRegexNode<S> rest, bool isLazy) = _loopsEnumerator.Current.Key; int upper = _loopsEnumerator.Current.Value; _current = _set._builder.CreateConcat(_set._builder.CreateLoop(body, isLazy, 0, upper), rest); return true; } _state = 3; goto default; default: _current = null!; return false; } } public void Reset() => throw new NotSupportedException(); } } }
// 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.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents a set of symbolic regexes that is either a disjunction or a conjunction</summary> internal sealed class SymbolicRegexSet<S> : IEnumerable<SymbolicRegexNode<S>> where S : notnull { internal readonly SymbolicRegexBuilder<S> _builder; private readonly HashSet<SymbolicRegexNode<S>> _set; /// <remarks> /// Symbolic regex A{0,k}?B is stored as (A,B,true) -> k -- lazy /// Symbolic regex A{0,k}? is stored as (A,(),true) -> k -- lazy /// Symbolic regex A{0,k}B is stored as (A,B,false) -> k -- eager /// Symbolic regex A{0,k} is stored as (A,(),false) -> k -- eager /// </remarks> private readonly Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int> _loops; /// <summary> the union (or intersection) of all singletons in the collection if any or null if none</summary> private readonly SymbolicRegexNode<S>? _singleton; internal readonly SymbolicRegexNodeKind _kind; private int _hashCode; /// <summary>If >= 0 then the maximal length of a fixed length markers in the set</summary> internal int _maximumLength = -1; private SymbolicRegexSet(SymbolicRegexBuilder<S> builder, SymbolicRegexNodeKind kind, HashSet<SymbolicRegexNode<S>>? set, Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int>? loops, SymbolicRegexNode<S>? singleton) { Debug.Assert(kind is SymbolicRegexNodeKind.And or SymbolicRegexNodeKind.Or); Debug.Assert((set is null) == (loops is null)); _builder = builder; _kind = kind; _set = set ?? new HashSet<SymbolicRegexNode<S>>(); _loops = loops ?? new Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int>(); _singleton = singleton; } /// <summary>Denotes the empty conjunction</summary> public bool IsEverything => _kind == SymbolicRegexNodeKind.And && _set.Count == 0 && _loops.Count == 0 && _singleton == null; /// <summary>Denotes the empty disjunction</summary> public bool IsNothing => _kind == SymbolicRegexNodeKind.Or && _set.Count == 0 && _loops.Count == 0 && _singleton == null; /// <summary>How many elements are there in this set</summary> public int Count => _set.Count + _loops.Count + (_singleton == null ? 0 : 1); /// <summary>True iff the set is a singleton</summary> public bool IsSingleton => Count == 1; internal static SymbolicRegexSet<S> CreateFull(SymbolicRegexBuilder<S> builder) => new SymbolicRegexSet<S>(builder, SymbolicRegexNodeKind.And, null, null, null); internal static SymbolicRegexSet<S> CreateEmpty(SymbolicRegexBuilder<S> builder) => new SymbolicRegexSet<S>(builder, SymbolicRegexNodeKind.Or, null, null, null); internal static SymbolicRegexSet<S> CreateMulti(SymbolicRegexBuilder<S> builder, IEnumerable<SymbolicRegexNode<S>> elems, SymbolicRegexNodeKind kind) { // Loops contains the actual multi-set part of the collection var loops = new Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int>(); // Other represents a normal set var other = new HashSet<SymbolicRegexNode<S>>(); // Combination of singletons (when not null) SymbolicRegexNode<S>? singleton = null; int fixedLength = -1; foreach (SymbolicRegexNode<S> elem in elems) { // Keep track of the maximal fixed length if this is a disjunction // this means for example if the regex is abc(3)|bc(2) and // the input is xxxabcyyy then two fixed length markers will occur (3) and (2) // after reading c and the maximal one is taken // in a conjuctive setting this is undefined and the fixed length remains -1 if (kind == SymbolicRegexNodeKind.Or && elem._kind == SymbolicRegexNodeKind.FixedLengthMarker && elem._lower > fixedLength) { fixedLength = elem._lower; } #region start foreach if (elem == builder._anyStar) { // .* is the absorbing element for disjunction if (kind == SymbolicRegexNodeKind.Or) { return builder.FullSet; } } else if (elem == builder._nothing) { // [] is the absorbing element for conjunction if (kind == SymbolicRegexNodeKind.And) { return builder.EmptySet; } } else { switch (elem._kind) { case SymbolicRegexNodeKind.And: case SymbolicRegexNodeKind.Or: Debug.Assert(elem._alts is not null); if (kind == elem._kind) { // Flatten the inner set foreach (SymbolicRegexNode<S> alt in elem._alts) { if (alt._kind == SymbolicRegexNodeKind.Loop && alt._lower == 0) { AddLoopElement(builder, loops, other, alt, builder.Epsilon, kind); } else { if (alt._kind == SymbolicRegexNodeKind.Concat && alt._left!._kind == SymbolicRegexNodeKind.Loop && alt._left._lower == 0) { Debug.Assert(alt._right is not null); AddLoopElement(builder, loops, other, alt._left, alt._right, kind); } else { if (alt._kind == SymbolicRegexNodeKind.Singleton) { Debug.Assert(alt._set is not null); if (singleton is null) { singleton = alt; } else { Debug.Assert(singleton._kind == SymbolicRegexNodeKind.Singleton && singleton._set is not null); // Join the predicates either by Intersecting or Unioning // which at the character predicate level translates to conjunction or disjunction in the underlying character algebra S pred = kind == SymbolicRegexNodeKind.Or ? builder._solver.Or(singleton._set, alt._set) : builder._solver.And(singleton._set, alt._set); singleton = SymbolicRegexNode<S>.CreateSingleton(builder, pred); } } else { other.Add(alt); } } } } } else { other.Add(elem); } break; case SymbolicRegexNodeKind.Loop: if (elem._lower == 0) { AddLoopElement(builder, loops, other, elem, builder.Epsilon, kind); } else { other.Add(elem); } break; case SymbolicRegexNodeKind.Concat: Debug.Assert(elem._left is not null && elem._right is not null); if (elem._kind == SymbolicRegexNodeKind.Concat && elem._left._kind == SymbolicRegexNodeKind.Loop && elem._left._lower == 0) { AddLoopElement(builder, loops, other, elem._left, elem._right, kind); } else { other.Add(elem); } break; case SymbolicRegexNodeKind.Singleton: Debug.Assert(elem._set is not null); if (singleton is null) { singleton = elem; } else { Debug.Assert(singleton._kind == SymbolicRegexNodeKind.Singleton && singleton._set is not null); // Join the predicates either by Intersecting or Unioning // which at the character predicate level translates to conjunction or disjunction in the underlying character algebra S pred = kind == SymbolicRegexNodeKind.Or ? builder._solver.Or(singleton._set, elem._set) : builder._solver.And(singleton._set, elem._set); singleton = SymbolicRegexNode<S>.CreateSingleton(builder, pred); } break; default: other.Add(elem); break; } } #endregion } // This optimization is only valid for a conjunction/intersection if (kind == SymbolicRegexNodeKind.And && singleton is not null && singleton.Equals(builder._solver.False)) { return builder.EmptySet; } // The following is only valid for a disjunction/union if (kind == SymbolicRegexNodeKind.Or) { // If any element of other is covered in loops then omit it var others1 = new HashSet<SymbolicRegexNode<S>>(); foreach (SymbolicRegexNode<S> sr in other) { // If there is an element A{0,m} then A is not needed because // it is included by the loop due to the upper bound m > 0 if (loops.ContainsKey((sr, builder.Epsilon, false))) { others1.Add(sr); } } foreach (KeyValuePair<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int> pair in loops) { // If there is an element A{0,m}B then B is not needed because // it is included by the concatenation due to the lower bound 0 if (other.Contains(pair.Key.Item2)) { others1.Add(pair.Key.Item2); } } other.ExceptWith(others1); } return other.Count != 0 || loops.Count != 0 || singleton is not null ? new SymbolicRegexSet<S>(builder, kind, other, loops, singleton) { _maximumLength = fixedLength } : kind == SymbolicRegexNodeKind.Or ? builder.EmptySet : builder.FullSet; [MethodImpl(MethodImplOptions.AggressiveInlining)] static void AddLoopElement( SymbolicRegexBuilder<S> builder, Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int> loops, HashSet<SymbolicRegexNode<S>> other, SymbolicRegexNode<S> loop, SymbolicRegexNode<S> rest, SymbolicRegexNodeKind kind) { if (loop._upper == 0 && rest.IsEpsilon) { // In a set treat a loop with upper=lower=0 and no rest (no continuation after the loop) // as () independent of whether it is lazy or eager other.Add(builder.Epsilon); } else { Debug.Assert(loop._left is not null); (SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool) key = (loop._left, rest, loop.IsLazy); if (!loops.TryGetValue(key, out int count) || (kind == SymbolicRegexNodeKind.Or ? count < loop._upper : count > loop._upper)) // If disjunction then map to the maximum of the upper bounds else to the minimum { loops[key] = loop._upper; } } } } internal bool IsNullableFor(uint context) { Enumerator e = GetEnumerator(); if (_kind == SymbolicRegexNodeKind.Or) { // Some element must be nullable while (e.MoveNext()) { if (e.Current.IsNullableFor(context)) { return true; } } return false; } else { Debug.Assert(_kind == SymbolicRegexNodeKind.And); // All elements must be nullable while (e.MoveNext()) { if (!e.Current.IsNullableFor(context)) { return false; } } return true; } } public override int GetHashCode() { if (_hashCode == 0) { int hashCode = _kind.GetHashCode(); if (_singleton is not null) { hashCode ^= _singleton.GetHashCode(); } foreach (SymbolicRegexNode<S> n in _set) { hashCode ^= n.GetHashCode(); } foreach (KeyValuePair<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int> entry in _loops) { hashCode ^= entry.Key.GetHashCode() + entry.Value.GetHashCode(); } _hashCode = hashCode; } return _hashCode; } public override bool Equals([NotNullWhen(true)] object? obj) { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance if (obj is not SymbolicRegexSet<S> that || _kind != that._kind || _singleton is null && that._singleton is not null || _singleton is not null && !_singleton.Equals(that._singleton) || _set.Count != that._set.Count || _loops.Count != that._loops.Count || (_set.Count > 0 && !_set.SetEquals(that._set))) { return false; } foreach (KeyValuePair<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int> c in _loops) { if (!that._loops.TryGetValue(c.Key, out int count) || !count.Equals(c.Value)) { return false; } } return true; } public void ToString(StringBuilder sb) { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance if (IsNothing) { sb.Append(SymbolicRegexNode<S>.EmptyCharClass); } else if (IsEverything) { sb.Append(".*"); } else { Enumerator enumerator = GetEnumerator(); bool nonempty = enumerator.MoveNext(); Debug.Assert(nonempty, "Collection must be nonempty because IsNothing is false and IsEverything is false"); SymbolicRegexNode<S> node = enumerator.Current; if (!enumerator.MoveNext()) { // The collection only has one element node.ToString(sb); } else { // Union of two or more elements sb.Append('('); // Append the first two elements node.ToString(sb); // Using the operator & for intersection char op = _kind == SymbolicRegexNodeKind.Or ? '|' : '&'; sb.Append(op); enumerator.Current.ToString(sb); while (enumerator.MoveNext()) { // Append all the remaining elements sb.Append(op); enumerator.Current.ToString(sb); } sb.Append(')'); } } } internal SymbolicRegexSet<T> Transform<T>(SymbolicRegexBuilder<T> builderT, Func<S, T> predicateTransformer) where T : notnull { // This function is mutually recursive with the one in SymbolicRegexBuilder, which has stack overflow avoidance return SymbolicRegexSet<T>.CreateMulti(builderT, TransformElements(builderT, predicateTransformer), _kind); IEnumerable<SymbolicRegexNode<T>> TransformElements(SymbolicRegexBuilder<T> builderT, Func<S, T> predicateTransformer) { foreach (SymbolicRegexNode<S> sr in this) { yield return _builder.Transform(sr, builderT, predicateTransformer); } } } internal SymbolicRegexNode<S> GetSingletonElement() { Debug.Assert(IsSingleton); Enumerator e = GetEnumerator(); bool success = e.MoveNext(); Debug.Assert(success); return e.Current; } internal SymbolicRegexSet<S> Reverse() { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance return CreateMulti(_builder, ReverseElements(), _kind); IEnumerable<SymbolicRegexNode<S>> ReverseElements() { foreach (SymbolicRegexNode<S> n in this) { yield return n.Reverse(); } } } internal bool StartsWithLoop(int upperBoundLowestValue) { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance foreach (SymbolicRegexNode<S> n in this) { if (n.StartsWithLoop(upperBoundLowestValue)) { return true; } } return false; } public Enumerator GetEnumerator() => new Enumerator(this); IEnumerator<SymbolicRegexNode<S>> IEnumerable<SymbolicRegexNode<S>>.GetEnumerator() => new Enumerator(this); IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); internal int GetFixedLength() { // This function is mutually recursive with the one in SymbolicRegexNode, which has stack overflow avoidance if (_loops.Count > 0) { return -1; } int length = -1; foreach (SymbolicRegexNode<S> node in _set) { int nodeLength = node.GetFixedLength(); if (nodeLength == -1) { return -1; } else if (length == -1) { length = nodeLength; } else if (length != nodeLength) { return -1; } } if (_singleton is not null && length != 1) { if (length == -1) { length = 1; } else { length = -1; } } return length; } /// <summary>Enumerates all symbolic regexes in the set</summary> internal struct Enumerator : IEnumerator<SymbolicRegexNode<S>> { private readonly SymbolicRegexSet<S> _set; private int _state; // 0 = return singleton, 1 == iterate set, 2 == iterate loops, 3 == done private SymbolicRegexNode<S>? _current; private HashSet<SymbolicRegexNode<S>>.Enumerator _setEnumerator; private Dictionary<(SymbolicRegexNode<S>, SymbolicRegexNode<S>, bool), int>.Enumerator _loopsEnumerator; internal Enumerator(SymbolicRegexSet<S> symbolicRegexSet) { _state = symbolicRegexSet._singleton is null ? 1 : 0; _set = symbolicRegexSet; _setEnumerator = symbolicRegexSet._set.GetEnumerator(); _loopsEnumerator = symbolicRegexSet._loops.GetEnumerator(); _current = null; } public SymbolicRegexNode<S> Current => _current!; object IEnumerator.Current => Current; public void Dispose() { _state = 3; _setEnumerator.Dispose(); _loopsEnumerator.Dispose(); } public bool MoveNext() { switch (_state) { case 0: Debug.Assert(_set._singleton is not null); _current = _set._singleton; _state = 1; return true; case 1: if (_setEnumerator.MoveNext()) { _current = _setEnumerator.Current; return true; } _state = 2; goto case 2; case 2: if (_loopsEnumerator.MoveNext()) { // Recreate the symbolic regex from (body,rest)->k to body{0,k}rest (SymbolicRegexNode<S> body, SymbolicRegexNode<S> rest, bool isLazy) = _loopsEnumerator.Current.Key; int upper = _loopsEnumerator.Current.Value; _current = _set._builder.CreateConcat(_set._builder.CreateLoop(body, isLazy, 0, upper), rest); return true; } _state = 3; goto default; default: _current = null!; return false; } } public void Reset() => throw new NotSupportedException(); } } }
1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/TransitionRegex.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.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents a symbolic derivative created from a symbolic regex without using minterms</summary> internal sealed class TransitionRegex<S> where S : notnull { public readonly SymbolicRegexBuilder<S> _builder; public readonly TransitionRegexKind _kind; public readonly S? _test; public readonly TransitionRegex<S>? _first; public readonly TransitionRegex<S>? _second; public readonly SymbolicRegexNode<S>? _node; public readonly DerivativeEffect? _effect; private TransitionRegex(SymbolicRegexBuilder<S> builder, TransitionRegexKind kind, S? test, TransitionRegex<S>? first, TransitionRegex<S>? second, SymbolicRegexNode<S>? node, DerivativeEffect? effect) { Debug.Assert(builder is not null); Debug.Assert( kind is TransitionRegexKind.Leaf && node is not null && Equals(test, default(S)) && first is null && second is null && effect is null || kind is TransitionRegexKind.Conditional && test is not null && first is not null && second is not null && node is null && effect is null || kind is TransitionRegexKind.Union && Equals(test, default(S)) && first is not null && second is not null && node is null && effect is null || kind is TransitionRegexKind.OrderedUnion && Equals(test, default(S)) && first is not null && second is not null && node is null && effect is null || kind is TransitionRegexKind.Lookaround && Equals(test, default(S)) && first is not null && second is not null && node is not null && effect is null || kind is TransitionRegexKind.Effect && Equals(test, default(S)) && first is not null && second is null && node is null && effect is not null); _builder = builder; _kind = kind; _test = test; _first = first; _second = second; _node = node; _effect = effect; } private static TransitionRegex<S> GetOrCreate(SymbolicRegexBuilder<S> builder, TransitionRegexKind kind, S? test, TransitionRegex<S>? one, TransitionRegex<S>? two, SymbolicRegexNode<S>? node, DerivativeEffect? effect = null) { // Keep transition regexes internalized using the builder ref TransitionRegex<S>? tr = ref CollectionsMarshal.GetValueRefOrAddDefault(builder._trCache, (kind, test, one, two, node, effect), out _); return tr ??= new TransitionRegex<S>(builder, kind, test, one, two, node, effect); } public bool IsNothing { get { if (_kind == TransitionRegexKind.Leaf) { Debug.Assert(_node != null); return _node.IsNothing; } return false; } } public bool IsAnyStar { get { if (_kind == TransitionRegexKind.Leaf) { Debug.Assert(_node != null); return _node.IsAnyStar; } return false; } } /// <summary>Complement of transition regex</summary> public TransitionRegex<S> Complement() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(Complement); } switch (_kind) { case TransitionRegexKind.Leaf: // Complement is propagated to the leaf Debug.Assert(_node is not null); return GetOrCreate(_builder, _kind, default(S), null, null, _node._builder.Not(_node)); case TransitionRegexKind.Union: // Apply deMorgan's laws Debug.Assert(_first is not null && _second is not null); return Intersect(_first.Complement(), _second.Complement()); default: // Both Conditional and Nullability obey the same laws of propagation of complement Debug.Assert(_first is not null && _second is not null); return GetOrCreate(_builder, _kind, _test, _first.Complement(), _second.Complement(), _node); } } public static TransitionRegex<S> Leaf(SymbolicRegexNode<S> node) => GetOrCreate(node._builder, TransitionRegexKind.Leaf, default(S), null, null, node); /// <summary>Concatenate a node at the end of this transition regex</summary> public TransitionRegex<S> Concat(SymbolicRegexNode<S> node) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(Concat, node); } switch (_kind) { case TransitionRegexKind.Leaf: Debug.Assert(_node is not null); return GetOrCreate(_builder, _kind, default(S), null, null, _node._builder.CreateConcat(_node, node)); case TransitionRegexKind.Effect: Debug.Assert(_first is not null); return GetOrCreate(_builder, _kind, default(S), _first.Concat(node), null, null, _effect); default: // All other three cases are disjunctive and obey the same laws of propagation of complement Debug.Assert(_first is not null && _second is not null); return GetOrCreate(_builder, _kind, _test, _first.Concat(node), _second.Concat(node), _node); } } /// <summary>Intersection of transition regexes</summary> public static TransitionRegex<S> Intersect(TransitionRegex<S> one, TransitionRegex<S> two) { // Apply standard simplifications // [] & t = [], t & .* = t if (one.IsNothing || two.IsAnyStar || one == two) { return one; } // t & [] = [], .* & t = t if (two.IsNothing || one.IsAnyStar) { return two; } return one.IntersectWith(two, one._builder._solver.True); } private TransitionRegex<S> IntersectWith(TransitionRegex<S> that, S pathIn) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(IntersectWith, that, pathIn); } Debug.Assert(_builder._solver.IsSatisfiable(pathIn)); #region Conditional // Intersect when this is a Conditional if (_kind == TransitionRegexKind.Conditional) { Debug.Assert(_test is not null && _first is not null && _second is not null); S thenPath = _builder._solver.And(pathIn, _test); S elsePath = _builder._solver.And(pathIn, _builder._solver.Not(_test)); if (!_builder._solver.IsSatisfiable(thenPath)) { // then case being infeasible implies that elsePath must be satisfiable return _second.IntersectWith(that, elsePath); } if (!_builder._solver.IsSatisfiable(elsePath)) { // else case is infeasible return _first.IntersectWith(that, thenPath); } TransitionRegex<S> thencase = _first.IntersectWith(that, thenPath); TransitionRegex<S> elsecase = _second.IntersectWith(that, elsePath); if (thencase == elsecase) { // Both branches result in the same thing, so the test can be omitted return thencase; } return GetOrCreate(_builder, TransitionRegexKind.Conditional, _test, thencase, elsecase, null); } // Swap the order of this and that if that is a Conditional if (that._kind == TransitionRegexKind.Conditional) { return that.IntersectWith(this, pathIn); } #endregion #region Union // Intersect when this is a Union // Use the following law of distributivity: (A|B)&C = A&C|B&C if (_kind == TransitionRegexKind.Union) { Debug.Assert(_first is not null && _second is not null); return Union(_first.IntersectWith(that, pathIn), _second.IntersectWith(that, pathIn)); } // Swap the order of this and that if that is a Union if (that._kind == TransitionRegexKind.Union) { return that.IntersectWith(this, pathIn); } #endregion #region Nullability if (_kind == TransitionRegexKind.Lookaround) { Debug.Assert(_node is not null && _first is not null && _second is not null); return Lookaround(_node, _first.IntersectWith(that, pathIn), _second.IntersectWith(that, pathIn)); } if (that._kind == TransitionRegexKind.Lookaround) { Debug.Assert(that._node is not null && that._first is not null && that._second is not null); return Lookaround(that._node, that._first.IntersectWith(this, pathIn), that._second.IntersectWith(this, pathIn)); } #endregion // Propagate intersection to the leaves Debug.Assert(_kind is TransitionRegexKind.Leaf && that._kind is TransitionRegexKind.Leaf && _node is not null && that._node is not null); return Leaf(_builder.And(_node, that._node)); } /// <summary>Union of transition regexes</summary> public static TransitionRegex<S> Union(TransitionRegex<S> one, TransitionRegex<S> two, bool ordered = false) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(Union, one, two, ordered); } // Apply common simplifications, always trying to push the operations into the leaves or to eliminate redundant branches if (one.IsNothing || two.IsAnyStar || one == two) { return two; } if (two.IsNothing || one.IsAnyStar) { return one; } if (one._kind == TransitionRegexKind.Conditional && two._kind == TransitionRegexKind.Conditional) { Debug.Assert(one._test is not null && one._first is not null && one._second is not null); Debug.Assert(two._test is not null && two._first is not null && two._second is not null); // if (psi, t1, t2) | if(psi, s1, s2) = if(psi, t1|s1, t2|s2) if (one._test.Equals(two._test)) { return Conditional(one._test, Union(one._first, two._first, ordered), Union(one._second, two._second, ordered)); } // if (psi, t, []) | if(phi, t, []) = if(psi or phi, t, []) if (one._second.IsNothing && two._second.IsNothing && one._first.Equals(two._first)) { return Conditional(one._builder._solver.Or(one._test, two._test), one._first, one._second); } } return GetOrCreate(one._builder, ordered ? TransitionRegexKind.OrderedUnion : TransitionRegexKind.Union, default(S), one, two, null); } public static TransitionRegex<S> Conditional(S test, TransitionRegex<S> thencase, TransitionRegex<S> elsecase) => (thencase == elsecase || thencase._builder._solver.True.Equals(test)) ? thencase : thencase._builder._solver.False.Equals(test) ? elsecase : GetOrCreate(thencase._builder, TransitionRegexKind.Conditional, test, thencase, elsecase, null); public static TransitionRegex<S> Lookaround(SymbolicRegexNode<S> nullabilityTest, TransitionRegex<S> thencase, TransitionRegex<S> elsecase) => (thencase == elsecase) ? thencase : GetOrCreate(thencase._builder, TransitionRegexKind.Lookaround, default(S), thencase, elsecase, nullabilityTest); public static TransitionRegex<S> Effect(TransitionRegex<S> child, DerivativeEffect effect) => child.IsNothing ? child : GetOrCreate(child._builder, TransitionRegexKind.Effect, default(S), child, null, null, effect); public override string ToString() => _kind switch { TransitionRegexKind.Leaf => $"{_node}", TransitionRegexKind.Union => $"{_first} | {_second}", TransitionRegexKind.OrderedUnion => $"{_first} || {_second}", TransitionRegexKind.Conditional => $"if({_test}, {_first}, {_second})", TransitionRegexKind.Effect => _effect?.Kind switch { DerivativeEffectKind.CaptureStart => $"captureStart({_effect?.CaptureNumber}, {_first})", _ => $"captureEnd({_effect?.CaptureNumber}, {_first})", }, _ => $"if (IsNull({_node}), {_first}, {_second})", }; #if DEBUG /// <summary>Enumerates all the paths in this transition regex excluding dead-end paths</summary> public IEnumerable<(S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>)> EnumeratePaths(S pathCondition) { switch (_kind) { case TransitionRegexKind.Leaf: Debug.Assert(_node is not null); // Omit any path that leads to a deadend if (!_node.IsNothing) { yield return (pathCondition, null, _node); } break; case TransitionRegexKind.Union: case TransitionRegexKind.OrderedUnion: Debug.Assert(_first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _first.EnumeratePaths(pathCondition)) { yield return path; } foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _second.EnumeratePaths(pathCondition)) { yield return path; } break; case TransitionRegexKind.Conditional: Debug.Assert(_test is not null && _first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _first.EnumeratePaths(_builder._solver.And(pathCondition, _test))) { yield return path; } foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _second.EnumeratePaths(_builder._solver.And(pathCondition, _builder._solver.Not(_test)))) { yield return path; } break; default: Debug.Assert(_kind is TransitionRegexKind.Lookaround && _node is not null && _first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _first.EnumeratePaths(pathCondition)) { SymbolicRegexNode<S> nullabilityTest = _node; if (path.Item2 is not null) { nullabilityTest = _builder.And(path.Item2, nullabilityTest); } yield return (path.Item1, nullabilityTest, path.Item3); } foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _second.EnumeratePaths(pathCondition)) { // Complement the nullability test SymbolicRegexNode<S> nullabilityTest = _builder.Not(_node); if (path.Item2 is not null) { nullabilityTest = _builder.And(path.Item2, nullabilityTest); } yield return (path.Item1, nullabilityTest, path.Item3); } break; } } #endif /// <summary> /// Build the union of all leaves that are reachable with the given minterm and context. /// </summary> /// <remarks> /// This version respects the difference between Union and OrderedUnion, translating them to Or and OrderedOr /// nodes respectively. /// </remarks> /// <param name="minterm">the minterm of the next character</param> /// <param name="context">the current context</param> /// <returns>a union of leaves</returns> public SymbolicRegexNode<S> TransitionOrdered(S minterm, uint context) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(TransitionOrdered, minterm, context); } switch (_kind) { case TransitionRegexKind.Leaf: Debug.Assert(_node is not null); return _node; case TransitionRegexKind.Conditional: { Debug.Assert(_test is not null && _first is not null && _second is not null); TransitionRegex<S> target = _builder._solver.IsSatisfiable(_builder._solver.And(minterm, _test)) ? _first : _second; if (!target.IsNothing) { return target.TransitionOrdered(minterm, context); } } break; case TransitionRegexKind.Union: // Observe that without Union Transition returns excatly one of the leaves Debug.Assert(_first is not null && _second is not null); return _builder.Or(_first.TransitionOrdered(minterm, context), _second.TransitionOrdered(minterm, context)); case TransitionRegexKind.OrderedUnion: // Observe that without Union Transition returns excatly one of the leaves Debug.Assert(_first is not null && _second is not null); return _builder.OrderedOr(_first.TransitionOrdered(minterm, context), _second.TransitionOrdered(minterm, context)); case TransitionRegexKind.Effect: // Effects are ignored here Debug.Assert(_first is not null && _effect is not null); return _first.TransitionOrdered(minterm, context); default: { Debug.Assert(_kind is TransitionRegexKind.Lookaround && _node is not null && _first is not null && _second is not null); // Branch according to the result of nullability TransitionRegex<S> target = _node.IsNullableFor(context) ? _first : _second; if (!target.IsNothing) { return target.TransitionOrdered(minterm, context); } } break; } return _builder._nothing; } /// <summary> /// Enumerate the leaves reachable with a given minterm and context, and collect the effects on the path to each leaf. /// Any transitions after the first unconditionally nullable one are ignored, as the backtracking engines would never /// take a path corresponding to those transitions. /// </summary> /// <param name="minterm">the minterm of the next character</param> /// <param name="context">the current context</param> /// <returns>an enumeration of pairs of leaves and the effects leading to them</returns> public IEnumerable<(SymbolicRegexNode<S>, List<DerivativeEffect>)> TransitionsWithEffects(S minterm, uint context) { // Collect all target leaves with their effects Stack<(TransitionRegex<S>, List<DerivativeEffect>)> todo = new(); todo.Push((this, new List<DerivativeEffect>())); while (todo.Count > 0) { (TransitionRegex<S> top, List<DerivativeEffect> effects) = todo.Pop(); switch (top._kind) { case TransitionRegexKind.Leaf: Debug.Assert(top._node is not null); yield return (top._node, effects); // If the leaf is nullable lower priority transitions would never get used anyway, so stop here if (top._node.IsNullable) { yield break; } break; case TransitionRegexKind.Conditional: Debug.Assert(top._test is not null && top._first is not null && top._second is not null); if (_builder._solver.IsSatisfiable(_builder._solver.And(minterm, top._test))) { if (!top._first.IsNothing) { todo.Push((top._first, new List<DerivativeEffect>(effects))); } } else { if (!top._second.IsNothing) { todo.Push((top._second, effects)); } } break; case TransitionRegexKind.Union: case TransitionRegexKind.OrderedUnion: Debug.Assert(top._first is not null && top._second is not null); todo.Push((top._second, new List<DerivativeEffect>(effects))); todo.Push((top._first, effects)); break; case TransitionRegexKind.Effect: Debug.Assert(top._first is not null && top._effect is not null); effects.Add((DerivativeEffect)top._effect); todo.Push((top._first, effects)); break; default: Debug.Assert(top._kind is TransitionRegexKind.Lookaround && top._node is not null && top._first is not null && top._second is not null); // Branch according to the result of nullability if (top._node.IsNullableFor(context)) { if (!top._first.IsNothing) { todo.Push((top._first, new List<DerivativeEffect>(effects))); } } else { if (!top._second.IsNothing) { todo.Push((top._second, effects)); } } break; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if DEBUG using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents a symbolic derivative created from a symbolic regex without using minterms</summary> internal sealed class TransitionRegex<S> where S : notnull { public readonly SymbolicRegexBuilder<S> _builder; public readonly TransitionRegexKind _kind; public readonly S? _test; public readonly TransitionRegex<S>? _first; public readonly TransitionRegex<S>? _second; public readonly SymbolicRegexNode<S>? _node; public readonly DerivativeEffect? _effect; private TransitionRegex(SymbolicRegexBuilder<S> builder, TransitionRegexKind kind, S? test, TransitionRegex<S>? first, TransitionRegex<S>? second, SymbolicRegexNode<S>? node, DerivativeEffect? effect) { Debug.Assert(builder is not null); Debug.Assert( kind is TransitionRegexKind.Leaf && node is not null && Equals(test, default(S)) && first is null && second is null && effect is null || kind is TransitionRegexKind.Conditional && test is not null && first is not null && second is not null && node is null && effect is null || kind is TransitionRegexKind.Union && Equals(test, default(S)) && first is not null && second is not null && node is null && effect is null || kind is TransitionRegexKind.Lookaround && Equals(test, default(S)) && first is not null && second is not null && node is not null && effect is null || kind is TransitionRegexKind.Effect && Equals(test, default(S)) && first is not null && second is null && node is null && effect is not null); _builder = builder; _kind = kind; _test = test; _first = first; _second = second; _node = node; _effect = effect; } private static TransitionRegex<S> GetOrCreate(SymbolicRegexBuilder<S> builder, TransitionRegexKind kind, S? test, TransitionRegex<S>? one, TransitionRegex<S>? two, SymbolicRegexNode<S>? node, DerivativeEffect? effect = null) { // Keep transition regexes internalized using the builder ref TransitionRegex<S>? tr = ref CollectionsMarshal.GetValueRefOrAddDefault(builder._trCache, (kind, test, one, two, node, effect), out _); return tr ??= new TransitionRegex<S>(builder, kind, test, one, two, node, effect); } public bool IsNothing { get { if (_kind == TransitionRegexKind.Leaf) { Debug.Assert(_node != null); return _node.IsNothing; } return false; } } public bool IsAnyStar { get { if (_kind == TransitionRegexKind.Leaf) { Debug.Assert(_node != null); return _node.IsAnyStar; } return false; } } /// <summary>Complement of transition regex</summary> public TransitionRegex<S> Complement() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(Complement); } switch (_kind) { case TransitionRegexKind.Leaf: // Complement is propagated to the leaf Debug.Assert(_node is not null); return GetOrCreate(_builder, _kind, default(S), null, null, _node._builder.Not(_node)); case TransitionRegexKind.Union: // Apply deMorgan's laws Debug.Assert(_first is not null && _second is not null); return Intersect(_first.Complement(), _second.Complement()); default: // Both Conditional and Nullability obey the same laws of propagation of complement Debug.Assert(_first is not null && _second is not null); return GetOrCreate(_builder, _kind, _test, _first.Complement(), _second.Complement(), _node); } } public static TransitionRegex<S> Leaf(SymbolicRegexNode<S> node) => GetOrCreate(node._builder, TransitionRegexKind.Leaf, default(S), null, null, node); /// <summary>Concatenate a node at the end of this transition regex</summary> public TransitionRegex<S> Concat(SymbolicRegexNode<S> node) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(Concat, node); } switch (_kind) { case TransitionRegexKind.Leaf: Debug.Assert(_node is not null); return GetOrCreate(_builder, _kind, default(S), null, null, _node._builder.CreateConcat(_node, node)); case TransitionRegexKind.Effect: Debug.Assert(_first is not null); return GetOrCreate(_builder, _kind, default(S), _first.Concat(node), null, null, _effect); default: // All other three cases are disjunctive and obey the same laws of propagation of complement Debug.Assert(_first is not null && _second is not null); return GetOrCreate(_builder, _kind, _test, _first.Concat(node), _second.Concat(node), _node); } } /// <summary>Intersection of transition regexes</summary> public static TransitionRegex<S> Intersect(TransitionRegex<S> one, TransitionRegex<S> two) { // Apply standard simplifications // [] & t = [], t & .* = t if (one.IsNothing || two.IsAnyStar || one == two) { return one; } // t & [] = [], .* & t = t if (two.IsNothing || one.IsAnyStar) { return two; } return one.IntersectWith(two, one._builder._solver.True); } private TransitionRegex<S> IntersectWith(TransitionRegex<S> that, S pathIn) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(IntersectWith, that, pathIn); } Debug.Assert(_builder._solver.IsSatisfiable(pathIn)); #region Conditional // Intersect when this is a Conditional if (_kind == TransitionRegexKind.Conditional) { Debug.Assert(_test is not null && _first is not null && _second is not null); S thenPath = _builder._solver.And(pathIn, _test); S elsePath = _builder._solver.And(pathIn, _builder._solver.Not(_test)); if (!_builder._solver.IsSatisfiable(thenPath)) { // then case being infeasible implies that elsePath must be satisfiable return _second.IntersectWith(that, elsePath); } if (!_builder._solver.IsSatisfiable(elsePath)) { // else case is infeasible return _first.IntersectWith(that, thenPath); } TransitionRegex<S> thencase = _first.IntersectWith(that, thenPath); TransitionRegex<S> elsecase = _second.IntersectWith(that, elsePath); if (thencase == elsecase) { // Both branches result in the same thing, so the test can be omitted return thencase; } return GetOrCreate(_builder, TransitionRegexKind.Conditional, _test, thencase, elsecase, null); } // Swap the order of this and that if that is a Conditional if (that._kind == TransitionRegexKind.Conditional) { return that.IntersectWith(this, pathIn); } #endregion #region Union // Intersect when this is a Union // Use the following law of distributivity: (A|B)&C = A&C|B&C if (_kind == TransitionRegexKind.Union) { Debug.Assert(_first is not null && _second is not null); return Union(_first.IntersectWith(that, pathIn), _second.IntersectWith(that, pathIn)); } // Swap the order of this and that if that is a Union if (that._kind == TransitionRegexKind.Union) { return that.IntersectWith(this, pathIn); } #endregion #region Nullability if (_kind == TransitionRegexKind.Lookaround) { Debug.Assert(_node is not null && _first is not null && _second is not null); return Lookaround(_node, _first.IntersectWith(that, pathIn), _second.IntersectWith(that, pathIn)); } if (that._kind == TransitionRegexKind.Lookaround) { Debug.Assert(that._node is not null && that._first is not null && that._second is not null); return Lookaround(that._node, that._first.IntersectWith(this, pathIn), that._second.IntersectWith(this, pathIn)); } #endregion // Propagate intersection to the leaves Debug.Assert(_kind is TransitionRegexKind.Leaf && that._kind is TransitionRegexKind.Leaf && _node is not null && that._node is not null); return Leaf(_builder.And(_node, that._node)); } /// <summary>Union of transition regexes</summary> public static TransitionRegex<S> Union(TransitionRegex<S> one, TransitionRegex<S> two) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(Union, one, two); } // Apply common simplifications, always trying to push the operations into the leaves or to eliminate redundant branches if (one.IsNothing || two.IsAnyStar || one == two) { return two; } if (two.IsNothing || one.IsAnyStar) { return one; } if (one._kind == TransitionRegexKind.Conditional && two._kind == TransitionRegexKind.Conditional) { Debug.Assert(one._test is not null && one._first is not null && one._second is not null); Debug.Assert(two._test is not null && two._first is not null && two._second is not null); // if (psi, t1, t2) | if(psi, s1, s2) = if(psi, t1|s1, t2|s2) if (one._test.Equals(two._test)) { return Conditional(one._test, Union(one._first, two._first), Union(one._second, two._second)); } // if (psi, t, []) | if(phi, t, []) = if(psi or phi, t, []) if (one._second.IsNothing && two._second.IsNothing && one._first.Equals(two._first)) { return Conditional(one._builder._solver.Or(one._test, two._test), one._first, one._second); } } return GetOrCreate(one._builder, TransitionRegexKind.Union, default(S), one, two, null); } public static TransitionRegex<S> Conditional(S test, TransitionRegex<S> thencase, TransitionRegex<S> elsecase) => (thencase == elsecase || thencase._builder._solver.True.Equals(test)) ? thencase : thencase._builder._solver.False.Equals(test) ? elsecase : GetOrCreate(thencase._builder, TransitionRegexKind.Conditional, test, thencase, elsecase, null); public static TransitionRegex<S> Lookaround(SymbolicRegexNode<S> nullabilityTest, TransitionRegex<S> thencase, TransitionRegex<S> elsecase) => (thencase == elsecase) ? thencase : GetOrCreate(thencase._builder, TransitionRegexKind.Lookaround, default(S), thencase, elsecase, nullabilityTest); public static TransitionRegex<S> Effect(TransitionRegex<S> child, DerivativeEffect effect) => child.IsNothing ? child : GetOrCreate(child._builder, TransitionRegexKind.Effect, default(S), child, null, null, effect); public override string ToString() => _kind switch { TransitionRegexKind.Leaf => $"{_node}", TransitionRegexKind.Union => $"{_first} | {_second}", TransitionRegexKind.Conditional => $"if({_test}, {_first}, {_second})", TransitionRegexKind.Effect => _effect?.Kind switch { DerivativeEffectKind.CaptureStart => $"captureStart({_effect?.CaptureNumber}, {_first})", _ => $"captureEnd({_effect?.CaptureNumber}, {_first})", }, _ => $"if (IsNull({_node}), {_first}, {_second})", }; /// <summary>Enumerates all the paths in this transition regex excluding dead-end paths</summary> public IEnumerable<(S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>)> EnumeratePaths(S pathCondition) { switch (_kind) { case TransitionRegexKind.Leaf: Debug.Assert(_node is not null); // Omit any path that leads to a deadend if (!_node.IsNothing) { yield return (pathCondition, null, _node); } break; case TransitionRegexKind.Union: Debug.Assert(_first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _first.EnumeratePaths(pathCondition)) { yield return path; } foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _second.EnumeratePaths(pathCondition)) { yield return path; } break; case TransitionRegexKind.Conditional: Debug.Assert(_test is not null && _first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _first.EnumeratePaths(_builder._solver.And(pathCondition, _test))) { yield return path; } foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _second.EnumeratePaths(_builder._solver.And(pathCondition, _builder._solver.Not(_test)))) { yield return path; } break; default: Debug.Assert(_kind is TransitionRegexKind.Lookaround && _node is not null && _first is not null && _second is not null); foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _first.EnumeratePaths(pathCondition)) { SymbolicRegexNode<S> nullabilityTest = _node; if (path.Item2 is not null) { nullabilityTest = _builder.And(path.Item2, nullabilityTest); } yield return (path.Item1, nullabilityTest, path.Item3); } foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in _second.EnumeratePaths(pathCondition)) { // Complement the nullability test SymbolicRegexNode<S> nullabilityTest = _builder.Not(_node); if (path.Item2 is not null) { nullabilityTest = _builder.And(path.Item2, nullabilityTest); } yield return (path.Item1, nullabilityTest, path.Item3); } break; } } } } #endif
1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/TransitionRegexKind.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.RegularExpressions.Symbolic { /// <summary>Kinds of transition regexes. Transition regexes maintain a DNF form that pushes all intersections and complements to the leaves.</summary> internal enum TransitionRegexKind { Leaf, Conditional, Union, OrderedUnion, Lookaround, Effect } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if DEBUG namespace System.Text.RegularExpressions.Symbolic { /// <summary>Kinds of transition regexes. Transition regexes maintain a DNF form that pushes all intersections and complements to the leaves.</summary> internal enum TransitionRegexKind { Leaf, Conditional, Union, Lookaround, Effect } } #endif
1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Text.RegularExpressions/src/System/Threading/StackHelper.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.Runtime.CompilerServices; using System.Threading.Tasks; namespace System.Threading { /// <summary>Provides tools for avoiding stack overflows.</summary> internal static class StackHelper { /// <summary>Tries to ensure there is sufficient stack to execute the average .NET function.</summary> public static bool TryEnsureSufficientExecutionStack() { #if REGEXGENERATOR try { RuntimeHelpers.EnsureSufficientExecutionStack(); return true; } catch { return false; } #else return RuntimeHelpers.TryEnsureSufficientExecutionStack(); #endif } // Queues the supplied delegate to the thread pool, then block waiting for it to complete. // It does so in a way that prevents task inlining (which would defeat the purpose) but that // also plays nicely with the thread pool's sync-over-async aggressive thread injection policies. /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1>(Action<TArg1> action, TArg1 arg1) => Task.Run(() => action(arg1)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2>(Action<TArg1, TArg2> action, TArg1 arg1, TArg2 arg2) => Task.Run(() => action(arg1, arg2)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> /// <param name="arg3">The second argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2, TArg3>(Action<TArg1, TArg2, TArg3> action, TArg1 arg1, TArg2 arg2, TArg3 arg3) => Task.Run(() => action(arg1, arg2, arg3)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> public static TResult CallOnEmptyStack<TResult>(Func<TResult> func) => Task.Run(() => func()) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TResult>(Func<TArg1, TResult> func, TArg1 arg1) => Task.Run(() => func(arg1)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> /// <param name="arg2">The second argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TArg2, TResult>(Func<TArg1, TArg2, TResult> func, TArg1 arg1, TArg2 arg2) => Task.Run(() => func(arg1, arg2)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> /// <param name="arg2">The second argument to pass to the function.</param> /// <param name="arg3">The third argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TArg2, TArg3, TResult>(Func<TArg1, TArg2, TArg3, TResult> func, TArg1 arg1, TArg2 arg2, TArg3 arg3) => Task.Run(() => func(arg1, arg2, arg3)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace System.Threading { /// <summary>Provides tools for avoiding stack overflows.</summary> internal static class StackHelper { /// <summary>Tries to ensure there is sufficient stack to execute the average .NET function.</summary> public static bool TryEnsureSufficientExecutionStack() { #if REGEXGENERATOR try { RuntimeHelpers.EnsureSufficientExecutionStack(); return true; } catch { return false; } #else return RuntimeHelpers.TryEnsureSufficientExecutionStack(); #endif } // Queues the supplied delegate to the thread pool, then block waiting for it to complete. // It does so in a way that prevents task inlining (which would defeat the purpose) but that // also plays nicely with the thread pool's sync-over-async aggressive thread injection policies. /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1>(Action<TArg1> action, TArg1 arg1) => Task.Run(() => action(arg1)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2>(Action<TArg1, TArg2> action, TArg1 arg1, TArg2 arg2) => Task.Run(() => action(arg1, arg2)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> /// <param name="arg3">The third argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2, TArg3>(Action<TArg1, TArg2, TArg3> action, TArg1 arg1, TArg2 arg2, TArg3 arg3) => Task.Run(() => action(arg1, arg2, arg3)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <typeparam name="TArg4">The type of the fourth argument to pass to the function.</typeparam> /// <typeparam name="TArg5">The type of the fifth argument to pass to the function.</typeparam> /// <typeparam name="TArg6">The type of the sixth argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> /// <param name="arg3">The third argument to pass to the action.</param> /// <param name="arg4">The fourth argument to pass to the action.</param> /// <param name="arg5">The fifth argument to pass to the action.</param> /// <param name="arg6">The sixth argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>(Action<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6> action, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6) => Task.Run(() => action(arg1, arg2, arg3, arg4, arg5, arg6)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> public static TResult CallOnEmptyStack<TResult>(Func<TResult> func) => Task.Run(() => func()) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TResult>(Func<TArg1, TResult> func, TArg1 arg1) => Task.Run(() => func(arg1)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> /// <param name="arg2">The second argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TArg2, TResult>(Func<TArg1, TArg2, TResult> func, TArg1 arg1, TArg2 arg2) => Task.Run(() => func(arg1, arg2)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> /// <param name="arg2">The second argument to pass to the function.</param> /// <param name="arg3">The third argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TArg2, TArg3, TResult>(Func<TArg1, TArg2, TArg3, TResult> func, TArg1 arg1, TArg2 arg2, TArg3 arg3) => Task.Run(() => func(arg1, arg2, arg3)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); } }
1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/StringSequence.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.Numerics; using System.Runtime.InteropServices; namespace System.Diagnostics.Metrics { internal partial struct StringSequence1 : IEquatable<StringSequence1>, IStringSequence { public string Value1; public StringSequence1(string value1) { Value1 = value1; } public override int GetHashCode() => Value1.GetHashCode(); public bool Equals(StringSequence1 other) { return Value1 == other.Value1; } //GetHashCode() is in the platform specific files public override bool Equals(object? obj) { return obj is StringSequence1 ss1 && Equals(ss1); } } internal partial struct StringSequence2 : IEquatable<StringSequence2>, IStringSequence { public string Value1; public string Value2; public StringSequence2(string value1, string value2) { Value1 = value1; Value2 = value2; } public bool Equals(StringSequence2 other) { return Value1 == other.Value1 && Value2 == other.Value2; } //GetHashCode() is in the platform specific files public override bool Equals(object? obj) { return obj is StringSequence2 ss2 && Equals(ss2); } } internal partial struct StringSequence3 : IEquatable<StringSequence3>, IStringSequence { public string Value1; public string Value2; public string Value3; public StringSequence3(string value1, string value2, string value3) { Value1 = value1; Value2 = value2; Value3 = value3; } public bool Equals(StringSequence3 other) { return Value1 == other.Value1 && Value2 == other.Value2 && Value3 == other.Value3; } //GetHashCode() is in the platform specific files public override bool Equals(object? obj) { return obj is StringSequence3 ss3 && Equals(ss3); } } internal partial struct StringSequenceMany : IEquatable<StringSequenceMany>, IStringSequence { private readonly string[] _values; public StringSequenceMany(string[] values) { _values = values; } public Span<string> AsSpan() { return _values.AsSpan(); } public bool Equals(StringSequenceMany other) { if (_values.Length != other._values.Length) { return false; } for (int i = 0; i < _values.Length; i++) { if (_values[i] != other._values[i]) { return false; } } return true; } //GetHashCode() is in the platform specific files public override bool Equals(object? obj) { return obj is StringSequenceMany ssm && Equals(ssm); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Numerics; using System.Runtime.InteropServices; namespace System.Diagnostics.Metrics { internal partial struct StringSequence1 : IEquatable<StringSequence1>, IStringSequence { public string Value1; public StringSequence1(string value1) { Value1 = value1; } public override int GetHashCode() => Value1.GetHashCode(); public bool Equals(StringSequence1 other) { return Value1 == other.Value1; } //GetHashCode() is in the platform specific files public override bool Equals(object? obj) { return obj is StringSequence1 ss1 && Equals(ss1); } } internal partial struct StringSequence2 : IEquatable<StringSequence2>, IStringSequence { public string Value1; public string Value2; public StringSequence2(string value1, string value2) { Value1 = value1; Value2 = value2; } public bool Equals(StringSequence2 other) { return Value1 == other.Value1 && Value2 == other.Value2; } //GetHashCode() is in the platform specific files public override bool Equals(object? obj) { return obj is StringSequence2 ss2 && Equals(ss2); } } internal partial struct StringSequence3 : IEquatable<StringSequence3>, IStringSequence { public string Value1; public string Value2; public string Value3; public StringSequence3(string value1, string value2, string value3) { Value1 = value1; Value2 = value2; Value3 = value3; } public bool Equals(StringSequence3 other) { return Value1 == other.Value1 && Value2 == other.Value2 && Value3 == other.Value3; } //GetHashCode() is in the platform specific files public override bool Equals(object? obj) { return obj is StringSequence3 ss3 && Equals(ss3); } } internal partial struct StringSequenceMany : IEquatable<StringSequenceMany>, IStringSequence { private readonly string[] _values; public StringSequenceMany(string[] values) { _values = values; } public Span<string> AsSpan() { return _values.AsSpan(); } public bool Equals(StringSequenceMany other) { if (_values.Length != other._values.Length) { return false; } for (int i = 0; i < _values.Length; i++) { if (_values[i] != other._values[i]) { return false; } } return true; } //GetHashCode() is in the platform specific files public override bool Equals(object? obj) { return obj is StringSequenceMany ssm && Equals(ssm); } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Configuration.ConfigurationManager/tests/System/Configuration/KeyValueConfigurationCollectionTests.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.Configuration; using Xunit; namespace System.ConfigurationTests { public class KeyValueConfigurationCollectionTests { [Fact] public void MsdnRootSample() { // https://msdn.microsoft.com/en-us/library/system.configuration.keyvalueconfigurationcollection(v=vs.110).aspx using (var temp = new TempConfig(TestData.EmptyConfig)) { var config = ConfigurationManager.OpenExeConfiguration(temp.ExePath); AppSettingsSection configSection = (AppSettingsSection)config.GetSection("appSettings"); Assert.Equal("appSettings", configSection.SectionInformation.Name); KeyValueConfigurationElement myAdminKeyVal = new KeyValueConfigurationElement("myAdminTool", "admin.aspx"); KeyValueConfigurationCollection configSettings = config.AppSettings.Settings; Assert.Equal(0, configSettings.AllKeys.Length); config.AppSettings.Settings.Add(myAdminKeyVal); Assert.False(configSection.SectionInformation.IsLocked); config.Save(); KeyValueConfigurationCollection settings = config.AppSettings.Settings; foreach (KeyValueConfigurationElement keyValueElement in settings) { Assert.Equal("myAdminTool", keyValueElement.Key); Assert.Equal("admin.aspx", keyValueElement.Value); } } } [Fact] public void CollectionTypeIsAddRemoveMap() { Assert.Equal(ConfigurationElementCollectionType.AddRemoveClearMap, new KeyValueConfigurationCollection().CollectionType); } [Fact] public void ThrowOnDuplicateIsFalse() { Assert.False(new TestKeyValueCollection().TestThrowOnDuplicate); } [Fact] public void CreateNewElement() { var element = new TestKeyValueCollection().TestCreateNewElement(); Assert.IsType<KeyValueConfigurationElement>(element); Assert.Equal("", ((KeyValueConfigurationElement)element).Key); Assert.Equal("", ((KeyValueConfigurationElement)element).Value); } [Fact] public void EmptyAllKeys() { Assert.Equal(0, new KeyValueConfigurationCollection().AllKeys.Length); } [Fact] public void AddNullKeyValueThrows() { Assert.Throws<ConfigurationErrorsException>(() => new KeyValueConfigurationCollection().Add(null, null)); } [Fact] public void AddNullKeyValueElementThrows() { var element = new KeyValueConfigurationElement(null, null); Assert.Throws<ConfigurationErrorsException>(() => new KeyValueConfigurationCollection().Add(element)); } [Fact] public void AddNullKeyThrows() { Assert.Throws<ConfigurationErrorsException>(() => new KeyValueConfigurationCollection().Add(null, "foo")); } [Fact] public void AddNullValue() { var collection = new KeyValueConfigurationCollection(); collection.Add("foo", null); Assert.Null(collection["foo"].Value); } [Fact] public void AddOverValue() { var collection = new KeyValueConfigurationCollection(); collection.Add("foo", "foo"); Assert.Equal("foo", collection["foo"].Value); collection.Add("foo", "bar"); Assert.Equal("foo,bar", collection["foo"].Value); } [Fact] public void ModifyElementValue() { var collection = new KeyValueConfigurationCollection(); collection.Add("foo", "foo"); collection["foo"].Value = "bar"; Assert.Equal("bar", collection["foo"].Value); } [Fact] public void RemoveKey() { var collection = new KeyValueConfigurationCollection(); collection.Add("foo", "foo"); Assert.Equal("foo", collection["foo"].Value); collection.Remove("foo"); Assert.Null(collection["foo"]); } [Fact] public void Clear() { var collection = new KeyValueConfigurationCollection(); collection.Add("foo", "foo"); Assert.Equal("foo", collection["foo"].Value); collection.Clear(); Assert.Null(collection["foo"]); } private class TestKeyValueCollection : KeyValueConfigurationCollection { public bool TestThrowOnDuplicate => ThrowOnDuplicate; public ConfigurationElement TestCreateNewElement() => CreateNewElement(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Configuration; using Xunit; namespace System.ConfigurationTests { public class KeyValueConfigurationCollectionTests { [Fact] public void MsdnRootSample() { // https://msdn.microsoft.com/en-us/library/system.configuration.keyvalueconfigurationcollection(v=vs.110).aspx using (var temp = new TempConfig(TestData.EmptyConfig)) { var config = ConfigurationManager.OpenExeConfiguration(temp.ExePath); AppSettingsSection configSection = (AppSettingsSection)config.GetSection("appSettings"); Assert.Equal("appSettings", configSection.SectionInformation.Name); KeyValueConfigurationElement myAdminKeyVal = new KeyValueConfigurationElement("myAdminTool", "admin.aspx"); KeyValueConfigurationCollection configSettings = config.AppSettings.Settings; Assert.Equal(0, configSettings.AllKeys.Length); config.AppSettings.Settings.Add(myAdminKeyVal); Assert.False(configSection.SectionInformation.IsLocked); config.Save(); KeyValueConfigurationCollection settings = config.AppSettings.Settings; foreach (KeyValueConfigurationElement keyValueElement in settings) { Assert.Equal("myAdminTool", keyValueElement.Key); Assert.Equal("admin.aspx", keyValueElement.Value); } } } [Fact] public void CollectionTypeIsAddRemoveMap() { Assert.Equal(ConfigurationElementCollectionType.AddRemoveClearMap, new KeyValueConfigurationCollection().CollectionType); } [Fact] public void ThrowOnDuplicateIsFalse() { Assert.False(new TestKeyValueCollection().TestThrowOnDuplicate); } [Fact] public void CreateNewElement() { var element = new TestKeyValueCollection().TestCreateNewElement(); Assert.IsType<KeyValueConfigurationElement>(element); Assert.Equal("", ((KeyValueConfigurationElement)element).Key); Assert.Equal("", ((KeyValueConfigurationElement)element).Value); } [Fact] public void EmptyAllKeys() { Assert.Equal(0, new KeyValueConfigurationCollection().AllKeys.Length); } [Fact] public void AddNullKeyValueThrows() { Assert.Throws<ConfigurationErrorsException>(() => new KeyValueConfigurationCollection().Add(null, null)); } [Fact] public void AddNullKeyValueElementThrows() { var element = new KeyValueConfigurationElement(null, null); Assert.Throws<ConfigurationErrorsException>(() => new KeyValueConfigurationCollection().Add(element)); } [Fact] public void AddNullKeyThrows() { Assert.Throws<ConfigurationErrorsException>(() => new KeyValueConfigurationCollection().Add(null, "foo")); } [Fact] public void AddNullValue() { var collection = new KeyValueConfigurationCollection(); collection.Add("foo", null); Assert.Null(collection["foo"].Value); } [Fact] public void AddOverValue() { var collection = new KeyValueConfigurationCollection(); collection.Add("foo", "foo"); Assert.Equal("foo", collection["foo"].Value); collection.Add("foo", "bar"); Assert.Equal("foo,bar", collection["foo"].Value); } [Fact] public void ModifyElementValue() { var collection = new KeyValueConfigurationCollection(); collection.Add("foo", "foo"); collection["foo"].Value = "bar"; Assert.Equal("bar", collection["foo"].Value); } [Fact] public void RemoveKey() { var collection = new KeyValueConfigurationCollection(); collection.Add("foo", "foo"); Assert.Equal("foo", collection["foo"].Value); collection.Remove("foo"); Assert.Null(collection["foo"]); } [Fact] public void Clear() { var collection = new KeyValueConfigurationCollection(); collection.Add("foo", "foo"); Assert.Equal("foo", collection["foo"].Value); collection.Clear(); Assert.Null(collection["foo"]); } private class TestKeyValueCollection : KeyValueConfigurationCollection { public bool TestThrowOnDuplicate => ThrowOnDuplicate; public ConfigurationElement TestCreateNewElement() => CreateNewElement(); } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Drawing.Common/src/System/Drawing/Printing/InvalidPrinterException.Serializable.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 isn't built into the .csproj in the runtime libraries but is consumed by Mono. using System.Runtime.Serialization; namespace System.Drawing.Printing { partial class InvalidPrinterException { protected InvalidPrinterException(SerializationInfo info, StreamingContext context) : base(info, context) { _settings = (PrinterSettings)info.GetValue("settings", typeof(PrinterSettings)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("settings", _settings); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This file isn't built into the .csproj in the runtime libraries but is consumed by Mono. using System.Runtime.Serialization; namespace System.Drawing.Printing { partial class InvalidPrinterException { protected InvalidPrinterException(SerializationInfo info, StreamingContext context) : base(info, context) { _settings = (PrinterSettings)info.GetValue("settings", typeof(PrinterSettings)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("settings", _settings); } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Private.Xml/src/System/Xml/Serialization/ContextAwareTables.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.Xml.Serialization { using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.Loader; internal class ContextAwareTables<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]T> where T : class? { private Hashtable _defaultTable; private ConditionalWeakTable<Type, T> _collectibleTable; public ContextAwareTables() { _defaultTable = new Hashtable(); _collectibleTable = new ConditionalWeakTable<Type, T>(); } internal T GetOrCreateValue(Type t, Func<T> f) { // The fast and most common default case T? ret = (T?)_defaultTable[t]; if (ret != null) return ret; // Common case for collectible contexts if (_collectibleTable.TryGetValue(t, out ret)) return ret; // Not found. Do the slower work of creating the value in the correct collection. AssemblyLoadContext? alc = AssemblyLoadContext.GetLoadContext(t.Assembly); // Null and non-collectible load contexts use the default table if (alc == null || !alc.IsCollectible) { lock (_defaultTable) { if ((ret = (T?)_defaultTable[t]) == null) { ret = f(); _defaultTable[t] = ret; } } } // Collectible load contexts should use the ConditionalWeakTable so they can be unloaded else { lock (_collectibleTable) { if (!_collectibleTable.TryGetValue(t, out ret)) { ret = f(); _collectibleTable.AddOrUpdate(t, ret); } } } return ret; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Serialization { using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.Loader; internal class ContextAwareTables<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]T> where T : class? { private Hashtable _defaultTable; private ConditionalWeakTable<Type, T> _collectibleTable; public ContextAwareTables() { _defaultTable = new Hashtable(); _collectibleTable = new ConditionalWeakTable<Type, T>(); } internal T GetOrCreateValue(Type t, Func<T> f) { // The fast and most common default case T? ret = (T?)_defaultTable[t]; if (ret != null) return ret; // Common case for collectible contexts if (_collectibleTable.TryGetValue(t, out ret)) return ret; // Not found. Do the slower work of creating the value in the correct collection. AssemblyLoadContext? alc = AssemblyLoadContext.GetLoadContext(t.Assembly); // Null and non-collectible load contexts use the default table if (alc == null || !alc.IsCollectible) { lock (_defaultTable) { if ((ret = (T?)_defaultTable[t]) == null) { ret = f(); _defaultTable[t] = ret; } } } // Collectible load contexts should use the ConditionalWeakTable so they can be unloaded else { lock (_collectibleTable) { if (!_collectibleTable.TryGetValue(t, out ret)) { ret = f(); _collectibleTable.AddOrUpdate(t, ret); } } } return ret; } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.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.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Xml; namespace System.Security.Cryptography.Xml { /// <summary> /// Trace support for debugging issues signing and verifying XML signatures. /// </summary> internal static class SignedXmlDebugLog { // // In order to enable XML digital signature debug loggging, applications should setup their config // file to be similar to the following: // // <configuration> // <system.diagnostics> // <sources> // <source name="System.Security.Cryptography.Xml.SignedXml" // switchName="XmlDsigLogSwitch"> // <listeners> // <add name="logFile" /> // </listeners> // </source> // </sources> // <switches> // <add name="XmlDsigLogSwitch" value="Verbose" /> // </switches> // <sharedListeners> // <add name="logFile" // type="System.Diagnostics.TextWriterTraceListener" // initializeData="XmlDsigLog.txt"/> // </sharedListeners> // <trace autoflush="true"> // <listeners> // <add name="logFile" /> // </listeners> // </trace> // </system.diagnostics> // </configuration> // private const string NullString = "(null)"; private static readonly TraceSource s_traceSource = new TraceSource("System.Security.Cryptography.Xml.SignedXml"); private static volatile bool s_haveVerboseLogging; private static volatile bool s_verboseLogging; private static volatile bool s_haveInformationLogging; private static volatile bool s_informationLogging; /// <summary> /// Types of events that are logged to the debug log /// </summary> internal enum SignedXmlDebugEvent { /// <summary> /// Canonicalization of input XML has begun /// </summary> BeginCanonicalization, /// <summary> /// Verification of the signature format itself is beginning /// </summary> BeginCheckSignatureFormat, /// <summary> /// Verification of a signed info is beginning /// </summary> BeginCheckSignedInfo, /// <summary> /// Signing is beginning /// </summary> BeginSignatureComputation, /// <summary> /// Signature verification is beginning /// </summary> BeginSignatureVerification, /// <summary> /// Input data has been transformed to its canonicalized form /// </summary> CanonicalizedData, /// <summary> /// The result of signature format validation /// </summary> FormatValidationResult, /// <summary> /// Namespaces are being propigated into the signature /// </summary> NamespacePropagation, /// <summary> /// Output from a Reference /// </summary> ReferenceData, /// <summary> /// The result of a signature verification /// </summary> SignatureVerificationResult, /// <summary> /// Calculating the final signature /// </summary> Signing, /// <summary> /// A reference is being hashed /// </summary> SigningReference, /// <summary> /// A signature has failed to verify /// </summary> VerificationFailure, /// <summary> /// Verify that a reference has the correct hash value /// </summary> VerifyReference, /// <summary> /// Verification is processing the SignedInfo section of the signature /// </summary> VerifySignedInfo, /// <summary> /// Verification status on the x.509 certificate in use /// </summary> X509Verification, /// <summary> /// The signature is being rejected by the signature format verifier due to having /// a canonicalization algorithm which is not on the known valid list. /// </summary> UnsafeCanonicalizationMethod, /// <summary> /// The signature is being rejected by the signature verifier due to having /// a transform algorithm which is not on the known valid list. /// </summary> UnsafeTransformMethod, } /// <summary> /// Check to see if logging should be done in this process /// </summary> private static bool InformationLoggingEnabled { get { if (!s_haveInformationLogging) { s_informationLogging = s_traceSource.Switch.ShouldTrace(TraceEventType.Information); s_haveInformationLogging = true; } return s_informationLogging; } } /// <summary> /// Check to see if verbose log messages should be generated /// </summary> private static bool VerboseLoggingEnabled { get { if (!s_haveVerboseLogging) { s_verboseLogging = s_traceSource.Switch.ShouldTrace(TraceEventType.Verbose); s_haveVerboseLogging = true; } return s_verboseLogging; } } /// <summary> /// Convert the byte array into a hex string /// </summary> private static string FormatBytes(byte[] bytes) { if (bytes == null) return NullString; return HexConverter.ToString(bytes, HexConverter.Casing.Lower); } /// <summary> /// Map a key to a string describing the key /// </summary> private static string GetKeyName(object key) { Debug.Assert(key != null, "key != null"); ICspAsymmetricAlgorithm cspKey = key as ICspAsymmetricAlgorithm; X509Certificate certificate = key as X509Certificate; X509Certificate2 certificate2 = key as X509Certificate2; // // Use the following sources for key names, if available: // // * CAPI key -> key container name // * X509Certificate2 -> subject simple name // * X509Certificate -> subject name // * All others -> hash code // string keyName; #pragma warning disable CA1416 // This call site is reachable on all platforms. 'CspKeyContainerInfo.KeyContainerName' is supported on: 'windows'. if (cspKey != null && cspKey.CspKeyContainerInfo.KeyContainerName != null) { keyName = "\"" + cspKey.CspKeyContainerInfo.KeyContainerName + "\""; } #pragma warning restore CA1416 else if (certificate2 != null) { keyName = "\"" + certificate2.GetNameInfo(X509NameType.SimpleName, false) + "\""; } else if (certificate != null) { keyName = "\"" + certificate.Subject + "\""; } else { keyName = key.GetHashCode().ToString("x8", CultureInfo.InvariantCulture); } return $"{key.GetType().Name}#{keyName}"; } /// <summary> /// Map an object to a string describing the object /// </summary> private static string GetObjectId(object o) { Debug.Assert(o != null, "o != null"); return $"{o.GetType().Name}#{o.GetHashCode():x8}"; } /// <summary> /// Map an OID to the friendliest name possible /// </summary> private static string GetOidName(Oid oid) { Debug.Assert(oid != null, "oid != null"); string friendlyName = oid.FriendlyName; if (string.IsNullOrEmpty(friendlyName)) friendlyName = oid.Value; return friendlyName; } /// <summary> /// Log that canonicalization has begun on input data /// </summary> /// <param name="signedXml">SignedXml object doing the signing or verification</param> /// <param name="canonicalizationTransform">transform canonicalizing the input</param> internal static void LogBeginCanonicalization(SignedXml signedXml, Transform canonicalizationTransform) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_BeginCanonicalization, canonicalizationTransform.Algorithm, canonicalizationTransform.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCanonicalization, logMessage); } if (VerboseLoggingEnabled) { string canonicalizationSettings = SR.Format(CultureInfo.InvariantCulture, SR.Log_CanonicalizationSettings, canonicalizationTransform.Resolver.GetType(), canonicalizationTransform.BaseURI); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginCanonicalization, canonicalizationSettings); } } /// <summary> /// Log that we're going to be validating the signature format itself /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="formatValidator">Callback delegate which is being used for format verification</param> internal static void LogBeginCheckSignatureFormat(SignedXml signedXml, Func<SignedXml, bool> formatValidator) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(formatValidator != null, "formatValidator != null"); if (InformationLoggingEnabled) { MethodInfo validationMethod = formatValidator.Method; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_CheckSignatureFormat, validationMethod.Module.Assembly.FullName, validationMethod.DeclaringType.FullName, validationMethod.Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignatureFormat, logMessage); } } /// <summary> /// Log that checking SignedInfo is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="signedInfo">SignedInfo object being verified</param> internal static void LogBeginCheckSignedInfo(SignedXml signedXml, SignedInfo signedInfo) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signedInfo != null, " signedInfo != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_CheckSignedInfo, signedInfo.Id != null ? signedInfo.Id : NullString); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignedInfo, logMessage); } } /// <summary> /// Log that signature computation is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the signing</param> /// <param name="context">Context of the signature</param> internal static void LogBeginSignatureComputation(SignedXml signedXml, XmlElement context) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginSignatureComputation, SR.Log_BeginSignatureComputation); } if (VerboseLoggingEnabled) { string contextData = SR.Format(CultureInfo.InvariantCulture, SR.Log_XmlContext, context != null ? context.OuterXml : NullString); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginSignatureComputation, contextData); } } /// <summary> /// Log that signature verification is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="context">Context of the verification</param> internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlElement context) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginSignatureVerification, SR.Log_BeginSignatureVerification); } if (VerboseLoggingEnabled) { string contextData = SR.Format(CultureInfo.InvariantCulture, SR.Log_XmlContext, context != null ? context.OuterXml : NullString); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginSignatureVerification, contextData); } } /// <summary> /// Log the canonicalized data /// </summary> /// <param name="signedXml">SignedXml object doing the signing or verification</param> /// <param name="canonicalizationTransform">transform canonicalizing the input</param> internal static void LogCanonicalizedOutput(SignedXml signedXml, Transform canonicalizationTransform) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null"); if (VerboseLoggingEnabled) { using (StreamReader reader = new StreamReader(canonicalizationTransform.GetOutput(typeof(Stream)) as Stream)) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_CanonicalizedOutput, reader.ReadToEnd()); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.CanonicalizedData, logMessage); } } } /// <summary> /// Log that the signature format callback has rejected the signature /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="result">result of the signature format verification</param> internal static void LogFormatValidationResult(SignedXml signedXml, bool result) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { string logMessage = result ? SR.Log_FormatValidationSuccessful : SR.Log_FormatValidationNotSuccessful; WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.FormatValidationResult, logMessage); } } /// <summary> /// Log that a signature is being rejected as having an invalid format due to its canonicalization /// algorithm not being on the valid list. /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="algorithm">Canonicalization algorithm</param> /// <param name="validAlgorithms">List of valid canonicalization algorithms</param> internal static void LogUnsafeCanonicalizationMethod(SignedXml signedXml, string algorithm, IEnumerable<string> validAlgorithms) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(validAlgorithms != null, "validAlgorithms != null"); if (InformationLoggingEnabled) { StringBuilder validAlgorithmBuilder = new StringBuilder(); foreach (string validAlgorithm in validAlgorithms) { if (validAlgorithmBuilder.Length != 0) { validAlgorithmBuilder.Append(", "); } validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm); } string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_UnsafeCanonicalizationMethod, algorithm, validAlgorithmBuilder.ToString()); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.UnsafeCanonicalizationMethod, logMessage); } } /// <summary> /// Log that a signature is being rejected as having an invalid signature due to a transform /// algorithm not being on the valid list. /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="algorithm">Transform algorithm that was not allowed</param> /// <param name="validC14nAlgorithms">The valid C14N algorithms</param> /// <param name="validTransformAlgorithms">The valid C14N algorithms</param> internal static void LogUnsafeTransformMethod( SignedXml signedXml, string algorithm, IEnumerable<string> validC14nAlgorithms, IEnumerable<string> validTransformAlgorithms) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(validC14nAlgorithms != null, "validC14nAlgorithms != null"); Debug.Assert(validTransformAlgorithms != null, "validTransformAlgorithms != null"); if (InformationLoggingEnabled) { StringBuilder validAlgorithmBuilder = new StringBuilder(); foreach (string validAlgorithm in validC14nAlgorithms) { if (validAlgorithmBuilder.Length != 0) { validAlgorithmBuilder.Append(", "); } validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm); } foreach (string validAlgorithm in validTransformAlgorithms) { if (validAlgorithmBuilder.Length != 0) { validAlgorithmBuilder.Append(", "); } validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm); } string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_UnsafeTransformMethod, algorithm, validAlgorithmBuilder.ToString()); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.UnsafeTransformMethod, logMessage); } } /// <summary> /// Log namespaces which are being propagated into the signature /// </summary> /// <param name="signedXml">SignedXml doing the signing or verification</param> /// <param name="namespaces">namespaces being propagated</param> internal static void LogNamespacePropagation(SignedXml signedXml, XmlNodeList namespaces) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { if (namespaces != null) { foreach (XmlAttribute propagatedNamespace in namespaces) { string propagationMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_PropagatingNamespace, propagatedNamespace.Name, propagatedNamespace.Value); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.NamespacePropagation, propagationMessage); } } else { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.NamespacePropagation, SR.Log_NoNamespacesPropagated); } } } /// <summary> /// Log the output of a reference /// </summary> /// <param name="reference">The reference being processed</param> /// <param name="data">Stream containing the output of the reference</param> /// <returns>Stream containing the output of the reference</returns> internal static Stream LogReferenceData(Reference reference, Stream data) { if (VerboseLoggingEnabled) { // // Since the input data stream could be from the network or another source that does not // support rewinding, we will read the stream into a temporary MemoryStream that can be used // to stringify the output and also return to the reference so that it can produce the hash // value. // MemoryStream ms = new MemoryStream(); // First read the input stream into our temporary stream byte[] buffer = new byte[4096]; int readBytes; do { readBytes = data.Read(buffer, 0, buffer.Length); ms.Write(buffer, 0, readBytes); } while (readBytes == buffer.Length); // Log out information about it string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_TransformedReferenceContents, Encoding.UTF8.GetString(ms.ToArray())); WriteLine(reference, TraceEventType.Verbose, SignedXmlDebugEvent.ReferenceData, logMessage); // Rewind to the beginning, so that the entire input stream is hashed ms.Seek(0, SeekOrigin.Begin); return ms; } else { return data; } } /// <summary> /// Log the computation of a signature value when signing with an asymmetric algorithm /// </summary> /// <param name="signedXml">SignedXml object calculating the signature</param> /// <param name="key">key used for signing</param> /// <param name="signatureDescription">signature description being used to create the signature</param> /// <param name="hash">hash algorithm used to digest the output</param> /// <param name="asymmetricSignatureFormatter">signature formatter used to do the signing</param> internal static void LogSigning(SignedXml signedXml, object key, SignatureDescription signatureDescription, HashAlgorithm hash, AsymmetricSignatureFormatter asymmetricSignatureFormatter) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hash != null, "hash != null"); Debug.Assert(asymmetricSignatureFormatter != null, "asymmetricSignatureFormatter != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SigningAsymmetric, GetKeyName(key), signatureDescription.GetType().Name, hash.GetType().Name, asymmetricSignatureFormatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, logMessage); } } /// <summary> /// Log the computation of a signature value when signing with a keyed hash algorithm /// </summary> /// <param name="signedXml">SignedXml object calculating the signature</param> /// <param name="key">key the signature is created with</param> internal static void LogSigning(SignedXml signedXml, KeyedHashAlgorithm key) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(key != null, "key != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SigningHmac, key.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, logMessage); } } /// <summary> /// Log the calculation of a hash value of a reference /// </summary> /// <param name="signedXml">SignedXml object driving the signature</param> /// <param name="reference">Reference being hashed</param> internal static void LogSigningReference(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (VerboseLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SigningReference, GetObjectId(reference), reference.Uri, reference.Id, reference.Type, reference.DigestMethod, hashAlgorithmName); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.SigningReference, logMessage); } } /// <summary> /// Log the specific point where a signature is determined to not be verifiable /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="failureLocation">location that the signature was determined to be invalid</param> internal static void LogVerificationFailure(SignedXml signedXml, string failureLocation) { if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerificationFailed, failureLocation); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerificationFailure, logMessage); } } /// <summary> /// Log the success or failure of a signature verification operation /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">public key used to verify the signature</param> /// <param name="verified">true if the signature verified, false otherwise</param> internal static void LogVerificationResult(SignedXml signedXml, object key, bool verified) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(key != null, "key != null"); if (InformationLoggingEnabled) { string resource = verified ? SR.Log_VerificationWithKeySuccessful : SR.Log_VerificationWithKeyNotSuccessful; string logMessage = string.Format(CultureInfo.InvariantCulture, resource, GetKeyName(key)); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.SignatureVerificationResult, logMessage); } } /// <summary> /// Log the check for appropriate X509 key usage /// </summary> /// <param name="signedXml">SignedXml doing the signature verification</param> /// <param name="certificate">certificate having its key usages checked</param> /// <param name="keyUsages">key usages being examined</param> internal static void LogVerifyKeyUsage(SignedXml signedXml, X509Certificate certificate, X509KeyUsageExtension keyUsages) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(certificate != null, "certificate != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_KeyUsages, keyUsages.KeyUsages, GetOidName(keyUsages.Oid), GetKeyName(certificate)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, logMessage); } } /// <summary> /// Log that we are verifying a reference /// </summary> /// <param name="signedXml">SignedXMl object doing the verification</param> /// <param name="reference">reference being verified</param> internal static void LogVerifyReference(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerifyReference, GetObjectId(reference), reference.Uri, reference.Id, reference.Type); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifyReference, logMessage); } } /// <summary> /// Log the hash comparison when verifying a reference /// </summary> /// <param name="signedXml">SignedXml object verifying the signature</param> /// <param name="reference">reference being verified</param> /// <param name="actualHash">actual hash value of the reference</param> /// <param name="expectedHash">hash value the signature expected the reference to have</param> internal static void LogVerifyReferenceHash(SignedXml signedXml, Reference reference, byte[] actualHash, byte[] expectedHash) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); Debug.Assert(actualHash != null, "actualHash != null"); Debug.Assert(expectedHash != null, "expectedHash != null"); if (VerboseLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_ReferenceHash, GetObjectId(reference), reference.DigestMethod, hashAlgorithmName, FormatBytes(actualHash), FormatBytes(expectedHash)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifyReference, logMessage); } } /// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using an /// asymmetric key /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">key being used to verify the signed info</param> /// <param name="signatureDescription">type of signature description class used</param> /// <param name="hashAlgorithm">type of hash algorithm used</param> /// <param name="asymmetricSignatureDeformatter">type of signature deformatter used</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, AsymmetricAlgorithm key, SignatureDescription signatureDescription, HashAlgorithm hashAlgorithm, AsymmetricSignatureDeformatter asymmetricSignatureDeformatter, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hashAlgorithm != null, "hashAlgorithm != null"); Debug.Assert(asymmetricSignatureDeformatter != null, "asymmetricSignatureDeformatter != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerifySignedInfoAsymmetric, GetKeyName(key), signatureDescription.GetType().Name, hashAlgorithm.GetType().Name, asymmetricSignatureDeformatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = SR.Format(CultureInfo.InvariantCulture, SR.Log_ActualHashValue, FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = SR.Format(CultureInfo.InvariantCulture, SR.Log_RawSignatureValue, FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } } /// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using a /// keyed hash algorithm /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="mac">hash algorithm doing the verification</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, KeyedHashAlgorithm mac, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(mac != null, "mac != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerifySignedInfoHmac, mac.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = SR.Format(CultureInfo.InvariantCulture, SR.Log_ActualHashValue, FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = SR.Format(CultureInfo.InvariantCulture, SR.Log_RawSignatureValue, FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } } /// <summary> /// Log that an X509 chain is being built for a certificate /// </summary> /// <param name="signedXml">SignedXml object building the chain</param> /// <param name="chain">chain built for the certificate</param> /// <param name="certificate">certificate having the chain built for it</param> internal static void LogVerifyX509Chain(SignedXml signedXml, X509Chain chain, X509Certificate certificate) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(certificate != null, "certificate != null"); Debug.Assert(chain != null, "chain != null"); if (InformationLoggingEnabled) { string buildMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_BuildX509Chain, GetKeyName(certificate)); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.X509Verification, buildMessage); } if (VerboseLoggingEnabled) { // Dump out the flags and other miscelanious information used for building string revocationMode = SR.Format(CultureInfo.InvariantCulture, SR.Log_RevocationMode, chain.ChainPolicy.RevocationFlag); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationMode); string revocationFlag = SR.Format(CultureInfo.InvariantCulture, SR.Log_RevocationFlag, chain.ChainPolicy.RevocationFlag); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationFlag); string verificationFlags = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerificationFlag, chain.ChainPolicy.VerificationFlags); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationFlags); string verificationTime = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerificationTime, chain.ChainPolicy.VerificationTime); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationTime); string urlTimeout = SR.Format(CultureInfo.InvariantCulture, SR.Log_UrlTimeout, chain.ChainPolicy.UrlRetrievalTimeout); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, urlTimeout); } // If there were any errors in the chain, make sure to dump those out if (InformationLoggingEnabled) { foreach (X509ChainStatus status in chain.ChainStatus) { if (status.Status != X509ChainStatusFlags.NoError) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_X509ChainError, status.Status, status.StatusInformation); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.X509Verification, logMessage); } } } // Finally, dump out the chain itself if (VerboseLoggingEnabled) { StringBuilder chainElements = new StringBuilder(); chainElements.Append(SR.Log_CertificateChain); foreach (X509ChainElement element in chain.ChainElements) { chainElements.AppendFormat(CultureInfo.InvariantCulture, " {0}", GetKeyName(element.Certificate)); } WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, chainElements.ToString()); } } /// <summary> /// Write information when user hits the Signed XML recursion depth limit issue. /// This is helpful in debugging this kind of issues. /// </summary> /// <param name="signedXml">SignedXml object verifying the signature</param> /// <param name="reference">reference being verified</param> internal static void LogSignedXmlRecursionLimit(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (InformationLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SignedXmlRecursionLimit, GetObjectId(reference), reference.DigestMethod, hashAlgorithmName); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } } /// <summary> /// Write data to the log /// </summary> /// <param name="source">object doing the trace</param> /// <param name="eventType">severity of the debug event</param> /// <param name="data">data being written</param> /// <param name="eventId">type of event being traced</param> private static void WriteLine(object source, TraceEventType eventType, SignedXmlDebugEvent eventId, string data) { Debug.Assert(source != null, "source != null"); Debug.Assert(!string.IsNullOrEmpty(data), "!string.IsNullOrEmpty(data)"); Debug.Assert(InformationLoggingEnabled, "InformationLoggingEnabled"); s_traceSource.TraceEvent(eventType, (int)eventId, "[{0}, {1}] {2}", GetObjectId(source), eventId, data); } } }
// 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.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Xml; namespace System.Security.Cryptography.Xml { /// <summary> /// Trace support for debugging issues signing and verifying XML signatures. /// </summary> internal static class SignedXmlDebugLog { // // In order to enable XML digital signature debug loggging, applications should setup their config // file to be similar to the following: // // <configuration> // <system.diagnostics> // <sources> // <source name="System.Security.Cryptography.Xml.SignedXml" // switchName="XmlDsigLogSwitch"> // <listeners> // <add name="logFile" /> // </listeners> // </source> // </sources> // <switches> // <add name="XmlDsigLogSwitch" value="Verbose" /> // </switches> // <sharedListeners> // <add name="logFile" // type="System.Diagnostics.TextWriterTraceListener" // initializeData="XmlDsigLog.txt"/> // </sharedListeners> // <trace autoflush="true"> // <listeners> // <add name="logFile" /> // </listeners> // </trace> // </system.diagnostics> // </configuration> // private const string NullString = "(null)"; private static readonly TraceSource s_traceSource = new TraceSource("System.Security.Cryptography.Xml.SignedXml"); private static volatile bool s_haveVerboseLogging; private static volatile bool s_verboseLogging; private static volatile bool s_haveInformationLogging; private static volatile bool s_informationLogging; /// <summary> /// Types of events that are logged to the debug log /// </summary> internal enum SignedXmlDebugEvent { /// <summary> /// Canonicalization of input XML has begun /// </summary> BeginCanonicalization, /// <summary> /// Verification of the signature format itself is beginning /// </summary> BeginCheckSignatureFormat, /// <summary> /// Verification of a signed info is beginning /// </summary> BeginCheckSignedInfo, /// <summary> /// Signing is beginning /// </summary> BeginSignatureComputation, /// <summary> /// Signature verification is beginning /// </summary> BeginSignatureVerification, /// <summary> /// Input data has been transformed to its canonicalized form /// </summary> CanonicalizedData, /// <summary> /// The result of signature format validation /// </summary> FormatValidationResult, /// <summary> /// Namespaces are being propigated into the signature /// </summary> NamespacePropagation, /// <summary> /// Output from a Reference /// </summary> ReferenceData, /// <summary> /// The result of a signature verification /// </summary> SignatureVerificationResult, /// <summary> /// Calculating the final signature /// </summary> Signing, /// <summary> /// A reference is being hashed /// </summary> SigningReference, /// <summary> /// A signature has failed to verify /// </summary> VerificationFailure, /// <summary> /// Verify that a reference has the correct hash value /// </summary> VerifyReference, /// <summary> /// Verification is processing the SignedInfo section of the signature /// </summary> VerifySignedInfo, /// <summary> /// Verification status on the x.509 certificate in use /// </summary> X509Verification, /// <summary> /// The signature is being rejected by the signature format verifier due to having /// a canonicalization algorithm which is not on the known valid list. /// </summary> UnsafeCanonicalizationMethod, /// <summary> /// The signature is being rejected by the signature verifier due to having /// a transform algorithm which is not on the known valid list. /// </summary> UnsafeTransformMethod, } /// <summary> /// Check to see if logging should be done in this process /// </summary> private static bool InformationLoggingEnabled { get { if (!s_haveInformationLogging) { s_informationLogging = s_traceSource.Switch.ShouldTrace(TraceEventType.Information); s_haveInformationLogging = true; } return s_informationLogging; } } /// <summary> /// Check to see if verbose log messages should be generated /// </summary> private static bool VerboseLoggingEnabled { get { if (!s_haveVerboseLogging) { s_verboseLogging = s_traceSource.Switch.ShouldTrace(TraceEventType.Verbose); s_haveVerboseLogging = true; } return s_verboseLogging; } } /// <summary> /// Convert the byte array into a hex string /// </summary> private static string FormatBytes(byte[] bytes) { if (bytes == null) return NullString; return HexConverter.ToString(bytes, HexConverter.Casing.Lower); } /// <summary> /// Map a key to a string describing the key /// </summary> private static string GetKeyName(object key) { Debug.Assert(key != null, "key != null"); ICspAsymmetricAlgorithm cspKey = key as ICspAsymmetricAlgorithm; X509Certificate certificate = key as X509Certificate; X509Certificate2 certificate2 = key as X509Certificate2; // // Use the following sources for key names, if available: // // * CAPI key -> key container name // * X509Certificate2 -> subject simple name // * X509Certificate -> subject name // * All others -> hash code // string keyName; #pragma warning disable CA1416 // This call site is reachable on all platforms. 'CspKeyContainerInfo.KeyContainerName' is supported on: 'windows'. if (cspKey != null && cspKey.CspKeyContainerInfo.KeyContainerName != null) { keyName = "\"" + cspKey.CspKeyContainerInfo.KeyContainerName + "\""; } #pragma warning restore CA1416 else if (certificate2 != null) { keyName = "\"" + certificate2.GetNameInfo(X509NameType.SimpleName, false) + "\""; } else if (certificate != null) { keyName = "\"" + certificate.Subject + "\""; } else { keyName = key.GetHashCode().ToString("x8", CultureInfo.InvariantCulture); } return $"{key.GetType().Name}#{keyName}"; } /// <summary> /// Map an object to a string describing the object /// </summary> private static string GetObjectId(object o) { Debug.Assert(o != null, "o != null"); return $"{o.GetType().Name}#{o.GetHashCode():x8}"; } /// <summary> /// Map an OID to the friendliest name possible /// </summary> private static string GetOidName(Oid oid) { Debug.Assert(oid != null, "oid != null"); string friendlyName = oid.FriendlyName; if (string.IsNullOrEmpty(friendlyName)) friendlyName = oid.Value; return friendlyName; } /// <summary> /// Log that canonicalization has begun on input data /// </summary> /// <param name="signedXml">SignedXml object doing the signing or verification</param> /// <param name="canonicalizationTransform">transform canonicalizing the input</param> internal static void LogBeginCanonicalization(SignedXml signedXml, Transform canonicalizationTransform) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_BeginCanonicalization, canonicalizationTransform.Algorithm, canonicalizationTransform.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCanonicalization, logMessage); } if (VerboseLoggingEnabled) { string canonicalizationSettings = SR.Format(CultureInfo.InvariantCulture, SR.Log_CanonicalizationSettings, canonicalizationTransform.Resolver.GetType(), canonicalizationTransform.BaseURI); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginCanonicalization, canonicalizationSettings); } } /// <summary> /// Log that we're going to be validating the signature format itself /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="formatValidator">Callback delegate which is being used for format verification</param> internal static void LogBeginCheckSignatureFormat(SignedXml signedXml, Func<SignedXml, bool> formatValidator) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(formatValidator != null, "formatValidator != null"); if (InformationLoggingEnabled) { MethodInfo validationMethod = formatValidator.Method; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_CheckSignatureFormat, validationMethod.Module.Assembly.FullName, validationMethod.DeclaringType.FullName, validationMethod.Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignatureFormat, logMessage); } } /// <summary> /// Log that checking SignedInfo is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="signedInfo">SignedInfo object being verified</param> internal static void LogBeginCheckSignedInfo(SignedXml signedXml, SignedInfo signedInfo) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signedInfo != null, " signedInfo != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_CheckSignedInfo, signedInfo.Id != null ? signedInfo.Id : NullString); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignedInfo, logMessage); } } /// <summary> /// Log that signature computation is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the signing</param> /// <param name="context">Context of the signature</param> internal static void LogBeginSignatureComputation(SignedXml signedXml, XmlElement context) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginSignatureComputation, SR.Log_BeginSignatureComputation); } if (VerboseLoggingEnabled) { string contextData = SR.Format(CultureInfo.InvariantCulture, SR.Log_XmlContext, context != null ? context.OuterXml : NullString); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginSignatureComputation, contextData); } } /// <summary> /// Log that signature verification is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="context">Context of the verification</param> internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlElement context) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginSignatureVerification, SR.Log_BeginSignatureVerification); } if (VerboseLoggingEnabled) { string contextData = SR.Format(CultureInfo.InvariantCulture, SR.Log_XmlContext, context != null ? context.OuterXml : NullString); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginSignatureVerification, contextData); } } /// <summary> /// Log the canonicalized data /// </summary> /// <param name="signedXml">SignedXml object doing the signing or verification</param> /// <param name="canonicalizationTransform">transform canonicalizing the input</param> internal static void LogCanonicalizedOutput(SignedXml signedXml, Transform canonicalizationTransform) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null"); if (VerboseLoggingEnabled) { using (StreamReader reader = new StreamReader(canonicalizationTransform.GetOutput(typeof(Stream)) as Stream)) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_CanonicalizedOutput, reader.ReadToEnd()); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.CanonicalizedData, logMessage); } } } /// <summary> /// Log that the signature format callback has rejected the signature /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="result">result of the signature format verification</param> internal static void LogFormatValidationResult(SignedXml signedXml, bool result) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { string logMessage = result ? SR.Log_FormatValidationSuccessful : SR.Log_FormatValidationNotSuccessful; WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.FormatValidationResult, logMessage); } } /// <summary> /// Log that a signature is being rejected as having an invalid format due to its canonicalization /// algorithm not being on the valid list. /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="algorithm">Canonicalization algorithm</param> /// <param name="validAlgorithms">List of valid canonicalization algorithms</param> internal static void LogUnsafeCanonicalizationMethod(SignedXml signedXml, string algorithm, IEnumerable<string> validAlgorithms) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(validAlgorithms != null, "validAlgorithms != null"); if (InformationLoggingEnabled) { StringBuilder validAlgorithmBuilder = new StringBuilder(); foreach (string validAlgorithm in validAlgorithms) { if (validAlgorithmBuilder.Length != 0) { validAlgorithmBuilder.Append(", "); } validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm); } string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_UnsafeCanonicalizationMethod, algorithm, validAlgorithmBuilder.ToString()); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.UnsafeCanonicalizationMethod, logMessage); } } /// <summary> /// Log that a signature is being rejected as having an invalid signature due to a transform /// algorithm not being on the valid list. /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="algorithm">Transform algorithm that was not allowed</param> /// <param name="validC14nAlgorithms">The valid C14N algorithms</param> /// <param name="validTransformAlgorithms">The valid C14N algorithms</param> internal static void LogUnsafeTransformMethod( SignedXml signedXml, string algorithm, IEnumerable<string> validC14nAlgorithms, IEnumerable<string> validTransformAlgorithms) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(validC14nAlgorithms != null, "validC14nAlgorithms != null"); Debug.Assert(validTransformAlgorithms != null, "validTransformAlgorithms != null"); if (InformationLoggingEnabled) { StringBuilder validAlgorithmBuilder = new StringBuilder(); foreach (string validAlgorithm in validC14nAlgorithms) { if (validAlgorithmBuilder.Length != 0) { validAlgorithmBuilder.Append(", "); } validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm); } foreach (string validAlgorithm in validTransformAlgorithms) { if (validAlgorithmBuilder.Length != 0) { validAlgorithmBuilder.Append(", "); } validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm); } string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_UnsafeTransformMethod, algorithm, validAlgorithmBuilder.ToString()); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.UnsafeTransformMethod, logMessage); } } /// <summary> /// Log namespaces which are being propagated into the signature /// </summary> /// <param name="signedXml">SignedXml doing the signing or verification</param> /// <param name="namespaces">namespaces being propagated</param> internal static void LogNamespacePropagation(SignedXml signedXml, XmlNodeList namespaces) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { if (namespaces != null) { foreach (XmlAttribute propagatedNamespace in namespaces) { string propagationMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_PropagatingNamespace, propagatedNamespace.Name, propagatedNamespace.Value); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.NamespacePropagation, propagationMessage); } } else { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.NamespacePropagation, SR.Log_NoNamespacesPropagated); } } } /// <summary> /// Log the output of a reference /// </summary> /// <param name="reference">The reference being processed</param> /// <param name="data">Stream containing the output of the reference</param> /// <returns>Stream containing the output of the reference</returns> internal static Stream LogReferenceData(Reference reference, Stream data) { if (VerboseLoggingEnabled) { // // Since the input data stream could be from the network or another source that does not // support rewinding, we will read the stream into a temporary MemoryStream that can be used // to stringify the output and also return to the reference so that it can produce the hash // value. // MemoryStream ms = new MemoryStream(); // First read the input stream into our temporary stream byte[] buffer = new byte[4096]; int readBytes; do { readBytes = data.Read(buffer, 0, buffer.Length); ms.Write(buffer, 0, readBytes); } while (readBytes == buffer.Length); // Log out information about it string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_TransformedReferenceContents, Encoding.UTF8.GetString(ms.ToArray())); WriteLine(reference, TraceEventType.Verbose, SignedXmlDebugEvent.ReferenceData, logMessage); // Rewind to the beginning, so that the entire input stream is hashed ms.Seek(0, SeekOrigin.Begin); return ms; } else { return data; } } /// <summary> /// Log the computation of a signature value when signing with an asymmetric algorithm /// </summary> /// <param name="signedXml">SignedXml object calculating the signature</param> /// <param name="key">key used for signing</param> /// <param name="signatureDescription">signature description being used to create the signature</param> /// <param name="hash">hash algorithm used to digest the output</param> /// <param name="asymmetricSignatureFormatter">signature formatter used to do the signing</param> internal static void LogSigning(SignedXml signedXml, object key, SignatureDescription signatureDescription, HashAlgorithm hash, AsymmetricSignatureFormatter asymmetricSignatureFormatter) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hash != null, "hash != null"); Debug.Assert(asymmetricSignatureFormatter != null, "asymmetricSignatureFormatter != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SigningAsymmetric, GetKeyName(key), signatureDescription.GetType().Name, hash.GetType().Name, asymmetricSignatureFormatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, logMessage); } } /// <summary> /// Log the computation of a signature value when signing with a keyed hash algorithm /// </summary> /// <param name="signedXml">SignedXml object calculating the signature</param> /// <param name="key">key the signature is created with</param> internal static void LogSigning(SignedXml signedXml, KeyedHashAlgorithm key) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(key != null, "key != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SigningHmac, key.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, logMessage); } } /// <summary> /// Log the calculation of a hash value of a reference /// </summary> /// <param name="signedXml">SignedXml object driving the signature</param> /// <param name="reference">Reference being hashed</param> internal static void LogSigningReference(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (VerboseLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SigningReference, GetObjectId(reference), reference.Uri, reference.Id, reference.Type, reference.DigestMethod, hashAlgorithmName); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.SigningReference, logMessage); } } /// <summary> /// Log the specific point where a signature is determined to not be verifiable /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="failureLocation">location that the signature was determined to be invalid</param> internal static void LogVerificationFailure(SignedXml signedXml, string failureLocation) { if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerificationFailed, failureLocation); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerificationFailure, logMessage); } } /// <summary> /// Log the success or failure of a signature verification operation /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">public key used to verify the signature</param> /// <param name="verified">true if the signature verified, false otherwise</param> internal static void LogVerificationResult(SignedXml signedXml, object key, bool verified) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(key != null, "key != null"); if (InformationLoggingEnabled) { string resource = verified ? SR.Log_VerificationWithKeySuccessful : SR.Log_VerificationWithKeyNotSuccessful; string logMessage = string.Format(CultureInfo.InvariantCulture, resource, GetKeyName(key)); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.SignatureVerificationResult, logMessage); } } /// <summary> /// Log the check for appropriate X509 key usage /// </summary> /// <param name="signedXml">SignedXml doing the signature verification</param> /// <param name="certificate">certificate having its key usages checked</param> /// <param name="keyUsages">key usages being examined</param> internal static void LogVerifyKeyUsage(SignedXml signedXml, X509Certificate certificate, X509KeyUsageExtension keyUsages) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(certificate != null, "certificate != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_KeyUsages, keyUsages.KeyUsages, GetOidName(keyUsages.Oid), GetKeyName(certificate)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, logMessage); } } /// <summary> /// Log that we are verifying a reference /// </summary> /// <param name="signedXml">SignedXMl object doing the verification</param> /// <param name="reference">reference being verified</param> internal static void LogVerifyReference(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerifyReference, GetObjectId(reference), reference.Uri, reference.Id, reference.Type); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifyReference, logMessage); } } /// <summary> /// Log the hash comparison when verifying a reference /// </summary> /// <param name="signedXml">SignedXml object verifying the signature</param> /// <param name="reference">reference being verified</param> /// <param name="actualHash">actual hash value of the reference</param> /// <param name="expectedHash">hash value the signature expected the reference to have</param> internal static void LogVerifyReferenceHash(SignedXml signedXml, Reference reference, byte[] actualHash, byte[] expectedHash) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); Debug.Assert(actualHash != null, "actualHash != null"); Debug.Assert(expectedHash != null, "expectedHash != null"); if (VerboseLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_ReferenceHash, GetObjectId(reference), reference.DigestMethod, hashAlgorithmName, FormatBytes(actualHash), FormatBytes(expectedHash)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifyReference, logMessage); } } /// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using an /// asymmetric key /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">key being used to verify the signed info</param> /// <param name="signatureDescription">type of signature description class used</param> /// <param name="hashAlgorithm">type of hash algorithm used</param> /// <param name="asymmetricSignatureDeformatter">type of signature deformatter used</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, AsymmetricAlgorithm key, SignatureDescription signatureDescription, HashAlgorithm hashAlgorithm, AsymmetricSignatureDeformatter asymmetricSignatureDeformatter, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hashAlgorithm != null, "hashAlgorithm != null"); Debug.Assert(asymmetricSignatureDeformatter != null, "asymmetricSignatureDeformatter != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerifySignedInfoAsymmetric, GetKeyName(key), signatureDescription.GetType().Name, hashAlgorithm.GetType().Name, asymmetricSignatureDeformatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = SR.Format(CultureInfo.InvariantCulture, SR.Log_ActualHashValue, FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = SR.Format(CultureInfo.InvariantCulture, SR.Log_RawSignatureValue, FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } } /// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using a /// keyed hash algorithm /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="mac">hash algorithm doing the verification</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, KeyedHashAlgorithm mac, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(mac != null, "mac != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerifySignedInfoHmac, mac.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = SR.Format(CultureInfo.InvariantCulture, SR.Log_ActualHashValue, FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = SR.Format(CultureInfo.InvariantCulture, SR.Log_RawSignatureValue, FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } } /// <summary> /// Log that an X509 chain is being built for a certificate /// </summary> /// <param name="signedXml">SignedXml object building the chain</param> /// <param name="chain">chain built for the certificate</param> /// <param name="certificate">certificate having the chain built for it</param> internal static void LogVerifyX509Chain(SignedXml signedXml, X509Chain chain, X509Certificate certificate) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(certificate != null, "certificate != null"); Debug.Assert(chain != null, "chain != null"); if (InformationLoggingEnabled) { string buildMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_BuildX509Chain, GetKeyName(certificate)); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.X509Verification, buildMessage); } if (VerboseLoggingEnabled) { // Dump out the flags and other miscelanious information used for building string revocationMode = SR.Format(CultureInfo.InvariantCulture, SR.Log_RevocationMode, chain.ChainPolicy.RevocationFlag); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationMode); string revocationFlag = SR.Format(CultureInfo.InvariantCulture, SR.Log_RevocationFlag, chain.ChainPolicy.RevocationFlag); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationFlag); string verificationFlags = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerificationFlag, chain.ChainPolicy.VerificationFlags); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationFlags); string verificationTime = SR.Format(CultureInfo.InvariantCulture, SR.Log_VerificationTime, chain.ChainPolicy.VerificationTime); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationTime); string urlTimeout = SR.Format(CultureInfo.InvariantCulture, SR.Log_UrlTimeout, chain.ChainPolicy.UrlRetrievalTimeout); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, urlTimeout); } // If there were any errors in the chain, make sure to dump those out if (InformationLoggingEnabled) { foreach (X509ChainStatus status in chain.ChainStatus) { if (status.Status != X509ChainStatusFlags.NoError) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_X509ChainError, status.Status, status.StatusInformation); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.X509Verification, logMessage); } } } // Finally, dump out the chain itself if (VerboseLoggingEnabled) { StringBuilder chainElements = new StringBuilder(); chainElements.Append(SR.Log_CertificateChain); foreach (X509ChainElement element in chain.ChainElements) { chainElements.AppendFormat(CultureInfo.InvariantCulture, " {0}", GetKeyName(element.Certificate)); } WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, chainElements.ToString()); } } /// <summary> /// Write information when user hits the Signed XML recursion depth limit issue. /// This is helpful in debugging this kind of issues. /// </summary> /// <param name="signedXml">SignedXml object verifying the signature</param> /// <param name="reference">reference being verified</param> internal static void LogSignedXmlRecursionLimit(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (InformationLoggingEnabled) { HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SignedXmlRecursionLimit, GetObjectId(reference), reference.DigestMethod, hashAlgorithmName); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } } /// <summary> /// Write data to the log /// </summary> /// <param name="source">object doing the trace</param> /// <param name="eventType">severity of the debug event</param> /// <param name="data">data being written</param> /// <param name="eventId">type of event being traced</param> private static void WriteLine(object source, TraceEventType eventType, SignedXmlDebugEvent eventId, string data) { Debug.Assert(source != null, "source != null"); Debug.Assert(!string.IsNullOrEmpty(data), "!string.IsNullOrEmpty(data)"); Debug.Assert(InformationLoggingEnabled, "InformationLoggingEnabled"); s_traceSource.TraceEvent(eventType, (int)eventId, "[{0}, {1}] {2}", GetObjectId(source), eventId, data); } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/box-unbox/box-unbox003.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.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(object o) { return Helper.Compare((byte)o, Helper.Create(default(byte))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((byte?)o, Helper.Create(default(byte))); } private static int Main() { byte? s = Helper.Create(default(byte)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(object o) { return Helper.Compare((byte)o, Helper.Create(default(byte))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((byte?)o, Helper.Create(default(byte))); } private static int Main() { byte? s = Helper.Create(default(byte)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyKeyFileAttribute.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.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyKeyFileAttribute : Attribute { public AssemblyKeyFileAttribute(string keyFile) { KeyFile = keyFile; } public string KeyFile { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyKeyFileAttribute : Attribute { public AssemblyKeyFileAttribute(string keyFile) { KeyFile = keyFile; } public string KeyFile { get; } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc32.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.Binary; namespace System.IO.Hashing { /// <summary> /// Provides an implementation of the CRC-32 algorithm, as used in /// ITU-T V.42 and IEEE 802.3. /// </summary> /// <remarks> /// <para> /// This implementation emits the answer in the Little Endian byte order so that /// the CRC residue relationship (CRC(message concat CRC(message))) is a fixed value) holds. /// For CRC-32 this stable output is the byte sequence <c>{ 0x1C, 0xDF, 0x44, 0x21 }</c>, /// the Little Endian representation of <c>0x2144DF1C</c>. /// </para> /// <para> /// There are multiple, incompatible, definitions of a 32-bit cyclic redundancy /// check (CRC) algorithm. When interoperating with another system, ensure that you /// are using the same definition. The definition used by this implementation is not /// compatible with the cyclic redundancy check described in ITU-T I.363.5. /// </para> /// </remarks> public sealed partial class Crc32 : NonCryptographicHashAlgorithm { private const uint InitialState = 0xFFFF_FFFFu; private const int Size = sizeof(uint); private uint _crc = InitialState; /// <summary> /// Initializes a new instance of the <see cref="Crc32"/> class. /// </summary> public Crc32() : base(Size) { } /// <summary> /// Appends the contents of <paramref name="source"/> to the data already /// processed for the current hash computation. /// </summary> /// <param name="source">The data to process.</param> public override void Append(ReadOnlySpan<byte> source) { _crc = Update(_crc, source); } /// <summary> /// Resets the hash computation to the initial state. /// </summary> public override void Reset() { _crc = InitialState; } /// <summary> /// Writes the computed hash value to <paramref name="destination"/> /// without modifying accumulated state. /// </summary> /// <param name="destination">The buffer that receives the computed hash value.</param> protected override void GetCurrentHashCore(Span<byte> destination) { // The finalization step of the CRC is to perform the ones' complement. BinaryPrimitives.WriteUInt32LittleEndian(destination, ~_crc); } /// <summary> /// Writes the computed hash value to <paramref name="destination"/> /// then clears the accumulated state. /// </summary> protected override void GetHashAndResetCore(Span<byte> destination) { BinaryPrimitives.WriteUInt32LittleEndian(destination, ~_crc); _crc = InitialState; } /// <summary> /// Computes the CRC-32 hash of the provided data. /// </summary> /// <param name="source">The data to hash.</param> /// <returns>The CRC-32 hash of the provided data.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is <see langword="null"/>. /// </exception> public static byte[] Hash(byte[] source!!) { return Hash(new ReadOnlySpan<byte>(source)); } /// <summary> /// Computes the CRC-32 hash of the provided data. /// </summary> /// <param name="source">The data to hash.</param> /// <returns>The CRC-32 hash of the provided data.</returns> public static byte[] Hash(ReadOnlySpan<byte> source) { byte[] ret = new byte[Size]; StaticHash(source, ret); return ret; } /// <summary> /// Attempts to compute the CRC-32 hash of the provided data into the provided destination. /// </summary> /// <param name="source">The data to hash.</param> /// <param name="destination">The buffer that receives the computed hash value.</param> /// <param name="bytesWritten"> /// On success, receives the number of bytes written to <paramref name="destination"/>. /// </param> /// <returns> /// <see langword="true"/> if <paramref name="destination"/> is long enough to receive /// the computed hash value (4 bytes); otherwise, <see langword="false"/>. /// </returns> public static bool TryHash(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten) { if (destination.Length < Size) { bytesWritten = 0; return false; } bytesWritten = StaticHash(source, destination); return true; } /// <summary> /// Computes the CRC-32 hash of the provided data into the provided destination. /// </summary> /// <param name="source">The data to hash.</param> /// <param name="destination">The buffer that receives the computed hash value.</param> /// <returns> /// The number of bytes written to <paramref name="destination"/>. /// </returns> public static int Hash(ReadOnlySpan<byte> source, Span<byte> destination) { if (destination.Length < Size) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); return StaticHash(source, destination); } private static int StaticHash(ReadOnlySpan<byte> source, Span<byte> destination) { uint crc = InitialState; crc = Update(crc, source); BinaryPrimitives.WriteUInt32LittleEndian(destination, ~crc); return Size; } private static uint Update(uint crc, ReadOnlySpan<byte> source) { for (int i = 0; i < source.Length; i++) { byte idx = (byte)crc; idx ^= source[i]; crc = s_crcLookup[idx] ^ (crc >> 8); } return crc; } } }
// 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.Binary; namespace System.IO.Hashing { /// <summary> /// Provides an implementation of the CRC-32 algorithm, as used in /// ITU-T V.42 and IEEE 802.3. /// </summary> /// <remarks> /// <para> /// This implementation emits the answer in the Little Endian byte order so that /// the CRC residue relationship (CRC(message concat CRC(message))) is a fixed value) holds. /// For CRC-32 this stable output is the byte sequence <c>{ 0x1C, 0xDF, 0x44, 0x21 }</c>, /// the Little Endian representation of <c>0x2144DF1C</c>. /// </para> /// <para> /// There are multiple, incompatible, definitions of a 32-bit cyclic redundancy /// check (CRC) algorithm. When interoperating with another system, ensure that you /// are using the same definition. The definition used by this implementation is not /// compatible with the cyclic redundancy check described in ITU-T I.363.5. /// </para> /// </remarks> public sealed partial class Crc32 : NonCryptographicHashAlgorithm { private const uint InitialState = 0xFFFF_FFFFu; private const int Size = sizeof(uint); private uint _crc = InitialState; /// <summary> /// Initializes a new instance of the <see cref="Crc32"/> class. /// </summary> public Crc32() : base(Size) { } /// <summary> /// Appends the contents of <paramref name="source"/> to the data already /// processed for the current hash computation. /// </summary> /// <param name="source">The data to process.</param> public override void Append(ReadOnlySpan<byte> source) { _crc = Update(_crc, source); } /// <summary> /// Resets the hash computation to the initial state. /// </summary> public override void Reset() { _crc = InitialState; } /// <summary> /// Writes the computed hash value to <paramref name="destination"/> /// without modifying accumulated state. /// </summary> /// <param name="destination">The buffer that receives the computed hash value.</param> protected override void GetCurrentHashCore(Span<byte> destination) { // The finalization step of the CRC is to perform the ones' complement. BinaryPrimitives.WriteUInt32LittleEndian(destination, ~_crc); } /// <summary> /// Writes the computed hash value to <paramref name="destination"/> /// then clears the accumulated state. /// </summary> protected override void GetHashAndResetCore(Span<byte> destination) { BinaryPrimitives.WriteUInt32LittleEndian(destination, ~_crc); _crc = InitialState; } /// <summary> /// Computes the CRC-32 hash of the provided data. /// </summary> /// <param name="source">The data to hash.</param> /// <returns>The CRC-32 hash of the provided data.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is <see langword="null"/>. /// </exception> public static byte[] Hash(byte[] source!!) { return Hash(new ReadOnlySpan<byte>(source)); } /// <summary> /// Computes the CRC-32 hash of the provided data. /// </summary> /// <param name="source">The data to hash.</param> /// <returns>The CRC-32 hash of the provided data.</returns> public static byte[] Hash(ReadOnlySpan<byte> source) { byte[] ret = new byte[Size]; StaticHash(source, ret); return ret; } /// <summary> /// Attempts to compute the CRC-32 hash of the provided data into the provided destination. /// </summary> /// <param name="source">The data to hash.</param> /// <param name="destination">The buffer that receives the computed hash value.</param> /// <param name="bytesWritten"> /// On success, receives the number of bytes written to <paramref name="destination"/>. /// </param> /// <returns> /// <see langword="true"/> if <paramref name="destination"/> is long enough to receive /// the computed hash value (4 bytes); otherwise, <see langword="false"/>. /// </returns> public static bool TryHash(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten) { if (destination.Length < Size) { bytesWritten = 0; return false; } bytesWritten = StaticHash(source, destination); return true; } /// <summary> /// Computes the CRC-32 hash of the provided data into the provided destination. /// </summary> /// <param name="source">The data to hash.</param> /// <param name="destination">The buffer that receives the computed hash value.</param> /// <returns> /// The number of bytes written to <paramref name="destination"/>. /// </returns> public static int Hash(ReadOnlySpan<byte> source, Span<byte> destination) { if (destination.Length < Size) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); return StaticHash(source, destination); } private static int StaticHash(ReadOnlySpan<byte> source, Span<byte> destination) { uint crc = InitialState; crc = Update(crc, source); BinaryPrimitives.WriteUInt32LittleEndian(destination, ~crc); return Size; } private static uint Update(uint crc, ReadOnlySpan<byte> source) { for (int i = 0; i < source.Length; i++) { byte idx = (byte)crc; idx ^= source[i]; crc = s_crcLookup[idx] ^ (crc >> 8); } return crc; } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b76717/b76717.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.Text; public class rep { public static int Main() { char[] chars = new char[] { (char)0x800 }; byte[] bytes = new byte[20]; int numBytes = Encoding.UTF8.GetBytes(chars, 0, 1, bytes, 0); Console.WriteLine("Converted to bytes - got " + numBytes + " bytes!"); char[] chars2 = Encoding.UTF8.GetChars(bytes, 0, numBytes); Console.WriteLine("chars2.Length: " + chars2.Length); if (chars2.Length != 1) throw new Exception("Expected length to be 1!"); if (chars2[0] != chars[0]) throw new Exception("Char differed after being roundtripped! got: U+" + ((short)chars2[0]).ToString("x")); Console.WriteLine("looks good."); 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.Text; public class rep { public static int Main() { char[] chars = new char[] { (char)0x800 }; byte[] bytes = new byte[20]; int numBytes = Encoding.UTF8.GetBytes(chars, 0, 1, bytes, 0); Console.WriteLine("Converted to bytes - got " + numBytes + " bytes!"); char[] chars2 = Encoding.UTF8.GetChars(bytes, 0, numBytes); Console.WriteLine("chars2.Length: " + chars2.Length); if (chars2.Length != 1) throw new Exception("Expected length to be 1!"); if (chars2[0] != chars[0]) throw new Exception("Char differed after being roundtripped! got: U+" + ((short)chars2[0]).ToString("x")); Console.WriteLine("looks good."); return 100; } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/JsonSerializerApiValidation.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.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Text.Json.Serialization.Tests; using System.Threading.Tasks; using Xunit; namespace System.Text.Json.Serialization.Tests { public class JsonSerializerApiValidation_Span : JsonSerializerApiValidation { public JsonSerializerApiValidation_Span() : base(JsonSerializerWrapperForString.SpanSerializer) { } } public class JsonSerializerApiValidation_String : JsonSerializerApiValidation { public JsonSerializerApiValidation_String() : base(JsonSerializerWrapperForString.StringSerializer) { } } public class JsonSerializerApiValidation_AsyncStream : JsonSerializerApiValidation { public JsonSerializerApiValidation_AsyncStream() : base(JsonSerializerWrapperForString.AsyncStreamSerializer) { } } public class JsonSerializerApiValidation_SyncStream : JsonSerializerApiValidation { public JsonSerializerApiValidation_SyncStream() : base(JsonSerializerWrapperForString.SyncStreamSerializer) { } } public class JsonSerializerApiValidation_Writer : JsonSerializerApiValidation { public JsonSerializerApiValidation_Writer() : base(JsonSerializerWrapperForString.ReaderWriterSerializer) { } } public class JsonSerializerApiValidation_Document : JsonSerializerApiValidation { public JsonSerializerApiValidation_Document() : base(JsonSerializerWrapperForString.DocumentSerializer) { } } public class JsonSerializerApiValidation_Element : JsonSerializerApiValidation { public JsonSerializerApiValidation_Element() : base(JsonSerializerWrapperForString.ElementSerializer) { } } public class JsonSerializerApiValidation_Node : JsonSerializerApiValidation { public JsonSerializerApiValidation_Node() : base(JsonSerializerWrapperForString.NodeSerializer) { } } } /// <summary> /// Verifies input values for public JsonSerializer methods. /// </summary> public abstract class JsonSerializerApiValidation { private class MyPoco { } internal partial class MyDummyContext : JsonSerializerContext { public MyDummyContext() : base(new JsonSerializerOptions()) { } public MyDummyContext(JsonSerializerOptions options) : base(options) { } public override JsonTypeInfo? GetTypeInfo(Type type) => throw new NotImplementedException(); protected override JsonSerializerOptions? GeneratedSerializerOptions => null; } private JsonTypeInfo<MyPoco> myDummyTypeInfo = GetTypeInfo(); private JsonSerializerWrapperForString Serializer { get; } public JsonSerializerApiValidation(JsonSerializerWrapperForString serializer) { Serializer = serializer; } private static JsonTypeInfo<MyPoco> GetTypeInfo() { JsonObjectInfoValues<MyPoco> objectInfo = new() { ObjectCreator = static () => throw new NotImplementedException(), SerializeHandler = (Utf8JsonWriter writer, MyPoco value) => throw new NotImplementedException() }; return JsonMetadataServices.CreateObjectInfo<MyPoco>(new JsonSerializerOptions(), objectInfo); } [Fact] public async Task DeserializeNullException() { await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper<MyPoco>(json: "{}", jsonTypeInfo: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper(json: "{}", type: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper(json: "{}", type: typeof(MyPoco), context: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper(json: "{}", type: null, context: new MyDummyContext())); if (!Serializer.SupportsNullValueOnDeserialize) { await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper(json: null, type: typeof(MyPoco), context: new MyDummyContext())); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper(json: null, type: typeof(MyPoco))); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper<MyPoco>(json: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper<MyPoco>(json: null, jsonTypeInfo: myDummyTypeInfo)); } } [Fact] public async Task SerializeNullException() { await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.SerializeWrapper<MyPoco>(value: new MyPoco(), jsonTypeInfo: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.SerializeWrapper(value: new MyPoco(), inputType: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.SerializeWrapper(value: new MyPoco(), inputType: typeof(MyPoco), context: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.SerializeWrapper(value: new MyPoco(), inputType: null, context: new MyDummyContext())); } }
// 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.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Text.Json.Serialization.Tests; using System.Threading.Tasks; using Xunit; namespace System.Text.Json.Serialization.Tests { public class JsonSerializerApiValidation_Span : JsonSerializerApiValidation { public JsonSerializerApiValidation_Span() : base(JsonSerializerWrapperForString.SpanSerializer) { } } public class JsonSerializerApiValidation_String : JsonSerializerApiValidation { public JsonSerializerApiValidation_String() : base(JsonSerializerWrapperForString.StringSerializer) { } } public class JsonSerializerApiValidation_AsyncStream : JsonSerializerApiValidation { public JsonSerializerApiValidation_AsyncStream() : base(JsonSerializerWrapperForString.AsyncStreamSerializer) { } } public class JsonSerializerApiValidation_SyncStream : JsonSerializerApiValidation { public JsonSerializerApiValidation_SyncStream() : base(JsonSerializerWrapperForString.SyncStreamSerializer) { } } public class JsonSerializerApiValidation_Writer : JsonSerializerApiValidation { public JsonSerializerApiValidation_Writer() : base(JsonSerializerWrapperForString.ReaderWriterSerializer) { } } public class JsonSerializerApiValidation_Document : JsonSerializerApiValidation { public JsonSerializerApiValidation_Document() : base(JsonSerializerWrapperForString.DocumentSerializer) { } } public class JsonSerializerApiValidation_Element : JsonSerializerApiValidation { public JsonSerializerApiValidation_Element() : base(JsonSerializerWrapperForString.ElementSerializer) { } } public class JsonSerializerApiValidation_Node : JsonSerializerApiValidation { public JsonSerializerApiValidation_Node() : base(JsonSerializerWrapperForString.NodeSerializer) { } } } /// <summary> /// Verifies input values for public JsonSerializer methods. /// </summary> public abstract class JsonSerializerApiValidation { private class MyPoco { } internal partial class MyDummyContext : JsonSerializerContext { public MyDummyContext() : base(new JsonSerializerOptions()) { } public MyDummyContext(JsonSerializerOptions options) : base(options) { } public override JsonTypeInfo? GetTypeInfo(Type type) => throw new NotImplementedException(); protected override JsonSerializerOptions? GeneratedSerializerOptions => null; } private JsonTypeInfo<MyPoco> myDummyTypeInfo = GetTypeInfo(); private JsonSerializerWrapperForString Serializer { get; } public JsonSerializerApiValidation(JsonSerializerWrapperForString serializer) { Serializer = serializer; } private static JsonTypeInfo<MyPoco> GetTypeInfo() { JsonObjectInfoValues<MyPoco> objectInfo = new() { ObjectCreator = static () => throw new NotImplementedException(), SerializeHandler = (Utf8JsonWriter writer, MyPoco value) => throw new NotImplementedException() }; return JsonMetadataServices.CreateObjectInfo<MyPoco>(new JsonSerializerOptions(), objectInfo); } [Fact] public async Task DeserializeNullException() { await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper<MyPoco>(json: "{}", jsonTypeInfo: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper(json: "{}", type: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper(json: "{}", type: typeof(MyPoco), context: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper(json: "{}", type: null, context: new MyDummyContext())); if (!Serializer.SupportsNullValueOnDeserialize) { await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper(json: null, type: typeof(MyPoco), context: new MyDummyContext())); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper(json: null, type: typeof(MyPoco))); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper<MyPoco>(json: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.DeserializeWrapper<MyPoco>(json: null, jsonTypeInfo: myDummyTypeInfo)); } } [Fact] public async Task SerializeNullException() { await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.SerializeWrapper<MyPoco>(value: new MyPoco(), jsonTypeInfo: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.SerializeWrapper(value: new MyPoco(), inputType: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.SerializeWrapper(value: new MyPoco(), inputType: typeof(MyPoco), context: null)); await Assert.ThrowsAsync<ArgumentNullException>(async () => await Serializer.SerializeWrapper(value: new MyPoco(), inputType: null, context: new MyDummyContext())); } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/SubstitutionList.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.Diagnostics; namespace System.Xml.Xsl.Qil { /// <summary> /// Data structure for use in CloneAndReplace /// </summary> /// <remarks>Isolates the many QilNode classes from changes in /// the underlying data structure.</remarks> internal sealed class SubstitutionList { // BUGBUG Find an efficient collection internal class to support this private readonly ArrayList _s; public SubstitutionList() { _s = new ArrayList(4); } /// <summary> /// Add a substitution pair /// </summary> /// <param name="find">a node to be replaced</param> /// <param name="replace">its replacement</param> public void AddSubstitutionPair(QilNode find, QilNode replace) { _s.Add(find); _s.Add(replace); } /// <summary> /// Remove the last a substitution pair /// </summary> public void RemoveLastSubstitutionPair() { _s.RemoveRange(_s.Count - 2, 2); } /// <summary> /// Find the replacement for a node /// </summary> /// <param name="n">the node to replace</param> /// <returns>null if no replacement is found</returns> public QilNode? FindReplacement(QilNode n) { Debug.Assert(_s.Count % 2 == 0); for (int i = _s.Count - 2; i >= 0; i -= 2) if (_s[i] == n) return (QilNode)_s[i + 1]!; 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; using System.Collections; using System.Diagnostics; namespace System.Xml.Xsl.Qil { /// <summary> /// Data structure for use in CloneAndReplace /// </summary> /// <remarks>Isolates the many QilNode classes from changes in /// the underlying data structure.</remarks> internal sealed class SubstitutionList { // BUGBUG Find an efficient collection internal class to support this private readonly ArrayList _s; public SubstitutionList() { _s = new ArrayList(4); } /// <summary> /// Add a substitution pair /// </summary> /// <param name="find">a node to be replaced</param> /// <param name="replace">its replacement</param> public void AddSubstitutionPair(QilNode find, QilNode replace) { _s.Add(find); _s.Add(replace); } /// <summary> /// Remove the last a substitution pair /// </summary> public void RemoveLastSubstitutionPair() { _s.RemoveRange(_s.Count - 2, 2); } /// <summary> /// Find the replacement for a node /// </summary> /// <param name="n">the node to replace</param> /// <returns>null if no replacement is found</returns> public QilNode? FindReplacement(QilNode n) { Debug.Assert(_s.Count % 2 == 0); for (int i = _s.Count - 2; i >= 0; i -= 2) if (_s[i] == n) return (QilNode)_s[i + 1]!; return null; } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Linq.Expressions/tests/DelegateType/ActionTypeTests.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 class ActionTypeTests : DelegateCreationTests { [Fact] public void NullTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs", () => Expression.GetActionType(default(Type[]))); } [Fact] public void NullInTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs", () => Expression.GetActionType(typeof(int), null)); } [Theory] [MemberData(nameof(EmptyTypeArgs))] [MemberData(nameof(ValidTypeArgs), false)] public void SuccessfulGetActionType(Type[] typeArgs) { Type funcType = Expression.GetActionType(typeArgs); if (typeArgs.Length == 0) { Assert.Equal(typeof(Action), funcType); } else { Assert.StartsWith("System.Action`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } } [Theory] [MemberData(nameof(EmptyTypeArgs))] [MemberData(nameof(ValidTypeArgs), false)] public void SuccessfulTryGetActionType(Type[] typeArgs) { Type funcType; Assert.True(Expression.TryGetActionType(typeArgs, out funcType)); if (typeArgs.Length == 0) { Assert.Equal(typeof(Action), funcType); } else { Assert.StartsWith("System.Action`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } } // Open generic type args aren't useful directly with Expressions, but creating them is allowed. [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulGetActionTypeOpenGeneric(Type[] typeArgs) { Type funcType = Expression.GetActionType(typeArgs); Assert.Equal("Action`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulTryGetActionTypeWithOpenGeneric(Type[] typeArgs) { Type funcType; Assert.True(Expression.TryGetActionType(typeArgs, out funcType)); Assert.Equal("Action`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] [MemberData(nameof(VoidTypeArgs), true)] public void UnsuccessfulGetActionType(Type[] typeArgs) { string paramName = typeArgs.Any(t => t == typeof(void)) || typeArgs.Count(t => t.IsPointer) == 1 ? null : "typeArgs"; AssertExtensions.Throws<ArgumentException>(paramName, () => Expression.GetActionType(typeArgs)); } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] [MemberData(nameof(VoidTypeArgs), true)] public void UnsuccessfulTryGetActionType(Type[] typeArgs) { Type funcType; Assert.False(Expression.TryGetActionType(typeArgs, out funcType)); } } }
// 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 class ActionTypeTests : DelegateCreationTests { [Fact] public void NullTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs", () => Expression.GetActionType(default(Type[]))); } [Fact] public void NullInTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs", () => Expression.GetActionType(typeof(int), null)); } [Theory] [MemberData(nameof(EmptyTypeArgs))] [MemberData(nameof(ValidTypeArgs), false)] public void SuccessfulGetActionType(Type[] typeArgs) { Type funcType = Expression.GetActionType(typeArgs); if (typeArgs.Length == 0) { Assert.Equal(typeof(Action), funcType); } else { Assert.StartsWith("System.Action`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } } [Theory] [MemberData(nameof(EmptyTypeArgs))] [MemberData(nameof(ValidTypeArgs), false)] public void SuccessfulTryGetActionType(Type[] typeArgs) { Type funcType; Assert.True(Expression.TryGetActionType(typeArgs, out funcType)); if (typeArgs.Length == 0) { Assert.Equal(typeof(Action), funcType); } else { Assert.StartsWith("System.Action`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } } // Open generic type args aren't useful directly with Expressions, but creating them is allowed. [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulGetActionTypeOpenGeneric(Type[] typeArgs) { Type funcType = Expression.GetActionType(typeArgs); Assert.Equal("Action`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulTryGetActionTypeWithOpenGeneric(Type[] typeArgs) { Type funcType; Assert.True(Expression.TryGetActionType(typeArgs, out funcType)); Assert.Equal("Action`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] [MemberData(nameof(VoidTypeArgs), true)] public void UnsuccessfulGetActionType(Type[] typeArgs) { string paramName = typeArgs.Any(t => t == typeof(void)) || typeArgs.Count(t => t.IsPointer) == 1 ? null : "typeArgs"; AssertExtensions.Throws<ArgumentException>(paramName, () => Expression.GetActionType(typeArgs)); } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] [MemberData(nameof(VoidTypeArgs), true)] public void UnsuccessfulTryGetActionType(Type[] typeArgs) { Type funcType; Assert.False(Expression.TryGetActionType(typeArgs, out funcType)); } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Speech/src/Internal/SeekableReadStream.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.IO; namespace System.Speech.Internal { #pragma warning disable 56528 // Override of Dispose(bool) not needed as base stream should not be closed. // Class that is used to wrap a stream that does not support Seek into one that does. // While CacheDataForSeeking is true then Read data is buffered so that Seeking can be done later back into the buffer. // The Read call will first use the buffer and then the actual data once the buffer is read. // After CacheDataForSeeking is set to false data can be read from the buffer but no more Seeking can be done. internal class SeekableReadStream : Stream { #region Constructors internal SeekableReadStream(Stream baseStream) { Debug.Assert(baseStream.CanRead); _canSeek = baseStream.CanSeek; // If the stream is already seekable then don't need to do anything special _baseStream = baseStream; } #endregion #region Internal Properties internal bool CacheDataForSeeking { set { // Currently we can switch the caching off, but not back on again. Not needed for current scenarios. Debug.Assert(!value || _cacheDataForSeeking); _cacheDataForSeeking = value; } } public override bool CanRead { get { return true; } } public override bool CanSeek { get { // Can do seeking only if we are caching data or underlying stream supports it. return (_canSeek || _cacheDataForSeeking); } } public override bool CanWrite { get { return false; } } public override long Length { // Non Seekable streams may not implement this, but we don't have much choice as we can't calculate the Stream length any other way. get { return _baseStream.Length; } } public override long Position { get { if (_canSeek) { // Delegate to underlying Stream: return _baseStream.Position; } else { return _virtualPosition; } } set { if (_canSeek) { // Delegate to underlying Stream: _baseStream.Position = value; } else if (value != _virtualPosition) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), SR.Get(SRID.MustBeGreaterThanZero)); } // We can't check the length here so you can Seek beyond the end of the Stream. This will error later though. if (_cacheDataForSeeking) { if (value < _buffer.Count) { // We're moving within the already buffered data so just move the position: _virtualPosition = value; } else { // We're moving beyond current position. // Thus Read the new data and buffer it. // Read until at new position: long bytesToReadLong = value - _buffer.Count; if (bytesToReadLong > int.MaxValue) { throw new NotSupportedException(SR.Get(SRID.SeekNotSupported)); } byte[] readBuffer = new byte[bytesToReadLong]; Helpers.BlockingRead(_baseStream, readBuffer, 0, (int)bytesToReadLong); // Copy from readBuffer into cache: _buffer.AddRange(readBuffer); _virtualPosition = value; } } else { // No longer caching data so we can't seek around. // Limited cases of this could be supported if needed. throw new NotSupportedException(SR.Get(SRID.SeekNotSupported)); } } } } #endregion #region Internal Methods public override int Read(byte[] buffer, int offset, int count) { if (_canSeek) { // Delegate to underlying Stream: return _baseStream.Read(buffer, offset, count); } else { int bytesRead = 0; if (_virtualPosition < _buffer.Count) { // if new position inside buffer then read until at end of buffer int toCopy = (int)(_buffer.Count - _virtualPosition); if (toCopy > count) { toCopy = count; } _buffer.CopyTo((int)_virtualPosition, buffer, offset, toCopy); count -= toCopy; _virtualPosition += toCopy; offset += toCopy; bytesRead += toCopy; if (!_cacheDataForSeeking && _virtualPosition >= _buffer.Count) { // Used up all the buffer, free. _buffer.Clear(); } } if (count > 0) { // Still data to Read so read it from the base Stream: int localBytesRead = _baseStream.Read(buffer, offset, count); bytesRead += localBytesRead; _virtualPosition += localBytesRead; if (_cacheDataForSeeking) { // if caching then extend Stream. _buffer.Capacity += localBytesRead; // Copy from buffer + offset for bytesRead for (int i = 0; i < localBytesRead; i++) { _buffer.Add(buffer[offset + i]); } } // Even if we didn't read every requested byte we can return - that's the contract on Stream.Read. } return bytesRead; } } public override long Seek(long offset, SeekOrigin origin) { long position; checked // Check for integer overflow { switch (origin) { case SeekOrigin.Begin: position = offset; break; case SeekOrigin.Current: position = Position + offset; break; case SeekOrigin.End: position = Length + offset; break; default: throw new ArgumentException(SR.Get(SRID.EnumInvalid, "SeekOrigin"), nameof(origin)); } } Position = position; // Actually update position, checks for out of range return position; } public override void SetLength(long value) { throw new NotSupportedException(SR.Get(SRID.SeekNotSupported)); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(SR.Get(SRID.StreamMustBeWriteable)); } public override void Flush() { _baseStream.Flush(); } #endregion #region Private Fields private long _virtualPosition; private List<byte> _buffer = new(); // Data cached from start of stream onwards. private Stream _baseStream; private bool _cacheDataForSeeking = true; private bool _canSeek; #endregion } #pragma warning restore 56528 }
// 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.IO; namespace System.Speech.Internal { #pragma warning disable 56528 // Override of Dispose(bool) not needed as base stream should not be closed. // Class that is used to wrap a stream that does not support Seek into one that does. // While CacheDataForSeeking is true then Read data is buffered so that Seeking can be done later back into the buffer. // The Read call will first use the buffer and then the actual data once the buffer is read. // After CacheDataForSeeking is set to false data can be read from the buffer but no more Seeking can be done. internal class SeekableReadStream : Stream { #region Constructors internal SeekableReadStream(Stream baseStream) { Debug.Assert(baseStream.CanRead); _canSeek = baseStream.CanSeek; // If the stream is already seekable then don't need to do anything special _baseStream = baseStream; } #endregion #region Internal Properties internal bool CacheDataForSeeking { set { // Currently we can switch the caching off, but not back on again. Not needed for current scenarios. Debug.Assert(!value || _cacheDataForSeeking); _cacheDataForSeeking = value; } } public override bool CanRead { get { return true; } } public override bool CanSeek { get { // Can do seeking only if we are caching data or underlying stream supports it. return (_canSeek || _cacheDataForSeeking); } } public override bool CanWrite { get { return false; } } public override long Length { // Non Seekable streams may not implement this, but we don't have much choice as we can't calculate the Stream length any other way. get { return _baseStream.Length; } } public override long Position { get { if (_canSeek) { // Delegate to underlying Stream: return _baseStream.Position; } else { return _virtualPosition; } } set { if (_canSeek) { // Delegate to underlying Stream: _baseStream.Position = value; } else if (value != _virtualPosition) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), SR.Get(SRID.MustBeGreaterThanZero)); } // We can't check the length here so you can Seek beyond the end of the Stream. This will error later though. if (_cacheDataForSeeking) { if (value < _buffer.Count) { // We're moving within the already buffered data so just move the position: _virtualPosition = value; } else { // We're moving beyond current position. // Thus Read the new data and buffer it. // Read until at new position: long bytesToReadLong = value - _buffer.Count; if (bytesToReadLong > int.MaxValue) { throw new NotSupportedException(SR.Get(SRID.SeekNotSupported)); } byte[] readBuffer = new byte[bytesToReadLong]; Helpers.BlockingRead(_baseStream, readBuffer, 0, (int)bytesToReadLong); // Copy from readBuffer into cache: _buffer.AddRange(readBuffer); _virtualPosition = value; } } else { // No longer caching data so we can't seek around. // Limited cases of this could be supported if needed. throw new NotSupportedException(SR.Get(SRID.SeekNotSupported)); } } } } #endregion #region Internal Methods public override int Read(byte[] buffer, int offset, int count) { if (_canSeek) { // Delegate to underlying Stream: return _baseStream.Read(buffer, offset, count); } else { int bytesRead = 0; if (_virtualPosition < _buffer.Count) { // if new position inside buffer then read until at end of buffer int toCopy = (int)(_buffer.Count - _virtualPosition); if (toCopy > count) { toCopy = count; } _buffer.CopyTo((int)_virtualPosition, buffer, offset, toCopy); count -= toCopy; _virtualPosition += toCopy; offset += toCopy; bytesRead += toCopy; if (!_cacheDataForSeeking && _virtualPosition >= _buffer.Count) { // Used up all the buffer, free. _buffer.Clear(); } } if (count > 0) { // Still data to Read so read it from the base Stream: int localBytesRead = _baseStream.Read(buffer, offset, count); bytesRead += localBytesRead; _virtualPosition += localBytesRead; if (_cacheDataForSeeking) { // if caching then extend Stream. _buffer.Capacity += localBytesRead; // Copy from buffer + offset for bytesRead for (int i = 0; i < localBytesRead; i++) { _buffer.Add(buffer[offset + i]); } } // Even if we didn't read every requested byte we can return - that's the contract on Stream.Read. } return bytesRead; } } public override long Seek(long offset, SeekOrigin origin) { long position; checked // Check for integer overflow { switch (origin) { case SeekOrigin.Begin: position = offset; break; case SeekOrigin.Current: position = Position + offset; break; case SeekOrigin.End: position = Length + offset; break; default: throw new ArgumentException(SR.Get(SRID.EnumInvalid, "SeekOrigin"), nameof(origin)); } } Position = position; // Actually update position, checks for out of range return position; } public override void SetLength(long value) { throw new NotSupportedException(SR.Get(SRID.SeekNotSupported)); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(SR.Get(SRID.StreamMustBeWriteable)); } public override void Flush() { _baseStream.Flush(); } #endregion #region Private Fields private long _virtualPosition; private List<byte> _buffer = new(); // Data cached from start of stream onwards. private Stream _baseStream; private bool _cacheDataForSeeking = true; private bool _canSeek; #endregion } #pragma warning restore 56528 }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh.Vector64.Int16.Vector64.Int16.3.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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3() { var test = new ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3(); 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 ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3 { 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(ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3 testClass) { var result = AdvSimd.Arm64.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(_fld1, _fld2, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), 3 ); 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 readonly byte Imm = 3; 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 ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3() { 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 ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3() { 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), 3 ); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), 3 ); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), (byte)3 }); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), (byte)3 }); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( _clsVar1, _clsVar2, 3 ); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(pClsVar2)), 3 ); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(op1, op2, 3); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3(); var result = AdvSimd.Arm64.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(test._fld1, test._fld2, 3); 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 ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(_fld1, _fld2, 3); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), 3 ); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(test._fld1, test._fld2, 3); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&test._fld2)), 3 ); 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> firstOp, Vector64<Int16> secondOp, 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]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), secondOp); 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* firstOp, void* secondOp, 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>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (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[] firstOp, Int16[] secondOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.MultiplyRoundedDoublingSaturateHigh(firstOp[0], secondOp[Imm]) != 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh)}<Int16>(Vector64<Int16>, Vector64<Int16>, 3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); 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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3() { var test = new ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3(); 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 ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3 { 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(ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3 testClass) { var result = AdvSimd.Arm64.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(_fld1, _fld2, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), 3 ); 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 readonly byte Imm = 3; 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 ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3() { 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 ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3() { 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), 3 ); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), 3 ); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr), (byte)3 }); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)), (byte)3 }); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( _clsVar1, _clsVar2, 3 ); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(pClsVar2)), 3 ); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(op1, op2, 3); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3(); var result = AdvSimd.Arm64.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(test._fld1, test._fld2, 3); 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 ImmBinaryOpTest__MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh_Vector64_Int16_Vector64_Int16_3(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(_fld1, _fld2, 3); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)), 3 ); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(test._fld1, test._fld2, 3); 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&test._fld2)), 3 ); 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> firstOp, Vector64<Int16> secondOp, 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]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), secondOp); 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* firstOp, void* secondOp, 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>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (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[] firstOp, Int16[] secondOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.MultiplyRoundedDoublingSaturateHigh(firstOp[0], secondOp[Imm]) != 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.MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh)}<Int16>(Vector64<Int16>, Vector64<Int16>, 3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/tests/JIT/Math/Functions/Single/SinSingle.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; namespace System.MathBenchmarks { public partial class Single { // Tests MathF.Sin(float) over 5000 iterations for the domain -PI/2, +PI/2 private const float sinDelta = 0.000628318531f; private const float sinExpectedResult = 1.03592682f; public void Sin() => SinTest(); public static void SinTest() { float result = 0.0f, value = -1.57079633f; for (int iteration = 0; iteration < MathTests.Iterations; iteration++) { value += sinDelta; result += MathF.Sin(value); } float diff = MathF.Abs(sinExpectedResult - result); if (diff > MathTests.SingleEpsilon) { throw new Exception($"Expected Result {sinExpectedResult,10:g9}; Actual Result {result,10:g9}"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace System.MathBenchmarks { public partial class Single { // Tests MathF.Sin(float) over 5000 iterations for the domain -PI/2, +PI/2 private const float sinDelta = 0.000628318531f; private const float sinExpectedResult = 1.03592682f; public void Sin() => SinTest(); public static void SinTest() { float result = 0.0f, value = -1.57079633f; for (int iteration = 0; iteration < MathTests.Iterations; iteration++) { value += sinDelta; result += MathF.Sin(value); } float diff = MathF.Abs(sinExpectedResult - result); if (diff > MathTests.SingleEpsilon) { throw new Exception($"Expected Result {sinExpectedResult,10:g9}; Actual Result {result,10:g9}"); } } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.NonUap.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.ComponentModel; using System.Runtime.Versioning; namespace System.Diagnostics { public partial class Process : IDisposable { [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] public void Kill(bool entireProcessTree) { if (!entireProcessTree) { Kill(); } else { EnsureState(State.Associated | State.IsLocal); if (IsSelfOrDescendantOf(GetCurrentProcess())) throw new InvalidOperationException(SR.KillEntireProcessTree_DisallowedBecauseTreeContainsCallingProcess); List<Exception>? result = KillTree(); if (result != null && result.Count != 0) throw new AggregateException(SR.KillEntireProcessTree_TerminationIncomplete, result); } } private bool IsSelfOrDescendantOf(Process processOfInterest) { if (Equals(processOfInterest)) return true; Process[] allProcesses = GetProcesses(); try { var descendantProcesses = new Queue<Process>(); Process? current = this; do { foreach (Process candidate in current.GetChildProcesses(allProcesses)) { if (processOfInterest.Equals(candidate)) return true; descendantProcesses.Enqueue(candidate); } } while (descendantProcesses.TryDequeue(out current)); } finally { foreach (Process process in allProcesses) { process.Dispose(); } } return false; } /// <summary> /// Returns all immediate child processes. /// </summary> private IReadOnlyList<Process> GetChildProcesses(Process[]? processes = null) { bool internallyInitializedProcesses = processes == null; processes = processes ?? GetProcesses(); List<Process> childProcesses = new List<Process>(); foreach (Process possibleChildProcess in processes) { // Only support disposing if this method initialized the set of processes being searched bool dispose = internallyInitializedProcesses; try { if (IsParentOf(possibleChildProcess)) { childProcesses.Add(possibleChildProcess); dispose = false; } } finally { if (dispose) possibleChildProcess.Dispose(); } } return childProcesses; } private static bool IsProcessInvalidException(Exception e) => // InvalidOperationException signifies conditions such as the process already being dead. // Win32Exception signifies issues such as insufficient permissions to get details on the process. // In either case, the predicate couldn't be applied so return the fallback result. e is InvalidOperationException || e is Win32Exception; } }
// 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.ComponentModel; using System.Runtime.Versioning; namespace System.Diagnostics { public partial class Process : IDisposable { [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] public void Kill(bool entireProcessTree) { if (!entireProcessTree) { Kill(); } else { EnsureState(State.Associated | State.IsLocal); if (IsSelfOrDescendantOf(GetCurrentProcess())) throw new InvalidOperationException(SR.KillEntireProcessTree_DisallowedBecauseTreeContainsCallingProcess); List<Exception>? result = KillTree(); if (result != null && result.Count != 0) throw new AggregateException(SR.KillEntireProcessTree_TerminationIncomplete, result); } } private bool IsSelfOrDescendantOf(Process processOfInterest) { if (Equals(processOfInterest)) return true; Process[] allProcesses = GetProcesses(); try { var descendantProcesses = new Queue<Process>(); Process? current = this; do { foreach (Process candidate in current.GetChildProcesses(allProcesses)) { if (processOfInterest.Equals(candidate)) return true; descendantProcesses.Enqueue(candidate); } } while (descendantProcesses.TryDequeue(out current)); } finally { foreach (Process process in allProcesses) { process.Dispose(); } } return false; } /// <summary> /// Returns all immediate child processes. /// </summary> private IReadOnlyList<Process> GetChildProcesses(Process[]? processes = null) { bool internallyInitializedProcesses = processes == null; processes = processes ?? GetProcesses(); List<Process> childProcesses = new List<Process>(); foreach (Process possibleChildProcess in processes) { // Only support disposing if this method initialized the set of processes being searched bool dispose = internallyInitializedProcesses; try { if (IsParentOf(possibleChildProcess)) { childProcesses.Add(possibleChildProcess); dispose = false; } } finally { if (dispose) possibleChildProcess.Dispose(); } } return childProcesses; } private static bool IsProcessInvalidException(Exception e) => // InvalidOperationException signifies conditions such as the process already being dead. // Win32Exception signifies issues such as insufficient permissions to get details on the process. // In either case, the predicate couldn't be applied so return the fallback result. e is InvalidOperationException || e is Win32Exception; } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Private.CoreLib/src/System/Text/Encoder.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.Runtime.InteropServices; namespace System.Text { // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // public abstract class Encoder { internal EncoderFallback? _fallback; internal EncoderFallbackBuffer? _fallbackBuffer; protected Encoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } public EncoderFallback? Fallback { get => _fallback; set { ArgumentNullException.ThrowIfNull(value); // Can't change fallback if buffer is wrong if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, nameof(value)); _fallback = value; _fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. public EncoderFallbackBuffer FallbackBuffer { get { if (_fallbackBuffer == null) { if (_fallback != null) _fallbackBuffer = _fallback.CreateFallbackBuffer(); else _fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return _fallbackBuffer; } } internal bool InternalHasFallbackBuffer => _fallbackBuffer != null; // Reset the Encoder // // Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset(). // // Virtual implementation has to call GetBytes with flush and a big enough buffer to clear a 0 char string // We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big. public virtual void Reset() { char[] charTemp = Array.Empty<char>(); byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)]; GetBytes(charTemp, 0, 0, byteTemp, 0, true); if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } // Returns the number of bytes the next call to GetBytes will // produce if presented with the given range of characters and the given // value of the flush parameter. The returned value takes into // account the state in which the encoder was left following the last call // to GetBytes. The state of the encoder is not affected by a call // to this method. // public abstract int GetByteCount(char[] chars, int index, int count, bool flush); // We expect this to be the workhorse for NLS encodings // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so avoid this method if you might be calling external encodings. [CLSCompliant(false)] public virtual unsafe int GetByteCount(char* chars!!, int count, bool flush) { // Validate input parameters if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); char[] arrChar = new char[count]; int index; for (index = 0; index < count; index++) arrChar[index] = chars[index]; return GetByteCount(arrChar, 0, count, flush); } public virtual unsafe int GetByteCount(ReadOnlySpan<char> chars, bool flush) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetByteCount(charsPtr, chars.Length, flush); } } // Encodes a range of characters in a character array into a range of bytes // in a byte array. The method encodes charCount characters from // chars starting at index charIndex, storing the resulting // bytes in bytes starting at index byteIndex. The encoding // takes into account the state in which the encoder was left following the // last call to this method. The flush parameter indicates whether // the encoder should flush any shift-states and partial characters at the // end of the conversion. To ensure correct termination of a sequence of // blocks of encoded bytes, the last call to GetBytes should specify // a value of true for the flush parameter. // // An exception occurs if the byte array is not large enough to hold the // complete encoding of the characters. The GetByteCount method can // be used to determine the exact number of bytes that will be produced for // a given range of characters. Alternatively, the GetMaxByteCount // method of the Encoding that produced this encoder can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush); // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implementation of an // external GetBytes() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the byte[] to our byte* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow byteCount either. [CLSCompliant(false)] public virtual unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, int byteCount, bool flush) { // Validate input parameters if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Get the char array to convert char[] arrChar = new char[charCount]; int index; for (index = 0; index < charCount; index++) arrChar[index] = chars[index]; // Get the byte array to fill byte[] arrByte = new byte[byteCount]; // Do the work int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush); Debug.Assert(result <= byteCount, "Returned more bytes than we have space for"); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't // rely on result because it could be a 3rd party implementation. We need // to make sure we never copy more than byteCount bytes no matter the value // of result if (result < byteCount) byteCount = result; // Don't copy too many bytes! for (index = 0; index < byteCount; index++) bytes[index] = arrByte[index]; return byteCount; } public virtual unsafe int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length, flush); } } // This method is used to avoid running out of output buffer space. // It will encode until it runs out of chars, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted chars and output bytes used. // It will only throw a buffer overflow exception if the entire lenght of bytes[] is // too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) public virtual void Convert(char[] chars!!, int charIndex, int charCount, byte[] bytes!!, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); charsUsed = charCount; // Its easy to do if it won't overrun our buffer. // Note: We don't want to call unsafe version because that might be an untrusted version // which could be really unsafe and we don't want to mix it up. while (charsUsed > 0) { if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush); completed = (charsUsed == charCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } // Same thing, but using pointers // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [CLSCompliant(false)] public virtual unsafe void Convert(char* chars!!, int charCount, byte* bytes!!, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Get ready to do it charsUsed = charCount; // Its easy to do if it won't overrun our buffer. while (charsUsed > 0) { if (GetByteCount(chars, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush); completed = (charsUsed == charCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } public virtual unsafe void Convert(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { Convert(charsPtr, chars.Length, bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out completed); } } } }
// 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.Runtime.InteropServices; namespace System.Text { // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // public abstract class Encoder { internal EncoderFallback? _fallback; internal EncoderFallbackBuffer? _fallbackBuffer; protected Encoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } public EncoderFallback? Fallback { get => _fallback; set { ArgumentNullException.ThrowIfNull(value); // Can't change fallback if buffer is wrong if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, nameof(value)); _fallback = value; _fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. public EncoderFallbackBuffer FallbackBuffer { get { if (_fallbackBuffer == null) { if (_fallback != null) _fallbackBuffer = _fallback.CreateFallbackBuffer(); else _fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return _fallbackBuffer; } } internal bool InternalHasFallbackBuffer => _fallbackBuffer != null; // Reset the Encoder // // Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset(). // // Virtual implementation has to call GetBytes with flush and a big enough buffer to clear a 0 char string // We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big. public virtual void Reset() { char[] charTemp = Array.Empty<char>(); byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)]; GetBytes(charTemp, 0, 0, byteTemp, 0, true); if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } // Returns the number of bytes the next call to GetBytes will // produce if presented with the given range of characters and the given // value of the flush parameter. The returned value takes into // account the state in which the encoder was left following the last call // to GetBytes. The state of the encoder is not affected by a call // to this method. // public abstract int GetByteCount(char[] chars, int index, int count, bool flush); // We expect this to be the workhorse for NLS encodings // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so avoid this method if you might be calling external encodings. [CLSCompliant(false)] public virtual unsafe int GetByteCount(char* chars!!, int count, bool flush) { // Validate input parameters if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); char[] arrChar = new char[count]; int index; for (index = 0; index < count; index++) arrChar[index] = chars[index]; return GetByteCount(arrChar, 0, count, flush); } public virtual unsafe int GetByteCount(ReadOnlySpan<char> chars, bool flush) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetByteCount(charsPtr, chars.Length, flush); } } // Encodes a range of characters in a character array into a range of bytes // in a byte array. The method encodes charCount characters from // chars starting at index charIndex, storing the resulting // bytes in bytes starting at index byteIndex. The encoding // takes into account the state in which the encoder was left following the // last call to this method. The flush parameter indicates whether // the encoder should flush any shift-states and partial characters at the // end of the conversion. To ensure correct termination of a sequence of // blocks of encoded bytes, the last call to GetBytes should specify // a value of true for the flush parameter. // // An exception occurs if the byte array is not large enough to hold the // complete encoding of the characters. The GetByteCount method can // be used to determine the exact number of bytes that will be produced for // a given range of characters. Alternatively, the GetMaxByteCount // method of the Encoding that produced this encoder can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush); // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implementation of an // external GetBytes() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the byte[] to our byte* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow byteCount either. [CLSCompliant(false)] public virtual unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, int byteCount, bool flush) { // Validate input parameters if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Get the char array to convert char[] arrChar = new char[charCount]; int index; for (index = 0; index < charCount; index++) arrChar[index] = chars[index]; // Get the byte array to fill byte[] arrByte = new byte[byteCount]; // Do the work int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush); Debug.Assert(result <= byteCount, "Returned more bytes than we have space for"); // Copy the byte array // WARNING: We MUST make sure that we don't copy too many bytes. We can't // rely on result because it could be a 3rd party implementation. We need // to make sure we never copy more than byteCount bytes no matter the value // of result if (result < byteCount) byteCount = result; // Don't copy too many bytes! for (index = 0; index < byteCount; index++) bytes[index] = arrByte[index]; return byteCount; } public virtual unsafe int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length, flush); } } // This method is used to avoid running out of output buffer space. // It will encode until it runs out of chars, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted chars and output bytes used. // It will only throw a buffer overflow exception if the entire lenght of bytes[] is // too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) public virtual void Convert(char[] chars!!, int charIndex, int charCount, byte[] bytes!!, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); charsUsed = charCount; // Its easy to do if it won't overrun our buffer. // Note: We don't want to call unsafe version because that might be an untrusted version // which could be really unsafe and we don't want to mix it up. while (charsUsed > 0) { if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush); completed = (charsUsed == charCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } // Same thing, but using pointers // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [CLSCompliant(false)] public virtual unsafe void Convert(char* chars!!, int charCount, byte* bytes!!, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Get ready to do it charsUsed = charCount; // Its easy to do if it won't overrun our buffer. while (charsUsed > 0) { if (GetByteCount(chars, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush); completed = (charsUsed == charCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; charsUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } public virtual unsafe void Convert(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars)) fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { Convert(charsPtr, chars.Length, bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out completed); } } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/tests/JIT/Regression/JitBlue/GitHub_17329/GitHub_17329.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; // Having an UnsafeValueTypeAttribute on a struct causes incoming arguments to be // spilled into shadow copies and the struct promotion optimization does not // currently handle this properly. // [UnsafeValueTypeAttribute] struct DangerousBuffer { public long a; public long b; public long c; } struct Point1 { long x; public Point1(long _x) { x = _x; } public void Increase(ref Point1 s, long amount) { x = s.x + amount; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public long Value() { return x; } } class TestCase { static public long[] arr; unsafe static long Test(int size, Point1 a, Point1 b, Point1 c) { // Mutate the values stored in a, b and c // So if these have a shadow copy we will notice // a.Increase(ref a, arr[0]); b.Increase(ref b, arr[1]); c.Increase(ref c, arr[2]); DangerousBuffer db = new DangerousBuffer(); db.a = -1; db.b = -2; db.c = -3; long* x1 = stackalloc long[size]; long sum = 0; if (size >= 3) { x1[0] = a.Value(); x1[1] = b.Value(); x1[2] = c.Value(); for (int i = 0; i < size; i++) { sum += x1[i]; } } return sum; } static int Main() { long testResult = 0; int mainResult = 0; Point1 p1 = new Point1(1); Point1 p2 = new Point1(3); Point1 p3 = new Point1(5); arr = new long[3]; arr[0] = 9; arr[1] = 10; arr[2] = 11; testResult = Test(3, p1, p2, p3); if (testResult != 39) { Console.WriteLine("FAILED!"); mainResult = -1; } else { Console.WriteLine("passed"); mainResult = 100; } return mainResult; } }
// 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; // Having an UnsafeValueTypeAttribute on a struct causes incoming arguments to be // spilled into shadow copies and the struct promotion optimization does not // currently handle this properly. // [UnsafeValueTypeAttribute] struct DangerousBuffer { public long a; public long b; public long c; } struct Point1 { long x; public Point1(long _x) { x = _x; } public void Increase(ref Point1 s, long amount) { x = s.x + amount; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public long Value() { return x; } } class TestCase { static public long[] arr; unsafe static long Test(int size, Point1 a, Point1 b, Point1 c) { // Mutate the values stored in a, b and c // So if these have a shadow copy we will notice // a.Increase(ref a, arr[0]); b.Increase(ref b, arr[1]); c.Increase(ref c, arr[2]); DangerousBuffer db = new DangerousBuffer(); db.a = -1; db.b = -2; db.c = -3; long* x1 = stackalloc long[size]; long sum = 0; if (size >= 3) { x1[0] = a.Value(); x1[1] = b.Value(); x1[2] = c.Value(); for (int i = 0; i < size; i++) { sum += x1[i]; } } return sum; } static int Main() { long testResult = 0; int mainResult = 0; Point1 p1 = new Point1(1); Point1 p2 = new Point1(3); Point1 p3 = new Point1(5); arr = new long[3]; arr[0] = 9; arr[1] = 10; arr[2] = 11; testResult = Test(3, p1, p2, p3); if (testResult != 39) { Console.WriteLine("FAILED!"); mainResult = -1; } else { Console.WriteLine("passed"); mainResult = 100; } return mainResult; } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Globalization/ref/System.Globalization.Forwards.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.Calendar))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CalendarWeekRule))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CompareOptions))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CompareInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CultureInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.DateTimeFormatInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.NumberFormatInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.TextInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CultureNotFoundException))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.UnicodeCategory))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CharUnicodeInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.RegionInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.StringInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.TextElementEnumerator))]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.Calendar))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CalendarWeekRule))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CompareOptions))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CompareInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CultureInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.DateTimeFormatInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.NumberFormatInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.TextInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CultureNotFoundException))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.UnicodeCategory))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.CharUnicodeInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.RegionInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.StringInfo))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Globalization.TextElementEnumerator))]
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/HelperTests.Win32Unix.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.IO.IsolatedStorage { public partial class HelperTests { [Fact] public void GetExistingRandomDirectory() { using (var temp = new TempDirectory()) { Assert.Null(Helper.GetExistingRandomDirectory(temp.Path)); string randomPath = Path.Combine(temp.Path, Path.GetRandomFileName(), Path.GetRandomFileName()); Directory.CreateDirectory(randomPath); Assert.Equal(randomPath, Helper.GetExistingRandomDirectory(temp.Path)); } } [Theory, InlineData(IsolatedStorageScope.User), InlineData(IsolatedStorageScope.Machine), ] public void GetRandomDirectory(IsolatedStorageScope scope) { using (var temp = new TempDirectory()) { string randomDir = Helper.GetRandomDirectory(temp.Path, scope); Assert.True(Directory.Exists(randomDir)); } } } }
// 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.IO.IsolatedStorage { public partial class HelperTests { [Fact] public void GetExistingRandomDirectory() { using (var temp = new TempDirectory()) { Assert.Null(Helper.GetExistingRandomDirectory(temp.Path)); string randomPath = Path.Combine(temp.Path, Path.GetRandomFileName(), Path.GetRandomFileName()); Directory.CreateDirectory(randomPath); Assert.Equal(randomPath, Helper.GetExistingRandomDirectory(temp.Path)); } } [Theory, InlineData(IsolatedStorageScope.User), InlineData(IsolatedStorageScope.Machine), ] public void GetRandomDirectory(IsolatedStorageScope scope) { using (var temp = new TempDirectory()) { string randomDir = Helper.GetRandomDirectory(temp.Path, scope); Assert.True(Directory.Exists(randomDir)); } } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/GetAndWithLowerAndUpper.SByte.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.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithLowerAndUpperSByte() { var test = new VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperSByte(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperSByte { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); SByte[] values = new SByte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSByte(); } Vector256<SByte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); Vector128<SByte> lowerResult = value.GetLower(); Vector128<SByte> upperResult = value.GetUpper(); ValidateGetResult(lowerResult, upperResult, values); Vector256<SByte> result = value.WithLower(upperResult); result = result.WithUpper(lowerResult); ValidateWithResult(result, values); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); SByte[] values = new SByte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSByte(); } Vector256<SByte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); object lowerResult = typeof(Vector256) .GetMethod(nameof(Vector256.GetLower)) .MakeGenericMethod(typeof(SByte)) .Invoke(null, new object[] { value }); object upperResult = typeof(Vector256) .GetMethod(nameof(Vector256.GetUpper)) .MakeGenericMethod(typeof(SByte)) .Invoke(null, new object[] { value }); ValidateGetResult((Vector128<SByte>)(lowerResult), (Vector128<SByte>)(upperResult), values); object result = typeof(Vector256) .GetMethod(nameof(Vector256.WithLower)) .MakeGenericMethod(typeof(SByte)) .Invoke(null, new object[] { value, upperResult }); result = typeof(Vector256) .GetMethod(nameof(Vector256.WithUpper)) .MakeGenericMethod(typeof(SByte)) .Invoke(null, new object[] { result, lowerResult }); ValidateWithResult((Vector256<SByte>)(result), values); } private void ValidateGetResult(Vector128<SByte> lowerResult, Vector128<SByte> upperResult, SByte[] values, [CallerMemberName] string method = "") { SByte[] lowerElements = new SByte[ElementCount / 2]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref lowerElements[0]), lowerResult); SByte[] upperElements = new SByte[ElementCount / 2]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref upperElements[0]), upperResult); ValidateGetResult(lowerElements, upperElements, values, method); } private void ValidateGetResult(SByte[] lowerResult, SByte[] upperResult, SByte[] values, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount / 2; i++) { if (lowerResult[i] != values[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<SByte>.GetLower(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", lowerResult)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = true; for (int i = ElementCount / 2; i < ElementCount; i++) { if (upperResult[i - (ElementCount / 2)] != values[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<SByte>.GetUpper(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", upperResult)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } private void ValidateWithResult(Vector256<SByte> result, SByte[] values, [CallerMemberName] string method = "") { SByte[] resultElements = new SByte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, method); } private void ValidateWithResult(SByte[] result, SByte[] values, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount / 2; i++) { if (result[i] != values[i + (ElementCount / 2)]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<SByte.WithLower(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = true; for (int i = ElementCount / 2; i < ElementCount; i++) { if (result[i] != values[i - (ElementCount / 2)]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<SByte.WithUpper(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); 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.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithLowerAndUpperSByte() { var test = new VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperSByte(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperSByte { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); SByte[] values = new SByte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSByte(); } Vector256<SByte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); Vector128<SByte> lowerResult = value.GetLower(); Vector128<SByte> upperResult = value.GetUpper(); ValidateGetResult(lowerResult, upperResult, values); Vector256<SByte> result = value.WithLower(upperResult); result = result.WithUpper(lowerResult); ValidateWithResult(result, values); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); SByte[] values = new SByte[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSByte(); } Vector256<SByte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]); object lowerResult = typeof(Vector256) .GetMethod(nameof(Vector256.GetLower)) .MakeGenericMethod(typeof(SByte)) .Invoke(null, new object[] { value }); object upperResult = typeof(Vector256) .GetMethod(nameof(Vector256.GetUpper)) .MakeGenericMethod(typeof(SByte)) .Invoke(null, new object[] { value }); ValidateGetResult((Vector128<SByte>)(lowerResult), (Vector128<SByte>)(upperResult), values); object result = typeof(Vector256) .GetMethod(nameof(Vector256.WithLower)) .MakeGenericMethod(typeof(SByte)) .Invoke(null, new object[] { value, upperResult }); result = typeof(Vector256) .GetMethod(nameof(Vector256.WithUpper)) .MakeGenericMethod(typeof(SByte)) .Invoke(null, new object[] { result, lowerResult }); ValidateWithResult((Vector256<SByte>)(result), values); } private void ValidateGetResult(Vector128<SByte> lowerResult, Vector128<SByte> upperResult, SByte[] values, [CallerMemberName] string method = "") { SByte[] lowerElements = new SByte[ElementCount / 2]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref lowerElements[0]), lowerResult); SByte[] upperElements = new SByte[ElementCount / 2]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref upperElements[0]), upperResult); ValidateGetResult(lowerElements, upperElements, values, method); } private void ValidateGetResult(SByte[] lowerResult, SByte[] upperResult, SByte[] values, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount / 2; i++) { if (lowerResult[i] != values[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<SByte>.GetLower(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", lowerResult)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = true; for (int i = ElementCount / 2; i < ElementCount; i++) { if (upperResult[i - (ElementCount / 2)] != values[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<SByte>.GetUpper(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", upperResult)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } private void ValidateWithResult(Vector256<SByte> result, SByte[] values, [CallerMemberName] string method = "") { SByte[] resultElements = new SByte[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, method); } private void ValidateWithResult(SByte[] result, SByte[] values, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount / 2; i++) { if (result[i] != values[i + (ElementCount / 2)]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<SByte.WithLower(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = true; for (int i = ElementCount / 2; i < ElementCount; i++) { if (result[i] != values[i - (ElementCount / 2)]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<SByte.WithUpper(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Drawing.Common/src/System/Drawing/Region.Unix.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.Drawing.Drawing2D; using System.Drawing.Internal; using System.Runtime.InteropServices; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing { public partial class Region { public void ReleaseHrgn(IntPtr regionHandle) { if (regionHandle == IntPtr.Zero) { throw new ArgumentNullException(nameof(regionHandle)); } // for libgdiplus HRGN == GpRegion*, and we check the return code int status = Gdip.GdipDeleteRegion(new HandleRef(this, regionHandle)); Gdip.CheckStatus(status); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Drawing.Drawing2D; using System.Drawing.Internal; using System.Runtime.InteropServices; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing { public partial class Region { public void ReleaseHrgn(IntPtr regionHandle) { if (regionHandle == IntPtr.Zero) { throw new ArgumentNullException(nameof(regionHandle)); } // for libgdiplus HRGN == GpRegion*, and we check the return code int status = Gdip.GdipDeleteRegion(new HandleRef(this, regionHandle)); Gdip.CheckStatus(status); } } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/libraries/System.Reflection.MetadataLoadContext/tests/src/Tests/TypeInfoFromProjectN/TypeInfo_GenericTypeArgumentsTests.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.Reflection.Tests { public class TypeInfoDeclaredGenericTypeArgumentsTests { //Interfaces // Verify Generic Arguments [Fact] public static void TestGenericArguments1() { VerifyGenericTypeArguments(typeof(Test_I).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments2() { VerifyGenericTypeArguments(typeof(Test_IG<>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments3() { VerifyGenericTypeArguments(typeof(Test_IG<int>).Project(), new string[] { "Int32" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments4() { VerifyGenericTypeArguments(typeof(Test_IG2<,>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments5() { VerifyGenericTypeArguments(typeof(Test_IG2<int, string>).Project(), new string[] { "Int32", "String" }, null); } // For Structs // Verify Generic Arguments [Fact] public static void TestGenericArguments6() { VerifyGenericTypeArguments(typeof(Test_S).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments7() { VerifyGenericTypeArguments(typeof(Test_SG<>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments8() { VerifyGenericTypeArguments(typeof(Test_SG<int>).Project(), new string[] { "Int32" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments9() { VerifyGenericTypeArguments(typeof(Test_SG2<,>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments10() { VerifyGenericTypeArguments(typeof(Test_SG2<int, string>).Project(), new string[] { "Int32", "String" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments11() { VerifyGenericTypeArguments(typeof(Test_SI).Project(), new string[] { }, new string[] { }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments12() { VerifyGenericTypeArguments(typeof(Test_SIG<>).Project(), new string[] { }, new string[] { "TS" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments13() { VerifyGenericTypeArguments(typeof(Test_SIG<int>).Project(), new string[] { "Int32" }, new string[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments14() { VerifyGenericTypeArguments(typeof(Test_SIG2<,>).Project(), new string[] { }, new string[] { "TS", "VS" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments15() { VerifyGenericTypeArguments(typeof(Test_SIG2<int, string>).Project(), new string[] { "Int32", "String" }, new string[] { "Int32", "String" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments16() { VerifyGenericTypeArguments(typeof(Test_SI_Int).Project(), new string[] { }, new string[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments17() { VerifyGenericTypeArguments(typeof(Test_SIG_Int<>).Project(), new string[] { }, new string[] { "TS", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments18() { VerifyGenericTypeArguments(typeof(Test_SIG_Int<string>).Project(), new string[] { "String" }, new string[] { "String", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments19() { VerifyGenericTypeArguments(typeof(Test_SIG_Int_Int).Project(), new string[] { }, new string[] { "Int32", "Int32" }); } //For classes // Verify Generic Arguments [Fact] public static void TestGenericArguments20() { VerifyGenericTypeArguments(typeof(Test_C).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments21() { VerifyGenericTypeArguments(typeof(Test_CG<>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments22() { VerifyGenericTypeArguments(typeof(Test_CG<int>).Project(), new string[] { "Int32" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments23() { VerifyGenericTypeArguments(typeof(Test_CG2<,>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments24() { VerifyGenericTypeArguments(typeof(Test_CG2<int, string>).Project(), new string[] { "Int32", "String" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments25() { VerifyGenericTypeArguments(typeof(Test_CI).Project(), new string[] { }, new string[] { }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments26() { VerifyGenericTypeArguments(typeof(Test_CIG<int>).Project(), new string[] { "Int32" }, new string[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments27() { VerifyGenericTypeArguments(typeof(Test_CIG2<,>).Project(), new string[] { }, new string[] { "T", "V" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments28() { VerifyGenericTypeArguments(typeof(Test_CIG2<int, string>).Project(), new string[] { "Int32", "String" }, new string[] { "Int32", "String" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments29() { VerifyGenericTypeArguments(typeof(Test_CI_Int).Project(), new string[] { }, new string[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments30() { VerifyGenericTypeArguments(typeof(Test_CIG_Int<>).Project(), new string[] { }, new string[] { "T", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments31() { VerifyGenericTypeArguments(typeof(Test_CIG_Int<string>).Project(), new string[] { "String" }, new string[] { "String", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments32() { VerifyGenericTypeArguments(typeof(Test_CIG_Int_Int).Project(), new string[] { }, new string[] { "Int32", "Int32" }); } //private helper methods private static void VerifyGenericTypeArguments(Type type, string[] expectedGTA, string[] expectedBaseGTA) { //Fix to initialize Reflection string str = typeof(object).Project().Name; TypeInfo typeInfo = type.GetTypeInfo(); Type[] retGenericTypeArguments = typeInfo.GenericTypeArguments; Assert.Equal(expectedGTA.Length, retGenericTypeArguments.Length); for (int i = 0; i < retGenericTypeArguments.Length; i++) { Assert.Equal(expectedGTA[i], retGenericTypeArguments[i].Name); } Type baseType = typeInfo.BaseType; if (baseType == null) return; if (baseType == typeof(ValueType).Project() || baseType == typeof(object).Project()) { Type[] interfaces = getInterfaces(typeInfo); if (interfaces.Length == 0) return; baseType = interfaces[0]; } TypeInfo typeInfoBase = baseType.GetTypeInfo(); retGenericTypeArguments = typeInfoBase.GenericTypeArguments; Assert.Equal(expectedBaseGTA.Length, retGenericTypeArguments.Length); for (int i = 0; i < retGenericTypeArguments.Length; i++) { Assert.Equal(expectedBaseGTA[i], retGenericTypeArguments[i].Name); } } private static Type[] getInterfaces(TypeInfo ti) { List<Type> list = new List<Type>(); IEnumerator<Type> allinterfaces = ti.ImplementedInterfaces.GetEnumerator(); while (allinterfaces.MoveNext()) { list.Add(allinterfaces.Current); } return list.ToArray(); } } //Metadata for Reflection public interface Test_I { } public interface Test_IG<TI> { } public interface Test_IG2<TI, VI> { } public struct Test_S { } public struct Test_SG<TS> { } public struct Test_SG2<TS, VS> { } public struct Test_SI : Test_I { } public struct Test_SIG<TS> : Test_IG<TS> { } public struct Test_SIG2<TS, VS> : Test_IG2<TS, VS> { } public struct Test_SI_Int : Test_IG<int> { } public struct Test_SIG_Int<TS> : Test_IG2<TS, int> { } public struct Test_SIG_Int_Int : Test_IG2<int, int> { } public class Test_C { } public class Test_CG<T> { } public class Test_CG2<T, V> { } public class Test_CI : Test_I { } public class Test_CIG<T> : Test_IG<T> { } public class Test_CIG2<T, V> : Test_IG2<T, V> { } public class Test_CI_Int : Test_IG<int> { } public class Test_CIG_Int<T> : Test_CG2<T, int> { } public class Test_CIG_Int_Int : Test_CG2<int, int> { } }
// 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.Reflection.Tests { public class TypeInfoDeclaredGenericTypeArgumentsTests { //Interfaces // Verify Generic Arguments [Fact] public static void TestGenericArguments1() { VerifyGenericTypeArguments(typeof(Test_I).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments2() { VerifyGenericTypeArguments(typeof(Test_IG<>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments3() { VerifyGenericTypeArguments(typeof(Test_IG<int>).Project(), new string[] { "Int32" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments4() { VerifyGenericTypeArguments(typeof(Test_IG2<,>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments5() { VerifyGenericTypeArguments(typeof(Test_IG2<int, string>).Project(), new string[] { "Int32", "String" }, null); } // For Structs // Verify Generic Arguments [Fact] public static void TestGenericArguments6() { VerifyGenericTypeArguments(typeof(Test_S).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments7() { VerifyGenericTypeArguments(typeof(Test_SG<>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments8() { VerifyGenericTypeArguments(typeof(Test_SG<int>).Project(), new string[] { "Int32" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments9() { VerifyGenericTypeArguments(typeof(Test_SG2<,>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments10() { VerifyGenericTypeArguments(typeof(Test_SG2<int, string>).Project(), new string[] { "Int32", "String" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments11() { VerifyGenericTypeArguments(typeof(Test_SI).Project(), new string[] { }, new string[] { }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments12() { VerifyGenericTypeArguments(typeof(Test_SIG<>).Project(), new string[] { }, new string[] { "TS" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments13() { VerifyGenericTypeArguments(typeof(Test_SIG<int>).Project(), new string[] { "Int32" }, new string[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments14() { VerifyGenericTypeArguments(typeof(Test_SIG2<,>).Project(), new string[] { }, new string[] { "TS", "VS" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments15() { VerifyGenericTypeArguments(typeof(Test_SIG2<int, string>).Project(), new string[] { "Int32", "String" }, new string[] { "Int32", "String" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments16() { VerifyGenericTypeArguments(typeof(Test_SI_Int).Project(), new string[] { }, new string[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments17() { VerifyGenericTypeArguments(typeof(Test_SIG_Int<>).Project(), new string[] { }, new string[] { "TS", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments18() { VerifyGenericTypeArguments(typeof(Test_SIG_Int<string>).Project(), new string[] { "String" }, new string[] { "String", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments19() { VerifyGenericTypeArguments(typeof(Test_SIG_Int_Int).Project(), new string[] { }, new string[] { "Int32", "Int32" }); } //For classes // Verify Generic Arguments [Fact] public static void TestGenericArguments20() { VerifyGenericTypeArguments(typeof(Test_C).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments21() { VerifyGenericTypeArguments(typeof(Test_CG<>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments22() { VerifyGenericTypeArguments(typeof(Test_CG<int>).Project(), new string[] { "Int32" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments23() { VerifyGenericTypeArguments(typeof(Test_CG2<,>).Project(), new string[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments24() { VerifyGenericTypeArguments(typeof(Test_CG2<int, string>).Project(), new string[] { "Int32", "String" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments25() { VerifyGenericTypeArguments(typeof(Test_CI).Project(), new string[] { }, new string[] { }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments26() { VerifyGenericTypeArguments(typeof(Test_CIG<int>).Project(), new string[] { "Int32" }, new string[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments27() { VerifyGenericTypeArguments(typeof(Test_CIG2<,>).Project(), new string[] { }, new string[] { "T", "V" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments28() { VerifyGenericTypeArguments(typeof(Test_CIG2<int, string>).Project(), new string[] { "Int32", "String" }, new string[] { "Int32", "String" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments29() { VerifyGenericTypeArguments(typeof(Test_CI_Int).Project(), new string[] { }, new string[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments30() { VerifyGenericTypeArguments(typeof(Test_CIG_Int<>).Project(), new string[] { }, new string[] { "T", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments31() { VerifyGenericTypeArguments(typeof(Test_CIG_Int<string>).Project(), new string[] { "String" }, new string[] { "String", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments32() { VerifyGenericTypeArguments(typeof(Test_CIG_Int_Int).Project(), new string[] { }, new string[] { "Int32", "Int32" }); } //private helper methods private static void VerifyGenericTypeArguments(Type type, string[] expectedGTA, string[] expectedBaseGTA) { //Fix to initialize Reflection string str = typeof(object).Project().Name; TypeInfo typeInfo = type.GetTypeInfo(); Type[] retGenericTypeArguments = typeInfo.GenericTypeArguments; Assert.Equal(expectedGTA.Length, retGenericTypeArguments.Length); for (int i = 0; i < retGenericTypeArguments.Length; i++) { Assert.Equal(expectedGTA[i], retGenericTypeArguments[i].Name); } Type baseType = typeInfo.BaseType; if (baseType == null) return; if (baseType == typeof(ValueType).Project() || baseType == typeof(object).Project()) { Type[] interfaces = getInterfaces(typeInfo); if (interfaces.Length == 0) return; baseType = interfaces[0]; } TypeInfo typeInfoBase = baseType.GetTypeInfo(); retGenericTypeArguments = typeInfoBase.GenericTypeArguments; Assert.Equal(expectedBaseGTA.Length, retGenericTypeArguments.Length); for (int i = 0; i < retGenericTypeArguments.Length; i++) { Assert.Equal(expectedBaseGTA[i], retGenericTypeArguments[i].Name); } } private static Type[] getInterfaces(TypeInfo ti) { List<Type> list = new List<Type>(); IEnumerator<Type> allinterfaces = ti.ImplementedInterfaces.GetEnumerator(); while (allinterfaces.MoveNext()) { list.Add(allinterfaces.Current); } return list.ToArray(); } } //Metadata for Reflection public interface Test_I { } public interface Test_IG<TI> { } public interface Test_IG2<TI, VI> { } public struct Test_S { } public struct Test_SG<TS> { } public struct Test_SG2<TS, VS> { } public struct Test_SI : Test_I { } public struct Test_SIG<TS> : Test_IG<TS> { } public struct Test_SIG2<TS, VS> : Test_IG2<TS, VS> { } public struct Test_SI_Int : Test_IG<int> { } public struct Test_SIG_Int<TS> : Test_IG2<TS, int> { } public struct Test_SIG_Int_Int : Test_IG2<int, int> { } public class Test_C { } public class Test_CG<T> { } public class Test_CG2<T, V> { } public class Test_CI : Test_I { } public class Test_CIG<T> : Test_IG<T> { } public class Test_CIG2<T, V> : Test_IG2<T, V> { } public class Test_CI_Int : Test_IG<int> { } public class Test_CIG_Int<T> : Test_CG2<T, int> { } public class Test_CIG_Int_Int : Test_CG2<int, int> { } }
-1
dotnet/runtime
66,038
Fix NonBacktracking quadratic behavior with deep loops
This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
olsaarik
2022-03-01T23:19:09Z
2022-03-08T21:30:47Z
906146aba64a9c14bcc77cffa5f540ead31cd4a7
78e071de86f8d18e2401730de9220fde7de0d838
Fix NonBacktracking quadratic behavior with deep loops. This PR now actually fixes https://github.com/dotnet/runtime/issues/65271. The source of the problem was a behavior in NonBacktracking's derivative construction, where the rule for concatenations was causing quadratic rebuilding of concatenations. Abstractly, the rule for a concatenation `RT` (ignoring the case when `R` is nullable) is `d(RT) = d(R)T`. With just concatenation involved, this wouldn't be a problem, since NonBacktracking keeps concatenations in right associative form, so this rule wouldn't really recurse into itself. However, with an alternating nesting of concatenations and loops (as happens in the deep loops test), this rule ends up getting recursively applied and each time the concatenation `d(R)T` is constructed, the right associative form gets rebuilt, since the concatenation is to the right. The change in this PR modifies the implementation of derivative construction to instead accumulate the `T` in that rule into a list that gets passed into recursive derivative construction calls. Then when the "leaf" of the recursion would have previously returned a derivative other than `Nothing`, it will now directly build the whole concatenation based on the "continuation" that has been already passed in. This avoids the quadratic rebuilding of the concatenations. The deep nesting of loops unit tests now finish in a few hundred milliseconds, somewhere between Interpreted and Compiled. In the course of making this change I also got rid of an intermediate step of building a `TransitionRegex` tree for the derivative and then interpreting that for the current context in the input. I originally used it because I found it easier to reason with that as the intermediate step, but actually the derivative construction is more readable when done directly.
./src/tests/JIT/HardwareIntrinsics/X86/Avx2/MaskStore.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\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.Reflection; 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 MaskStoreInt32() { var test = new StoreBinaryOpTest__MaskStoreInt32(); 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(); // 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(); // 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 StoreBinaryOpTest__MaskStoreInt32 { private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; 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<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(StoreBinaryOpTest__MaskStoreInt32 testClass) { Avx2.MaskStore((Int32*)testClass._dataTable.outArrayPtr, _fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static StoreBinaryOpTest__MaskStoreInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public StoreBinaryOpTest__MaskStoreInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreBinaryOpTest__MaskStoreInt32(); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, _fld1, _fld2); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _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(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] < 0) ? right[0] : result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] < 0) ? right[i] : result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MaskStore)}<Int32>(Vector256<Int32>, Vector256<Int32>): {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.Reflection; 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 MaskStoreInt32() { var test = new StoreBinaryOpTest__MaskStoreInt32(); 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(); // 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(); // 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 StoreBinaryOpTest__MaskStoreInt32 { private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; 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<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(StoreBinaryOpTest__MaskStoreInt32 testClass) { Avx2.MaskStore((Int32*)testClass._dataTable.outArrayPtr, _fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static StoreBinaryOpTest__MaskStoreInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public StoreBinaryOpTest__MaskStoreInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreBinaryOpTest__MaskStoreInt32(); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, _fld1, _fld2); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _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(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] < 0) ? right[0] : result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] < 0) ? right[i] : result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MaskStore)}<Int32>(Vector256<Int32>, Vector256<Int32>): {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