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,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/issues.targets
<?xml version="1.0" ?> <Project DefaultTargets = "GetListOfTestCmds" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- All OS/Arch/Runtime excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != ''"> <ExcludeList Include="$(XunitTestBinBase)/readytorun/DynamicMethodGCStress/DynamicMethodGCStress/*"> <Issue>timeout</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/GitHub_22888/test22888/*"> <Issue>https://github.com/dotnet/runtime/issues/13703</Issue> </ExcludeList> </ItemGroup> <!-- All OS/Arch CoreCLR excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(RuntimeFlavor)' == 'coreclr' "> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/StackTracePreserve/StackTracePreserveTests/*"> <Issue>https://github.com/dotnet/runtime/issues/11213</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/mono/runningmono/*"> <Issue>This test is to verify we are running mono, and therefore only makes sense on mono.</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/baseservices/threading/threadpool/bindhandle/bindhandleinvalid/*"> <Issue>https://github.com/dotnet/runtime/issues/66273</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/baseservices/threading/threadpool/bindhandle/bindhandleinvalid3/*"> <Issue>https://github.com/dotnet/runtime/issues/66273</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/baseservices/threading/threadpool/bindhandle/bindhandleinvalid4/*"> <Issue>https://github.com/dotnet/runtime/issues/66273</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/baseservices/threading/threadpool/bindhandle/bindhandleinvalid5/*"> <Issue>https://github.com/dotnet/runtime/issues/66273</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/baseservices/threading/threadpool/bindhandle/bindhandleinvalid6/*"> <Issue>https://github.com/dotnet/runtime/issues/66273</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/baseservices/threading/threadpool/bindhandle/bindhandlenull/*"> <Issue>https://github.com/dotnet/runtime/issues/66274</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Coverage/271010/**"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Coverage/smalloom/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/BackgroundGC/foregroundgc/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/LOHFragmentation/lohfragmentation/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/Allocation/finalizertest/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/collect/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/getgeneration/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/reregisterforfinalize/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/dev10bugs/536168/536168/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/readytorun/r2rdump/BasicTests/R2RDumpTest/*"> <Issue>https://github.com/dotnet/runtime/issues/10888 https://github.com/dotnet/runtime/issues/11823 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_255294/DevDiv_255294/*"> <Issue>https://github.com/dotnet/runtime/issues/44341</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/rvastatics/RVAOrderingTest/*"> <Issue>https://github.com/dotnet/runtime/issues/55966</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/HardwareIntrinsics/X86/X86Base/Pause*/**"> <Issue>https://github.com/dotnet/runtime/issues/62423</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest.Basic/*"> <Issue>https://github.com/dotnet/runtime/issues/57786</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/MonoAPI/**"> <Issue>CoreCLR does not implement the mono embedding API</Issue> </ExcludeList> </ItemGroup> <!-- All Unix targets on all runtimes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetsWindows)' != 'true'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/arglist/vararg_TargetUnix/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> </ItemGroup> <!-- All Unix targets on CoreCLR Runtime --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetsWindows)' != 'true' and '$(RuntimeFlavor)' == 'coreclr' "> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/stackoverflow/stackoverflowtester/*"> <Issue>https://github.com/dotnet/runtime/issues/46175</Issue> </ExcludeList> </ItemGroup> <!-- Arm32 All OS --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm' or '$(AltJitArch)' == 'arm') and '$(RuntimeFlavor)' == 'coreclr' "> <ExcludeList Include="$(XunitTestBinBase)/CoreMangLib/cti/system/reflection/emit/DynMethodJumpStubTests/DynMethodJumpStubTests/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeArray1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/hugeSimpleExpr1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/HeapExpansion/pluggaps/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/v2.0-beta2/460373/460373/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/v2.0-beta1/149926/149926/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/v2.0-rtm/494226/494226/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/dev10bugs/536168/536168/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetAllocatedBytesForCurrentThread/*"> <Issue>https://github.com/dotnet/runtime/issues/</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit-finalize/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/v2.0-rtm/494226/494226/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/dev10bugs/536168/536168/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/NoGCRegion/NoGC/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/LeakWheel/leakwheel/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/CoreMangLib/system/span/SlowTailCallArgs/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/rngchk/RngchkStress3/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/ServerModel/servermodel/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitintry/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitincatch/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/rngchk/ArrayWithThread_o/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinroot/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/Tailcall/TailcallVerifyWithPrefix/*"> <Issue>Depends on implicit tailcalls to be performed</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/arglist/vararg*/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/WindowsEventLog/WindowsEventLog_TargetUnix/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i53/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i13/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i03/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i33/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i63/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i73/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i83/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/tailcall/test_implicit_il_d/*"> <Issue>https://github.com/dotnet/runtime/issues/8891 Arm32 does not support implicit tailcalls</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/tailcall/test_implicit_il_r/*"> <Issue>https://github.com/dotnet/runtime/issues/8891 Arm32 does not support implicit tailcalls</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Stress/ABI/**/*"> <Issue>https://github.com/dotnet/runtime/issues/13241</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/eventpipe/eventpipe/*"> <Issue>TraceEvent can't parse unaligned floats on arm32</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/unittest/releaseondetach/*"> <Issue>https://github.com/dotnet/runtime/issues/64986</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/eventpipe/eventpipe_readevents/*"> <Issue>TraceEvent can't parse unaligned floats on arm32</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/regress/vsw/373472/**"> <Issue>Allocates large contiguous array that is not consistently available on 32-bit platforms</Issue> </ExcludeList> <!-- Arm32 does not support hardware intrinsics --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> </ItemGroup> <!-- Arm64 All OS --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm64' or '$(AltJitArch)' == 'arm64') and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/hugeexpr1/hugeexpr1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeArray/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeArray1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeField1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeField2/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/CoreMangLib/cti/system/string/StringFormat1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/CoreMangLib/cti/system/string/StringFormat2/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_590772/DevDiv_590772/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_605447/DevDiv_605447/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_590771/DevDiv_590771/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_56953/Runtime_56953/*"> <Issue>https://github.com/dotnet/runtime/issues/57515</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Generics/GenericsTest/*"> <Issue>https://github.com/dotnet/runtime/issues/60036</Issue> </ExcludeList> <!-- Arm64 does not support Vector256 --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256_1/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <!-- Arm64 does not support X86 hardware intrinsics --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/X86/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> </ItemGroup> <!-- Windows all architecture excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetsWindows)' == 'true' and '$(RuntimeFlavor)' == 'coreclr'"> </ItemGroup> <!-- Windows x64 specific excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetArchitecture)' == 'x64' and '$(TargetsWindows)' == 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport_r/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/GitHub_34094/Test34094/*"> <Issue>https://github.com/dotnet/runtime/issues/57458</Issue> </ExcludeList> <!-- X64 does not support Vector64 --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64_1/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <!-- X64 does not support Arm hardware intrinsics --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> </ItemGroup> <!-- Windows x86 specific excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetArchitecture)' == 'x86' and '$(TargetsWindows)' == 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/Allocation/largeexceptiontest/*"> <Issue>https://github.com/dotnet/runtime/issues/5200 Test is useful to have because it can be run manually when making changes to the GC that can have effects in OOM scenarios, but not appropriate to run on our current test infrastructure.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/gettotalmemory/*"> <Issue>https://github.com/dotnet/runtime/issues/5200 Test is useful to have because it can be run manually when making changes to the GC that can have effects in OOM scenarios, but not appropriate to run on our current test infrastructure.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/keepalive/*"> <Issue>https://github.com/dotnet/runtime/issues/5200 Test is useful to have because it can be run manually when making changes to the GC that can have effects in OOM scenarios, but not appropriate to run on our current test infrastructure.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/suppressfinalize/*"> <Issue>https://github.com/dotnet/runtime/issues/5200 Test is useful to have because it can be run manually when making changes to the GC that can have effects in OOM scenarios, but not appropriate to run on our current test infrastructure.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/Tailcall/TailcallVerifyWithPrefix/*"> <Issue>Depends on implicit tailcalls to be performed</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_255294/DevDiv_255294/*"> <Issue>https://github.com/dotnet/runtime/issues/8034 The test causes OutOfMemory exception in crossgen mode.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport_r/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/regress/vsw/373472/**"> <Issue>Allocates large contiguous array that is not consistently available on 32-bit platforms</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/GitHub_34094/Test34094/*"> <Issue>https://github.com/dotnet/runtime/issues/57458</Issue> </ExcludeList> <!-- X86 does not support Vector64 --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64_1/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <!-- X86 does not support Arm hardware intrinsics --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> </ItemGroup> <!-- Windows arm32 specific excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm' or '$(AltJitArch)' == 'arm') and '$(TargetsWindows)' == 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/Convert/out_of_range_fp_to_int_conversions/*"> <Issue>https://github.com/dotnet/runtime/issues/49184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/Primitives/NETClientPrimitives/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/Primitives/NETClientPrimitivesInALC/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NativeClients/Primitives/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/Lifetime/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NativeClients/Licensing/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NativeClients/DefaultInterfaces/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/IDispatch/NETClientIDispatch/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/Aggregation/NETClientAggregation/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/Licensing/NETClientLicense/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/ConsumeNETServer/ConsumeNETServer/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/ThisCall/ThisCallTest/*"> <Issue>Native member function calling conventions not supported on Windows ARM32.</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/StdCallMemberFunction/StdCallMemberFunctionTest/*"> <Issue>Native member function calling conventions not supported on Windows ARM32.</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/PlatformDefaultMemberFunction/PlatformDefaultMemberFunctionTest/*"> <Issue>Native member function calling conventions not supported on Windows ARM32.</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/CdeclMemberFunction/CdeclMemberFunctionTest/*"> <Issue>Native member function calling conventions not supported on Windows ARM32.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b88793/b88793/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b37646/b37646/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/1/arglist_Target_ARM/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b41391/b41391/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i00/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i70/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i32/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i51/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b32374/b32374/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Varargs/VarargsTest/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/volatile/1/arglist_Target_ARM/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b28901/b28901/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i82/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i80/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/gc/misc/funclet/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30864/b30864/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30838/b30838/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_r/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i61/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i60/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i31/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-EJIT/V1-M12-Beta2/b26323/b26323/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b26324/b26324a/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b26324/b26324b/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i50/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i62/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b36472/b36472/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i72/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b37598/b37598/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b46867/b46867/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b409748/b409748/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i30/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16423/b16423/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/2/arglist_Target_ARM/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_d/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Coverage/arglist_pos/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b35784/b35784/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31746/b31746/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i12/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i52/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i81/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i11/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b41852/b41852/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i02/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i01/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i71/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31745/b31745/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b91248/b91248/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/4/arglist_Target_ARM/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i10/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/regress/vsw/373472/**"> <Issue>Allocates large contiguous array that is not consistently available on 32-bit platforms</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/GitHub_45929/test45929/*"> <Issue>https://github.com/dotnet/runtime/issues/60152</Issue> </ExcludeList> </ItemGroup> <!-- Windows arm64 specific excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm64' or '$(AltJitArch)' == 'arm64') and '$(TargetsWindows)' == 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/Tailcall/TailcallVerifyWithPrefix/*"> <Issue>Condition17::Test1 checks that we tail call via helper when security cookie is needed; on arm64 we fast tail call in this case.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/dev10bugs/536168/536168/*"> <Issue>extremely memory/time intensive test</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/NoGCRegion/NoGC/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport_r/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/rngchk/RngchkStress3/*"> <Issue>Needs Triage</Issue> </ExcludeList> </ItemGroup> <!-- The following are x64 Unix failures on CoreCLR. --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetArchitecture)' == 'x64' and '$(TargetsWindows)' != 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/simple/ParallelCrashWorkerThreads/*"> <Issue>https://github.com/dotnet/runtime/issues/57621</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_d/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_r/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress1_r/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress3_r/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress1_do/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress3_do/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress1_ro/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress3_ro/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b41391/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b37646/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/pinning/object-pin/*"> <Issue>Issue building native components for the test.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_18232/GitHub_18232/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_19022/GitHub_19022/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_19149/GitHub_19149/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/rngchk/RngchkStress3/*"> <Issue>timeout</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_19601/Github_19601/*"> <Issue>Needs Triage</Issue> </ExcludeList> <!-- X64 does not support Vector64 --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64_1/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <!-- X64 does not support Arm hardware intrinsics --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> </ItemGroup> <!-- Unix arm64 specific --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm64' or '$(AltJitArch)' == 'arm64') and '$(TargetsWindows)' != 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler/*"> <Issue>Test times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally/*"> <Issue>Test times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitintry/*"> <Issue>Test times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitincatch/*"> <Issue>Test times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinroot/*"> <Issue>Test times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlstack/*"> <Issue>Release only crash</Issue> </ExcludeList> </ItemGroup> <!-- Unix arm32 specific --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm' or '$(AltJitArch)' == 'arm') and '$(TargetsWindows)' != 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/regress/vsw/373472/**"> <Issue>Allocates large contiguous array that is not consistently available on 32-bit platforms</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_56953/Runtime_56953/*"> <Issue>https://github.com/dotnet/runtime/issues/57856</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/multiple/multiple/*"> <Issue>https://github.com/dotnet/runtime/issues/57875</Issue> </ExcludeList> </ItemGroup> <!-- Tests that need to be triaged for vararg usage as that is not supported --> <!-- Note these will only be excluded for unix platforms on all runtimes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetsWindows)' != 'true' "> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/1/arglist*/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/2/arglist*/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/4/arglist*/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/volatile/1/arglist*/*"> <Issue>needs triage</Issue> </ExcludeList> </ItemGroup> <!-- Tests that need to be triaged for vararg usage as that is not supported --> <!-- Note these will only be excluded for unix platforms on CoreCLR only --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetsWindows)' != 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/gc/misc/funclet/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i00/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i01/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i02/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i03/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i10/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i11/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i12/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i13/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i30/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i31/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i32/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i33/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i50/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i51/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i52/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i53/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i60/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i61/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i62/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i63/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i70/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i71/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i72/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i73/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i80/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i81/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i82/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i83/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Coverage/arglist_pos/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_d/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_r/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-EJIT/V1-M12-Beta2/b26323/b26323/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16423/b16423/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b26324/b26324a/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b26324/b26324b/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b28901/b28901/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30838/b30838/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30864/b30864/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b32374/b32374/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b35784/b35784/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b36472/b36472/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b37598/b37598/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b41391/b41391/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b46867/b46867/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31745/b31745/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31746/b31746/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b37646/b37646/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b41852/b41852/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b88793/b88793/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b91248/b91248/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b409748/b409748/*"> <Issue>needs triage</Issue> </ExcludeList> </ItemGroup> <!-- Failures while testing via ILLINK --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(RunTestsViaIllink)' == 'true'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/*"> <!-- Linker runs reset CORE_ROOT to the linked directory based on superpmicollect.exe. The test runs other benchmarks to collect superpmi data. These tests cannot run from the binaries generated wrt superpmicollect.exe --> <Issue>By Test Infrastructure design</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/RVAInit/nested/*"> <!-- Data refered from static field is dropped --> <Issue>Bug</Issue> </ExcludeList> </ItemGroup> <!-- Crossgen2 specific --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TestBuildMode)' == 'crossgen2' or '$(TestBuildMode)' == 'crossgen') and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/NativeVarargs/NativeVarargsTest/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/CopyConstructorMarshaler/CopyConstructorMarshaler/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/ManagedCallingNative/ManagedCallingNative/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/LoadIjwFromModuleHandle/LoadIjwFromModuleHandle/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/NativeCallingManaged/NativeCallingManaged/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/FixupCallsHostWhenLoaded/FixupCallsHostWhenLoaded/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/v2.1/DDB/B168384/LdfldaHack/*"> <Issue>https://github.com/dotnet/runtime/issues/615</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035/*"> <Issue>https://github.com/dotnet/runtime/issues/64419</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/*"> <Issue>Not compatible with crossgen2</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/PInvoke/MarshalStructAsLayoutExp/*"> <Issue>https://github.com/dotnet/runtime/issues/43461</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/dev10_715437/dev10_715437/*"> <Issue>https://github.com/dotnet/runtime/issues/43498</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_34170/Runtime_34170/*"> <Issue>https://github.com/dotnet/runtime/issues/53560</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/debugging/poisoning/poison/*"> <Issue>https://github.com/dotnet/runtime/issues/56148</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/hugeexpr1/*"> <Issue>https://github.com/dotnet/runtime/issues/62881</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/AdvSimd.Arm64_Part2_ro/*"> <Issue>https://github.com/dotnet/runtime/issues/63856</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/AdvSimd.Arm64_Part2_r/*"> <Issue>https://github.com/dotnet/runtime/issues/63856</Issue> </ExcludeList> </ItemGroup> <!-- NativeAOT specific --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TestBuildMode)' == 'nativeaot' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/nativeaot/SmokeTests/MultiModule/MultiModule/*"> <Issue>https://github.com/dotnet/runtime/issues/66191</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/callconvs/TestCallingConventions/*"> <Issue>https://github.com/dotnet/runtimelab/issues/153</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/compilerservices/RuntimeWrappedException/RuntimeWrappedException/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Wrapping non-exception throws</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/RefEmit/EmittingIgnoresAccessChecksToAttributeIsRespected/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Reflection.Emit</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25468/GitHub_25468/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: BinaryFormatter</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/stackoverflow/stackoverflowtester/*"> <Issue>Specific to CoreCLR</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/threading/coverage/OSThreadId/osthreadid/*"> <Issue>Accessing a reflection blocked internal detail</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/threading/paramthreadstart/ThreadStartBool/*"> <Issue>https://github.com/dotnet/runtimelab/issues/220</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/TieredCompilation/**"> <Issue>No crossgen folder under Core_Root</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/typeequivalence/simple/Simple/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Type equivalence</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/WeakReference/Finalize2/*"> <Issue>Expectations about finalization order</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/ilasm/PortablePdb/IlasmPortablePdbTests/*"> <Issue>Specific to CoreCLR</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/ilasm/System/Runtime/CompilerServices/MethodImplOptionsTests/*"> <Issue>Specific to CoreCLR</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ArrayMarshalling/SafeArray/SafeArrayTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: SAFEARRAY</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: COM</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ExecInDefAppDom/ExecInDefAppDom/*"> <Issue>Specific to CoreCLR</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ICustomMarshaler/ConflictingNames/MultipleALCs/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: AssemblyLoadContext.LoadFromAssemblyPath</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: C++/CLI</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/LayoutClass/LayoutClassTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/163</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/MarshalAPI/FunctionPointer/FunctionPtrTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/164</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/MarshalAPI/IUnknown/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: COM</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/NativeLibrary/API/NativeLibraryTests/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/NativeLibrary/AssemblyLoadContext/ResolveUnmanagedDllTests/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackStressTest_TargetWindows/*"> <Issue>https://github.com/dotnet/runtimelab/issues/166</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackTests/*"> <Issue>https://github.com/dotnet/runtimelab/issues/206</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Array/MarshalArrayAsParam/AsDefault/AsDefaultTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/176: VARIANT marshalling</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/ArrayWithOffset/ArrayWithOffsetTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/170</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/AsAny/AsAnyTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/169</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Attributes/LCID/LCIDTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/171</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Attributes/SuppressGCTransition/SuppressGCTransitionTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/BestFitMapping/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/172</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/CriticalHandles/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/173</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/CustomMarshalers/CustomMarshalersTest/*"> <Issue>Specific to CoreCLR: Built-in COM Interop</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Decimal/DecimalTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/175</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Delegate/DelegateTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/176: IDispatch</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Generics/GenericsTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/177</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/IEnumerator/IEnumeratorTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: COM</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/CopyCtor/CopyCtorTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: C++/CLI</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/NativeCallManagedComVisible/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: COM</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SafeHandles/SafeHandleTests/*"> <Issue>https://github.com/dotnet/runtimelab/issues/168</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/ReversePInvoke/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/167</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Varargs/VarargsTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Varargs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Variant/VariantTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: VARIANT marshalling</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StringMarshalling/VBByRefStr/VBByRefStrTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/179</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/PInvoke/MarshalStructAsLayoutSeq/*"> <Issue>https://github.com/dotnet/runtimelab/issues/180</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalExpStruct/ReversePInvokeManaged/ReversePInvokeTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/180</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/DelegatePInvoke/DelegatePInvokeTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/180</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/ReversePInvoke/ReversePInvokeTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/180</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructPacking/StructPacking/*"> <Issue>https://github.com/dotnet/runtimelab/issues/181</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/154</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/WinRT/WinRT/*"> <Issue>https://github.com/dotnet/runtimelab/issues/182</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/arglist/vararg_TargetWindows/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Varargs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/forceinlining/NegativeCases/*"> <Issue>https://github.com/dotnet/runtimelab/issues/183</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/pinvoke/calli_excep/*"> <Issue>https://github.com/dotnet/runtimelab/issues/166</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/tailcall/more_tailcalls/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Tailcalls</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/throwbox/fault/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throws</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/throwbox/filter/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throws</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/throwbox/finally/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throws</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/throwbox/rethrow/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throws</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector128_1/Vector128_1_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector128_1/Vector128_1_ro/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64_1/Vector64_1_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64_1/Vector64_1_ro/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256_1/Vector256_1_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256_1/Vector256_1_ro/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/hugeSimpleExpr1/*"> <Issue>https://github.com/dotnet/runtimelab/issues/190</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/inl/caninline_d/*"> <Issue>https://github.com/dotnet/runtimelab/issues/183</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/inl/caninline_do/*"> <Issue>https://github.com/dotnet/runtimelab/issues/183</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/inl/caninline_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/183</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/inl/caninline_ro/*"> <Issue>https://github.com/dotnet/runtimelab/issues/183</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Arrays/misc/_il_relinitializearray/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: RuntimeHelpers.InitializeArray</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Arrays/misc/_il_dbginitializearray/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: RuntimeHelpers.InitializeArray</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinfilter_il_d/*"> <Issue>https://github.com/dotnet/runtimelab/issues/188</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinfilter_il_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/188</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/interactions/throw1dimarray_d/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throw</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/interactions/throw1dimarray_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throw</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/interactions/throw2dimarray_d/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throw</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/interactions/throw2dimarray_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throw</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/ObjectStackAllocation/ObjectStackAllocationTests/*"> <Issue>Need to pass flag to enable object stack allocation in RyuJIT</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/Devirtualization/Comparer_get_Default/*"> <Issue>https://github.com/dotnet/runtimelab/issues/1136</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fasta/fasta-1/*"> <Issue>Multimodule incompatible (GVM)</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/regex-redux/regex-redux-1/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/regex-redux/regex-redux-5/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-1/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-6/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/Burgers/Burgers/*"> <Issue>Multimodule incompatible (GVM)</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Deserialize/*"> <Issue>Needs xunit.performance</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Serialize/*"> <Issue>Needs xunit.performance</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b68872/b68872/*"> <Issue>https://github.com/dotnet/runtimelab/issues/188</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b71120/b71120/**"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Varargs</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b353858/b353858/**"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Thorough checking of invalid inputs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/v2.2/ddb/b429039/b429039/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: RuntimeHelpers.InitializeArray</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/*"> <Issue>https://github.com/dotnet/runtimelab/issues/196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_19444/GitHub_19444/*"> <Issue>https://github.com/dotnet/runtimelab/issues/197</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_22583/GitHub_22583/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Type equivalence</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25020/GitHub_25020/*"> <Issue>https://github.com/dotnet/runtimelab/issues/154</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25027/GitHub_25027/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Thorough checking of invalid inputs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_35384/GitHub_35384/*"> <Issue>https://github.com/dotnet/runtimelab/issues/198</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_4044/GitHub_4044/*"> <Issue>https://github.com/dotnet/runtimelab/issues/188</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/*"> <Issue>CoreCLR test</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/AssemblyDependencyResolver/AssemblyDependencyResolverTests/AssemblyDependencyResolverTests/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/AssemblyLoadContext30Extensions/AssemblyLoadContext30Extensions/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest.Basic/*"> <Issue>AOT incompatible</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest.ResolutionFlow/*"> <Issue>AOT incompatible</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/DictionaryExpansion/DictionaryExpansion/*"> <Issue>https://github.com/dotnet/runtimelab/issues/154</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/Regressions/ASURT/ASURT150271/test3/*"> <Issue>Won't fix https://github.com/dotnet/corert/issues/2396</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/Instantiation/Negative/abstract01/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Thorough checking of invalid inputs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/MethodImpl/generics_override1/*"> <Issue>https://github.com/dotnet/runtimelab/issues/207</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/347422/b347422/*"> <Issue>https://github.com/dotnet/runtimelab/issues/194</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/529206/vsw529206ModuleCctor/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: compat for exceptions thrown from module cctor</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/asurt150271/test3/*"> <Issue>https://github.com/dotnet/runtimelab/issues/202</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TSAmbiguities/CollapsedInterfaces/HelloWorld/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Thorough checking of invalid inputs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TSAmbiguities/SameMethodImpl/Override/HelloWorld/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Thorough checking of invalid inputs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/ByRefLocals/ByRefLocals/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/Statics/CollectibleStatics/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_64883/Runtime_64883/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/ContextualReflection/ContextualReflection/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/regressions/GitHub_15544/main/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: AssemblyName.GetAssemblyName</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/**/*"> <Issue>CoreCLR test</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/readytorun/**/*"> <Issue>CoreCLR test</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/Modifiers/modifiers/*"> <Issue>https://github.com/dotnet/runtimelab/issues/201</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/RefEmit/EmittingIgnoresAccessChecksToAttributeIsRespected\EmittingIgnoresAccessChecksToAttributeIsRespected/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Ref emit</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/SetValue/TrySetReadonlyStaticField/*"> <Issue>https://github.com/dotnet/runtimelab/issues/200</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/tracing/**/*"> <Issue>EventPipe</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b426654/b426654/*"> <Issue>https://github.com/dotnet/runtimelab/issues/208</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/v2.1/DDB/B168384/LdfldaHack/*"> <Issue>https://github.com/dotnet/runtime/issues/615</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_754566/DevDiv_754566/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Complext tail calls</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection\DefaultInterfaceMethods\Emit\*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Reflection.Emit</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection\DefaultInterfaceMethods\GetInterfaceMapConsumer\*"> <Issue>https://github.com/dotnet/runtimelab/issues/861</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop\IDynamicInterfaceCastable\IDynamicInterfaceCastable\*"> <Issue>https://github.com/dotnet/runtimelab/issues/1442</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)\Interop\PInvoke\Variant\VariantTestBuiltInComDisabled\*"> <Issue>https://github.com/dotnet/runtimelab/issues/306</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)\Interop\PInvoke\Variant\VariantTestComWrappers\*"> <Issue>https://github.com/dotnet/runtimelab/issues/306</Issue> </ExcludeList> <!-- Complex constrained calls --> <!-- https://github.com/dotnet/runtimelab/issues/1431 --> <ExcludeList Include="$(XunitTestBinBase)/Regressions\coreclr\16354\notimplemented\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader\DefaultInterfaceMethods\constrainedcall\constrainedcall\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader\DefaultInterfaceMethods\constrainedcall\constrained2\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader\DefaultInterfaceMethods\constrainedcall\constrained2_gm\*" /> <!-- Catch(T) in shared code --> <!-- https://github.com/dotnet/runtimelab/issues/204 --> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\throwincatch_d\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\throwincatch_do\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\throwincatch_r\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\throwincatch_ro\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchnestedtype_d\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchnestedtype_do\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchnestedtype_r\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchnestedtype_ro\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchsimpletype_d\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchsimpletype_do\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchsimpletype_r\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchsimpletype_ro\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/InstructionCombining/ArrayLengthArithmetic/*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b441487/b441487/*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_21990/GitHub_21990/*" /> <!-- Arrays with non-zero lower bounds --> <!-- https://github.com/dotnet/runtimelab/issues/155 --> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_b\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_i4\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_objref\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_r4\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_r8\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_struct\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_u8\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\misc\_il_dbgaddress\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\misc\_il_dbgldelem_get\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\misc\_il_reladdress\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\misc\_il_relgcarr\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\misc\_il_relldelem_get\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgfloat64_range1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgfloat64_range2\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgint32_1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgint32_m1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgint32_neg_range\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgint32_range1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgint32_range2\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relfloat64_range1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relfloat64_range2\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relint32_1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relint32_m1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relint32_neg_range\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relint32_range1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relint32_range2\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\int64\arrays\_il_relhugedim\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\refany\_il_dbgarray2\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\refany\_il_dbgarray3\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\refany\_il_relarray3\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\tailcall\_il_dbgdeep_array_nz\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\tailcall\_il_reldeep_array_nz\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\VT\port\_il_dbghuge_gcref\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\VT\port\_il_relhuge_gcref\*" /> <!-- Covariant returns --> <!-- https://github.com/dotnet/runtimelab/issues/205 --> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\Interfaces\UnitTest\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\Interfaces\UnsupportedScenario1\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\Interfaces\UnsupportedScenario2\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\Interfaces\UnsupportedScenario3\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\ReturnTypeValidation\ImplicitOverrideSameSigAsDecl\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\ReturnTypeValidation\OverrideSameSigAsDecl\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\Structs\IncompatibleOverride\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\AttributeTesting\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\CompatibleWithTest\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\UnitTest\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\UnitTest_GVM\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\UnitTestDelegates\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\OverrideMoreDerivedReturn\*" /> <!-- Static virtual methods --> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\StaticVirtualMethods\**" /> </ItemGroup> <!-- run.proj finds all the *.cmd/*.sh scripts in a test folder and creates corresponding test methods. Exclude these scripts to avoid creating such methods for the superpmicollect dependent test projects and running them separately from superpmicollect test. These should be excluded regardless of RuntimeFlavor/os/arch--> <ItemGroup Condition="'$(XunitTestBinBase)' != ''"> <ExcludeList Include="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/*" Exclude="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/superpmicollect.*"> <Issue>Do not run these scripts separately from superpmicollect test</Issue> </ExcludeList> </ItemGroup> <!-- Known failures for mono runtime on *all* architectures/operating systems in *all* runtime modes --> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono'" > <ExcludeList Include = "$(XUnitTestBinBase)/JIT/HardwareIntrinsics/X86/X86Base/Pause*/**"> <Issue>https://github.com/dotnet/runtime/issues/61693</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/reflection/GenericAttribute/**"> <Issue>https://github.com/dotnet/runtime/issues/56887</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/X86/Sse2.X64/StoreNonTemporal_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54176</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/X86/Sse2.X64/StoreNonTemporal_ro/**"> <Issue>https://github.com/dotnet/runtime/issues/54176</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/X86/Sse42.X64/Crc32_*/**"> <Issue>https://github.com/dotnet/runtime/issues/54185</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/Convert/out_of_range_fp_to_int_conversions/*"> <Issue>Mono does not define out of range fp to int conversions</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/DynamicPgo/**"> <Issue>Mono doesn't have a dynamic pgo or tiered compilation infrastructure</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/SIMD/Vector3Interop_r/*"> <Issue>https://github.com/dotnet/runtime/issues/46174</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/SIMD/Vector3Interop_ro/*"> <Issue>https://github.com/dotnet/runtime/issues/46174</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTestWithMcj/*"> <Issue>Tests features specific to coreclr</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/RuntimeConfiguration/*"> <Issue>Tests features specific to coreclr</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/ByRefLocals/**"> <Issue>https://github.com/dotnet/runtime/issues/40394</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/Statics/**"> <Issue>https://github.com/dotnet/runtime/issues/40394</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/CopyCtor/**"> <Issue>Handling for Copy constructors isn't present in mono interop</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StringMarshalling/AnsiBSTR/AnsiBStrTest/**"> <Issue>Crashes during LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StringMarshalling/BSTR/BSTRTest/**"> <Issue>Crashes during LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/Structs/IncompatibleOverride/**"> <Issue>Crashes during LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/HwiOp/CompareVectorWithZero/**"> <Issue>https://github.com/dotnet/runtime/pull/65632#issuecomment-1046294324</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/InstructionCombining/DivToMul/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/StructABI/StructABI/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_15949/GitHub_15949/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_15291/GitHub_15291/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16928/b16928/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/osr/osr015/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/rngchk/ArrayBound_o/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CctorsWithSideEffects/CctorThrowInlinedStatic/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/UnitTest/CompatibleWithTest/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CctorsWithSideEffects/CctorThrowMethodAccess/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/UnitTest/CompatibleWithTest/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/StaticVirtualMethods/GenericContext/**"> <Issue>Static virtual methods are not yet implemented in the Mono runtime.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/StaticVirtualMethods/InterfaceVariance/**"> <Issue>Static virtual methods are not yet implemented in the Mono runtime.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/StaticVirtualMethods/NegativeTestCases/**"> <Issue>Static virtual methods are not yet implemented in the Mono runtime.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/stackoverflow/stackoverflowtester/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/callconvs/TestCallingConventions/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/Collect1/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/CollectionCountTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetGCMemoryInfo/**"> <Issue>https://github.com/dotnet/runtime/issues/37950</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetGeneration/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetGeneration_fail/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetGenerationWR/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetTotalAllocatedBytes/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/MaxGeneration/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GCSettings/InputValidation/**"> <Issue>https://github.com/dotnet/runtime/issues/46666</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)GC/API/WeakReference/Finalize2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)GC/API/WeakReference/Finalize2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/LOHCompaction/lohpin/**"> <Issue>https://github.com/dotnet/runtime/issues/46666</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/ReflectObj/reflectobj/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/WeakReference/NullHandle/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizeexcep/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizenested/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizearray/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizedest/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizearraysleep/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizeinherit/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeio/finalizeio/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/BaseFinal/basefinal/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/NDPin/ndpinfinal/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlbigleak/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinknoleak/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinknoleak2/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinkstay/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinkgen/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlbigleakthd/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlstack/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlcollect/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/nstructtun/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/finalnstruct/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/nstructresur/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/WeakReference/weakreffinal/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/Resurrection/continue/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/Rootmem/rootmem/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/SingLinkList/singlinkgen/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/LeakWheel/leakwheel/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/ReflectObj/reflectobj/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/FragMan/fragman/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/LeakGen/leakgen/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/SingLinkList/singlinkgen/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ArrayMarshalling/ByValArray/MarshalArrayByValTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/Reflection/Reflection/**"> <Issue>https://github.com/dotnet/runtime/issues/34371</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/ComWrappers/**"> <Issue>Not supported on Mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ICastable/Castable/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IDynamicInterfaceCastable/IDynamicInterfaceCastable/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ICustomMarshaler/ConflictingNames/MultipleALCs/**"> <Issue>https://github.com/dotnet/runtime/issues/34072</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ICustomMarshaler/Primitives/ICustomMarshaler_TargetUnix/**"> <Issue>https://github.com/dotnet/runtime/issues/34374</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/LayoutClass/LayoutClassTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/MarshalAPI/FunctionPointer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/NativeLibrary/AssemblyLoadContext/ResolveUnmanagedDllTests/**"> <Issue>https://github.com/dotnet/runtime/issues/41180</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ObjectiveC/ObjectiveCMarshalAPI/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Array/MarshalArrayAsField/AsByValArray/AsByValArrayTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Array/MarshalArrayAsField/AsLPArray/AsLPArrayTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Array/MarshalArrayAsParam/AsDefault/AsDefaultTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Array/MarshalArrayAsParam/AsLPArray/AsLPArrayTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/ArrayWithOffset/ArrayWithOffsetTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/AsAny/AsAnyTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/CriticalHandles/ArrayTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/CriticalHandles/StructTest/StructTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/CriticalHandles/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/DateTime/DateTimeTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Decimal/DecimalTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Delegate/DelegateTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Generics/GenericsTest/GenericsTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SafeHandles/**"> <Issue>https://github.com/dotnet/runtime/issues/48084</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/PInvoke/Invalid/InvalidParamIndex/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/PInvoke/PassingByOut/PassingByOutTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/PInvoke/PassingByRef/PassingByRefTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/ReversePInvoke/PassingByOut/PassingByOutTest/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/ReversePInvoke/PassingByRef/PassingByRefTest/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StringMarshalling/LPSTR/LPSTRTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/PInvoke/MarshalStructAsLayoutSeq/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/ReversePInvoke/ReversePInvokeTest/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructPacking/StructPacking/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/Convert/ldind_conv/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/coverage/compiler/FilterToHandler/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/badldsfld_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/badldsfld_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/tailcall/more_tailcalls/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/tailcall/mutual_recursion/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/newarr/newarr/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_il/**"> <Issue>https://github.com/dotnet/runtime/issues/54867</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/call/call05_large/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/call/call05_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh05_dynamic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh05_large/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh05_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh06_dynamic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh06_large/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh06_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh07_dynamic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh07_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh08_dynamic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh08_large/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh08_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Boxing/morph/sin3double/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/KeepAliveBoxOpt/**"> <Issue>Relies on precise finalization and thus precise GC</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/doublearray/dblarray2_cs_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/doublearray/dblarray2_cs_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/doublearray/dblarray2_cs_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/doublearray/dblarray2_cs_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/doublearray/dblarray3_cs_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/lcs_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)JIT/Methodical/tailcall_v4/hijacking/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/ObjectStackAllocation/ObjectStackAllocationTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BilinearInterpol/BilinearInterpol/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31283/b31283/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b091942/b091942/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b441487/b441487/**"> <Issue>https://github.com/dotnet/runtime/issues/34383</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/v2.1/DDB/B168384/LdfldaHack/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/Dev11/Dev11_468598/Test_HndIndex_10_Plain/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/Dev11/Dev11_468598/Test_HndIndex_10_Reordered/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_545500/**"> <Issue>https://github.com/dotnet/runtime/issues/34084</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/devdiv_902271/DevDiv_902271/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_18144/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_18295/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_23411/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_23791/**"> <Issue>https://github.com/dotnet/runtime/issues/34385</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_27169/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_27551/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_27678/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_35384/GitHub_35384/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_4044/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_34587/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/V1.2-M02/b10828/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/AssemblyDependencyResolver/AssemblyDependencyResolverTests/AssemblyDependencyResolverTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest.ResolutionFlow/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest.Basic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/DefaultInterfaceMethods/reabstraction/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/Regressions/ASURT/ASURT150271/test3/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/Instantiation/Negative/abstract01/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/regressions/dev10_531793/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/Interfaces/**"> <Issue>https://github.com/dotnet/runtime/issues/37509</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/347422/b347422/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/GitHub_11371/Negative_ByRefLikeType/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/vsw529206/vsw529206ModuleCctor/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/rmv/il/RMV-2-15-12b/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TSAmbiguities/CollapsedInterfaces/HelloWorld/**"> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TSAmbiguities/SameMethodImpl/Override/HelloWorld/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CctorsWithSideEffects/CctorThrowLDFTNStaticMethod/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CctorsWithSideEffects/CctorThrowStaticFieldBFI/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CctorsWithSideEffects/TypeLoadInitExcepBFI/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CoreCLR/CctorThrowStaticFieldBFI/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/ContextualReflection/ContextualReflection/**"> <Issue>https://github.com/dotnet/runtime/issues/34072</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/elt/slowpatheltenter/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/elt/slowpatheltleave/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/unittest/metadatagetdispenser/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/rejit/rejit/rejit.sh"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/readytorun/**"> <Issue>These tests are not supposed to be run with mono.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/DefaultInterfaceMethods/Emit/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/DefaultInterfaceMethods/InvokeConsumer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/Modifiers/modifiers/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/SetValue/TrySetReadonlyStaticField/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/SetValue/TrySetReadonlyStaticField2/**"> <Issue>https://github.com/dotnet/runtime/issues/37903</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/15241/genericcontext/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/15647/interfacestatics/**"> <Issue>https://github.com/dotnet/runtime/issues/34390</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/16123/ambiguousconstraint/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/16355/variance/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/20616/UnicodeBug/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/22021/consumer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/tracing/eventpipe/gcdump/gcdump/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/tracing/eventpipe/providervalidation/**"> <Issue>https://github.com/dotnet/runtime/issues/59296</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/tracing/eventpipe/rundownvalidation/**"> <Issue>https://github.com/dotnet/runtime/issues/54801</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/DllImportAttribute/DllImportPath/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Generics/GenericsTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/DllImportAttribute/ExactSpelling/ExactSpellingTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Stress/ABI/pinvokes_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Stress/ABI/pinvokes_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Stress/ABI/stubs_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Stress/ABI/tailcalls_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Stress/ABI/tailcalls_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/debugging/poisoning/poison/**"> <Issue>Tests coreclr JIT's debug poisoning of address taken variables</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/debugging/debuginfo/**"> <Issue>Tests coreclr JIT's debug info generation</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/DisabledRuntimeMarshalling/**"> <Issue>https://github.com/dotnet/runtime/issues/64127</Issue> </ExcludeList> </ItemGroup> <!-- Known failures for mono runtime on *all* architectures/operating systems in interpreter runtime mode --> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono' and '$(RuntimeVariant)' == 'monointerpreter' "> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeArray1/**"> <Issue>https://github.com/dotnet/runtime/issues/46622</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54867</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_ro/**"> <Issue>https://github.com/dotnet/runtime/issues/54867</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_21990/**"> <Issue>https://github.com/dotnet/runtime/issues/46622</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/zeroinit/tail/**"> <Issue>https://github.com/dotnet/runtime/issues/37955</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow04_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/u_fld_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/u_fld_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh07_large/**"> <Issue>https://github.com/dotnet/runtime/issues/54395</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/verif/sniff/fg/ver_fg_13/**"> <Issue>https://github.com/dotnet/runtime/issues/54396</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r4nanconv_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/Statics/Misc/LiteralStatic/**"> <Issue>https://github.com/dotnet/runtime/issues/54560</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b59952/b59952/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16499/b16499b/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31547/b31547/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b45541/b45541/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b65176/b65176/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b27883/b27883/**"> <Issue>https://github.com/dotnet/runtime/issues/54394</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b34953/b34953/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30862/b30862/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30869/b30869/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b70964/b70964/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b63726/b63726/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/volatilstind_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b60142/b60142/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b53980/b53980/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b47093/b47093/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r4nanconv_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b45956/b45956/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b25701/b25701/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/volatilstind_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30892/b30892/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/volatilstind/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b44879/b44879/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b27873/b27873/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b71179/b71179/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b37578/b37578/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b28597/b28597/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b71120/b71120/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/refany/indcall_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b32614/b32614/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b50027/b50027/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b35354/b35354/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_605447/DevDiv_605447/**"> <Issue>https://github.com/dotnet/runtime/issues/54391</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/V1.2-M02/b102844/b102844/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/u_conv_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/casts/coverage/castclass_calli_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_362706/DevDiv_362706/**"> <Issue>https://github.com/dotnet/runtime/issues/54391</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/V2.0-Beta2/b309576/b309576/**"> <Issue>https://github.com/dotnet/runtime/issues/54391</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_578214/DevDiv_578214/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/ptr_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfinally_ind_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/casts/coverage/castclass_calli_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/instftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/valftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_710234/DevDiv_710234/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfinally_ind_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-RTM/b530694/b530694/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/deep/deep1_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/valftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/deep/deep1_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/instftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/flowgraph/dev10_bug679955/volatileLocal2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/virtftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/virtftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/ftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/ptr_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/ftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow02_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Dynamo/dynamo/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_24846/GitHub_24846/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/huge_filter_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54388</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/M00/b108366/b108366/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/huge_filter_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow03_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1.2-M01/b00722/b00722/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/tailcall_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Coverage/b39946/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_487699/DevDiv_487699/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/tailcall_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54388</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinclassconstructor_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/SIMD/VectorMatrix_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/strswitchfinal_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_405852/DevDiv_405852/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_544983/DevDiv_544983/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/Localloc_do/**"> <Issue>https://github.com/dotnet/runtime/issues/54359</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/Misc/function_pointer/MutualThdRecur-fptr/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinclassconstructor_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1.2-M01/b13452/b13452/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/div_r8/**"> <Issue>https://github.com/dotnet/runtime/issues/54375</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/deep/deep1_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/instftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/flowgraph/dev10_bug679955/volatileLocal2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/virtftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/virtftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/ftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/ptr_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/ftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow02_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Dynamo/dynamo/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/huge_filter_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/huge_filter_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54388</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow03_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/tailcall_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54388</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Coverage/b39946/**"> <Issue>https://github.com/dotnet/runtime/issues/54388</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/tailcall_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinclassconstructor_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/strswitchfinal_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_large/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/nstructresur/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/finalnstruct/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/strswitchfinal_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/strswitchfinal_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizearray/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow01_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b353858/b353858/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/SIMD/VectorMatrix_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/strswitchfinal_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/Localloc_do/**"> <Issue>https://github.com/dotnet/runtime/issues/54359</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/Misc/function_pointer/MutualThdRecur-fptr/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinclassconstructor_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/DefaultInterfaceMethods/diamondshape/diamondshape_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54399</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_dynamic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/Localloc_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54359</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/Localloc_ro/**"> <Issue>https://github.com/dotnet/runtime/issues/54359</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/neg_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/Localloc_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54359</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b25459/b25459/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/zeroinit/init_struct/**"> <Issue>https://github.com/dotnet/runtime/issues/54373</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinclassconstructor_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/pinvoke/tail/**"> <Issue>https://github.com/dotnet/runtime/issues/54373</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b39946/b39946/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/varargs/varargsupport/**"> <Issue>https://github.com/dotnet/runtime/issues/54401</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/varargs/varargsupport_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54401</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/M00/b109878/b109878/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/add_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/M00/b92726/b92726/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/DefaultInterfaceMethods/diamondshape/diamondshape_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54399</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/volatilldind_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/mul_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b84909/b84909/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/volatilldind_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/rem_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/ckfinite_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/div_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/sub_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/ldc_ckfinite_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/volatilldind/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/opt/rngchk/RngchkStress3/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Burgers/Burgers/**"> <Issue>https://github.com/dotnet/runtime/issues/54358</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/DelegatePInvoke/DelegatePInvokeTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinfilter_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/47624</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinfilter_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/47624</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)JIT/IL_Conformance/Old/Base/ckfinite/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_64125/Runtime_64125/**"> <Issue>needs triage</Issue> </ExcludeList> <!-- End interpreter issues --> </ItemGroup> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono' and '$(RuntimeVariant)' == 'llvmaot' "> <ExcludeList Include = "$(XunitTestBinBase)JIT/Methodical/ELEMENT_TYPE_IU/u_conv_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/nullabletypes/isinstvaluetype_do/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Generics/Instantiation/Structs/struct01/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeArray1/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Dynamo/dynamo/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizearray/**"> <Issue>https://github.com/dotnet/runtime/issues/54113</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventactivityidcontrol/eventactivityidcontrol/**"> <Issue>needs triage</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono' and '$(RuntimeVariant)' == 'llvmfullaot' "> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case1/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case11/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case12/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case14/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case15/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case3/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case4/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case5/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case6/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case7/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case8/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case9/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/NestedStructs/case03/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/NestedStructs/case04/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/NestedStructs/case05/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/RefFields/Validate/**"> <Issue>expected failure: unsupported type with ref field fails at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/SuppressGCTransition/SuppressGCTransitionTest/**"> <Issue>https://github.com/dotnet/runtime/issues/57361</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest/**"> <Issue>https://github.com/dotnet/runtime/issues/57362</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/CdeclMemberFunction/CdeclMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/57361</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/PlatformDefaultMemberFunction/PlatformDefaultMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/57361</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/StdCallMemberFunction/StdCallMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/57361</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/ThisCall/ThisCallTest/*"> <Issue>https://github.com/dotnet/runtime/issues/57361</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57369</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57369</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)JIT/Methodical/ELEMENT_TYPE_IU/u_conv_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57369</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/DelegatePInvoke/DelegatePInvokeTest/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Vector2_3_4/Vector2_3_4/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/HandleRef/HandleRefTest/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/badendfinally/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/badendfinally*/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/ceeillegal/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/ceeillegal*/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/pinvoke/tail/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/perffix/primitivevt/callconv3_il_*/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/zeroinit/tail/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/deep_*_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/deep_*_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumps2_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumper4_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumper5_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumps2_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_small/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_large/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_dynamic/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/misc/tailjump_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/misc/tailjump_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfinally_*_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfault_*_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfinally_*_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfault_jmp_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/25params/25paramMixed_*/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25020/GitHub_25020/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25027/GitHub_25027/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1.2-M01/b13452/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/WPF_3226/CSharpRepro/WPF_3226/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b353858/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_23861/GitHub_23861/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_279829/DevDiv_279829/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/verif/sniff/fg/ver_fg_13/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/localloc/call/call05_dynamic/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/ReturnTypeValidation/OverrideSameSigAsDecl/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/DictionaryExpansion/DictionaryExpansion/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/Regressions/ASURT/ASURT150271/test13/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/Statics/Misc/LiteralStatic/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/MethodImpl/generics_override1/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/UnitTest/UnitTest_GVM/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/ReturnTypeValidation/ImplicitOverrideSameSigAsDecl/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Regressions/coreclr/16354/notimplemented/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Serialize/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Deserialize/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_r*/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport/*"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport_r/*"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/TieredVtableMethodTests/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case2/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh07_large/**"> <Issue>llvmfullaot: EH problem</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Exceptions/ForeignThread/ForeignThreadExceptions/**"> <Issue>llvmfullaot: EH problem</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/nullabletypes/Desktop/boxunboxvaluetype_*/**"> <Issue>https://github.com/dotnet/runtime/issues/57353</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/nullabletypes/castclassvaluetype_*/**"> <Issue>https://github.com/dotnet/runtime/issues/57353</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Roslyn/CscBench/**"> <Issue>https://github.com/dotnet/runtime/issues/57352</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/opt/virtualstubdispatch/bigvtbl/bigvtbl_cs*/**"> <Issue>https://github.com/dotnet/runtime/issues/57352</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256_1/**"> <Issue>https://github.com/dotnet/runtime/issues/57352</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/DefaultInterfaceMethods/constrainedcall/constrained2_gm/**"> <Issue>https://github.com/dotnet/runtime/issues/57512</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/DisabledRuntimeMarshalling/DisabledRuntimeMarshalling_Disabled_NativeAssemblyEnabled/**"> <Issue>This test includes an intentionally-invalid UnmanagedCallersOnly method. Invalid UnmanagedCallersOnly methods cause failures at AOT-time.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/ArmBase/Yield_*/**"> <Issue>https://github.com/dotnet/runtime/issues/64179</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono' and ('$(RuntimeVariant)' == 'llvmfullaot' or '$(RuntimeVariant)' == 'llvmaot')"> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1.1-M1-Beta1/b143840/b143840/*"> <Issue>https://github.com/dotnet/runtime/issues/48914</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/eventsourceerror/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverseouter/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/bigevent/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/buffersize/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/complus_config/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/diagnosticport/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/eventsvalidation/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/pauseonstart/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processenvironment/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processinfo/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processinfo2/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/providervalidation/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverse/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/rundownvalidation/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/MonoAPI/MonoMono/Thunks/**"> <Issue>Test not expected to work with AOT</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono' and ('$(RuntimeVariant)' == 'llvmfullaot' or '$(RuntimeVariant)' == 'llvmaot') and '$(TargetArchitecture)' == 'arm64'"> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/UnitTest/UnitTestMultiModule/**"> <Issue>https://github.com/dotnet/runtime/issues/57371</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case2/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" '$(RuntimeFlavor)' == 'mono' and '$(TargetArchitecture)' == 'arm64' and '$(TargetsWindows)' != 'true' " > <ExcludeList Include="$(XunitTestBinBase)/baseservices/typeequivalence/simple/Simple/**"> <Issue>Doesn't compile with LLVM AOT.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/Variance/IL/Unbox002/**"> <Issue>Doesn't compile with LLVM AOT.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/Variance/IL/Unbox003/**"> <Issue>Doesn't compile with LLVM AOT.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/Variance/IL/vsw543506/**"> <Issue>Doesn't compile with LLVM AOT.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b44657/b44657/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b63726/b63726/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b60142/b60142/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_487699/DevDiv_487699/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r8nanconv_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/flowgraph/dev10_bug679955/volatileLocal2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r8nanconv_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b36302/b36302/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r4nanconv_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r4nanconv_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b53980/b53980/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_mutual_rec_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b27873/b27873/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b53994/b53994/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_406156/DevDiv_406156/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_370233/DevDiv_370233/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b73207/b73207/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_switch_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b25701/b25701/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b50027/b50027/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b34953/b34953/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30892/b30892/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_switch_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b32614/b32614/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b82247/b82247/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b59952/b59952/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b49435/b49435/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_mutual_rec_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30862/b30862/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b45541/b45541/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b71003/b71003/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31547/b31547/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b45956/b45956/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/div_r8/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow02_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Base/ckfinite/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/div_r4/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow01_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/StructABI/StructABI/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/M00/b108366/b108366/**"> <Issue>needs triage</Issue> </ExcludeList> </ItemGroup> <!-- These are known failures on mono-arm64 in the interpreter runtime variant --> <ItemGroup Condition=" '$(RuntimeFlavor)' == 'mono' and ('$(TargetArchitecture)' == 'arm64') and '$(TargetsWindows)' != 'true' and '$(RuntimeVariant)' == 'monointerpreter' " > <!-- The following issues only effect the Mono interpreter; there is currently no way to exclude based on that scenario --> <ExcludeList Include = "$(XunitTestBinBase)JIT/IL_Conformance/Old/Base/ckfinite/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/pauseonstart/**"> <Issue> needs triage </Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" '$(TargetArchitecture)' == 'wasm' " > <ExcludeList Include="$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54867</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_ro/**"> <Issue>https://github.com/dotnet/runtime/issues/54867</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256_1/**"> <Issue>https://github.com/dotnet/runtime/issues/54122</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector128_1/**"> <Issue>https://github.com/dotnet/runtime/issues/54122</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/threading/DeadThreads/DeadThreads/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/threading/coverage/OSThreadId/osthreadid/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackStressTest_TargetUnix/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/API/NativeLibraryTests/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackTests/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/ICustomMarshaler/ConflictingNames/SameNameDifferentAssembly/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/HandleRef/HandleRefTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/MultipleAssembliesWithSamePInvoke/MAWSPITest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Pointer/NonBlittablePointer/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Vector2_3_4/Vector2_3_4/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/RuntimeHandles/RuntimeHandlesTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Int/PInvokeIntTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SetLastError/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/SuppressGCTransition/SuppressGCTransitionTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallConv/UnmanagedCallConvTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/LocallocLarge_d/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/LocallocLarge_do/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/LocallocLarge_ro/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/LocallocLarge_r/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/ThisCall/ThisCallTest/*"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/StdCallMemberFunction/StdCallMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/PlatformDefaultMemberFunction/PlatformDefaultMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/CdeclMemberFunction/CdeclMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CircularCctors/CircularCctorFourThreadsBFI/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CoreCLR/CircularCctorThreeThreads03/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/regressions/523654/test532654_b/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/opt/rngchk/ArrayWithThread_o/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/opt/cse/VolatileTest_op_mul/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/conv_ovf_r8_i/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/ldc_conv_ovf_r8_i/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/switchinfinally_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/switchinfinally_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/switchinfinally_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/switchinfinally_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/cctor/misc/threads1_cs_do/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b99969/b99969/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumps4_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumps4_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r8nanconv_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r8nanconv_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/gc_poll/InsertGCPoll/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_40444/Runtime_40444/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b426654/b426654/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/V1.2-M01/b10827/b10827/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b425314/b425314/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_27924/GitHub_27924/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlbigleakthd/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinkgen/**"> <Issue>https://github.com/dotnet/runtime/issues/56804</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlcollect/**"> <Issue>https://github.com/dotnet/runtime/issues/56804</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CheckProjects/CheckProjects/**"> <Issue>https://github.com/dotnet/runtime/issues/41520</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/mandelbrot/mandelbrot-2/**"> <Issue>https://github.com/dotnet/runtime/issues/56814</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/spectralnorm/spectralnorm-3/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/binarytrees/binarytrees-5/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/binarytrees/binarytrees-6/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fasta/fasta-1/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/mandelbrot/mandelbrot-7/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Regressions/v2.0-beta2/452950/452950/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Stress/Framework/ReliabilityFramework/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/plug/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit-finalize/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit-threaded/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/LOHCompaction/lohcompactapi/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit_1/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlstack/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/THDChaos/thdchaos/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinkstay/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/nstructtun/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/BinTree/thdtreegrowingobj/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinknoleak2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/ServerModel/servermodel/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/THDList/thdlist/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/BinTree/thdtreelivingobj/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/NDPin/ndpinfinal/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Resurrection/continue/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/BinTree/thdtree/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/FinalizeTimeout/FinalizeTimeout/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/NoGCRegion/NoGC/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_3/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs_1/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/LargeMemory/API/gc/gettotalmemory/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Coverage/LargeObjectAlloc/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Coverage/LargeObjectAlloc2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventactivityidcontrol/eventactivityidcontrol/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/eventsourceerror/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Exceptions/ForeignThread/ForeignThreadExceptions/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/PortablePdb/IlasmPortablePdbTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/System/Runtime/CompilerServices/MethodImplOptionsTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/opt/Devirtualization/box2/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-6/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/ConsoleMandel/ConsoleMandel/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-1/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/RunBenchmarks/RunBenchmarks/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Roslyn/CscBench/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Span/Indexer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Bytemark/Bytemark/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fannkuch-redux/fannkuch-redux-2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/regex-redux/regex-redux-5/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/RayTracer/RayTracer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_64125/Runtime_64125/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_64883/Runtime_64883/*"> <Issue>Loads an assembly from file</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/incrementingeventcounter/**"> <Issue>System.Threading.Thread.UnsafeStart not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/eventcounter/**"> <Issue>System.Threading.Thread.UnsafeStart not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/runtimecounters/**"> <Issue>System.Threading.Thread.UnsafeStart not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/incrementingpollingcounter/**"> <Issue>System.Threading.Thread.UnsafeStart not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/pollingcounter/**"> <Issue>System.Threading.Thread.UnsafeStart not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/gh53564/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverse/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/bigevent/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient and system.diagnostics.process not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processinfo2/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient and system.diagnostics.process not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/diagnosticport/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processinfo/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient and system.diagnostics.process not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/buffersize/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverseouter/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processenvironment/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/pauseonstart/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" $(TargetOS) == 'Android' " > <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/**"> <Issue>No crossgen folder under Core_Root</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Exceptions/ForeignThread/ForeignThreadExceptions/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_3/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs_1/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/System/Runtime/CompilerServices/MethodImplOptionsTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/ICustomMarshaler/ConflictingNames/SameNameDifferentAssembly/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Vector2_3_4/Vector2_3_4/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/MultipleAssembliesWithSamePInvoke/MAWSPITest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Int/PInvokeIntTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Pointer/NonBlittablePointer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/SetLastError/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/SuppressGCTransition/SuppressGCTransitionTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/RuntimeHandles/RuntimeHandlesTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/HandleRef/HandleRefTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CheckProjects/CheckProjects/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/ThisCall/ThisCallTest/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/StdCallMemberFunction/StdCallMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/PlatformDefaultMemberFunction/PlatformDefaultMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/CdeclMemberFunction/CdeclMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/eh/basics/throwinfinallyintryfilter2/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/hfa/main/testC/hfa_nd1C_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/LargeMemory/API/gc/gettotalmemory/**"> <Issue>https://github.com/dotnet/runtime/issues/54913</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/PortablePdb/IlasmPortablePdbTests/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/API/NativeLibraryTests/**"> <Issue>https://github.com/dotnet/runtime/issues/54905</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackStressTest_TargetUnix/**"> <Issue>https://github.com/dotnet/runtime/issues/54905</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/switch/switch5/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_void_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/recurse_ep_void_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/recurse_ep_void_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/switch/switch6/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_void_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-6/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Deserialize/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Span/SpanBench/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Span/Indexer/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/SeekUnroll/SeekUnroll/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Roslyn/CscBench/**"> <Issue>https://github.com/dotnet/runtime/issues/54908</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Serialize/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25468/GitHub_25468/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_36614/GitHub_36614/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/readytorun/multifolder/multifolder/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit-finalize/*"> <Issue>https://github.com/dotnet/runtime/issues/44643</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Regressions/v2.0-rtm/494226/494226/*"> <Issue>https://github.com/dotnet/runtime/issues/44643</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/ServerModel/servermodel/*"> <Issue>https://github.com/dotnet/runtime/issues/44643</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/gc_poll/InsertGCPoll/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/V8/Crypto/Crypto/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fasta/fasta-1/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/regex-redux/regex-redux-5/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/RayTracer/RayTracer/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/complus_config/name_config_with_pid/**"> <Issue>https://github.com/dotnet/runtime/issues/54974</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallConv/UnmanagedCallConvTest/**"> <Issue>https://github.com/dotnet/runtime/issues/53077</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Dynamo/dynamo/**"> <Issue>https://github.com/dotnet/runtime/issues/53350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/DelegatePInvoke/DelegatePInvokeTest/**"> <Issue>https://github.com/dotnet/runtime/issues/53351</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/**"> <Issue>https://github.com/dotnet/runtime/issues/53353</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/diagnosticport/**"> <Issue>Cannot run multiple apps on Android for subprocesses</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/pauseonstart/**"> <Issue>Cannot run multiple apps on Android for subprocesses</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processenvironment/**"> <Issue>Cannot run multiple apps on Android for subprocesses</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverse/**"> <Issue>Cannot run multiple apps on Android for subprocesses</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverseouter/**"> <Issue>Cannot run multiple apps on Android for subprocesses</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" $(TargetOS) == 'Android' And '$(TargetArchitecture)' == 'arm64' " > <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fannkuch-redux/fannkuch-redux-5/**"> <Issue>https://github.com/dotnet/runtime/issues/52781</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" $(TargetOS) == 'Android' And '$(RuntimeVariant)' == 'monointerpreter' " > <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/mandelbrot/mandelbrot-7/**"> <Issue>https://github.com/dotnet/runtime/issues/55528</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" $(TargetOS) == 'iOSSimulator' " > <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/MultipleAssembliesWithSamePInvoke/MAWSPITest/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/RuntimeHandles/RuntimeHandlesTest/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Pointer/NonBlittablePointer/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Vector2_3_4/Vector2_3_4/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Int/PInvokeIntTest/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/HandleRef/HandleRefTest/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/ICustomMarshaler/ConflictingNames/SameNameDifferentAssembly/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Attributes/SuppressGCTransition/SuppressGCTransitionTest/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/API/NativeLibraryTests/**"> <Issue>System.PlatformNotSupportedException: Operation is not supported on this platform</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackStressTest_TargetUnix/**"> <Issue>System.DllNotFoundException: DoesNotExist</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackTests/**"> <Issue>System.DllNotFoundException: DoesNotExist</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest/**"> <Issue>System.DllNotFoundException: UnmanagedCallersOnlyDll</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ObjectiveC/AutoReleaseTest/**"> <Issue>System.DllNotFoundException: ObjectiveC</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/SuppressGCTransition/SuppressGCTransitionTest/**"> <Issue>System.DllNotFoundException: SuppressGCTransitionNative</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_36614/GitHub_36614/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.assert, Version=2.4.1.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/gc_poll/InsertGCPoll/**"> <Issue>System.DllNotFoundException: GCPollNative</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/complus_config/name_config_with_pid/**"> <Issue>System.ArgumentNullException: Value cannot be null. (Parameter 'path1')</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/readytorun/multifolder/multifolder/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly '/.../Library/Developer/CoreSimulator/Devices/941235AB-7563-4D79-AC28-946B7AD2304A/data/Containers/Bundle/Application/40176A30-D8F5-4497-958A-6514E5C684FC/readytorun_multifolder.app/testdir-multifolder/../FolderA/FolderA/FolderA.dll' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Exceptions/ForeignThread/ForeignThreadExceptions/**"> <Issue>Failed to catch an exception! System.DllNotFoundException: ForeignThreadExceptionsNative</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs/**"> <Issue>USAGE: MultipleWR.exe num objects [track]</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs_1/**"> <Issue>USAGE: MultipleWR.exe num objects [track]</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_2/**"> <Issue>GC_API 0|1|2</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_3/**"> <Issue>GC_API 0|1|2</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/PortablePdb/IlasmPortablePdbTests/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.runner.utility.netcoreapp10, Version=2.4.1.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/System/Runtime/CompilerServices/MethodImplOptionsTests/**"> <Issue>Environment variable is not set: 'CORE_ROOT'</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/LargeMemory/API/gc/gettotalmemory/**"> <Issue>System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/ThisCall/ThisCallTest/*"> <Issue>System.DllNotFoundException: ThisCallNative</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/StdCallMemberFunction/StdCallMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/PlatformDefaultMemberFunction/PlatformDefaultMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/CdeclMemberFunction/CdeclMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Span/SpanBench/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Serialize/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fasta/fasta-1/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/regex-redux/regex-redux-5/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/RayTracer/RayTracer/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/V8/Crypto/Crypto/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Roslyn/CscBench/**"> <Issue>This test requires CORE_ROOT to be set</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fannkuch-redux/fannkuch-redux-5/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/SeekUnroll/SeekUnroll/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.assert, Version=2.4.1.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-6/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Deserialize/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Span/Indexer/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CheckProjects/CheckProjects/*"> <Issue>CORE_ROOT must be set</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25468/GitHub_25468/**"> <Issue>Could not load file or assembly 'System.Drawing.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/SetLastError/SetLastErrorTest/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallConv/UnmanagedCallConvTest/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/DelegatePInvoke/DelegatePInvokeTest/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/eventsourceerror/eventsourceerror/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/mul_ovf_u2/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b41126/b41126/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Dynamo/dynamo/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_DefaultMode_R2r/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_DefaultMode_R2r/*"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_QuickJitForLoopsOff_R2r/*"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_QuickJitForLoopsOn_R2r/*"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_QuickJitOff_R2r/*"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_QuickJitOn_R2r/*"> <Issue>missing assembly</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" '$(TargetArchitecture)' == 'wasm' or ('$(TargetOS)' == 'Android' or '$(TargetOS)' == 'iOSSimulator')"> <ExcludeList Include="$(XunitTestBinBase)/Interop/MonoAPI/**"> <Issue>mobile and wasm don't support tests with native libraries. wasm also needs static linking</Issue> </ExcludeList> </ItemGroup> </Project>
<?xml version="1.0" ?> <Project DefaultTargets = "GetListOfTestCmds" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- All OS/Arch/Runtime excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != ''"> <ExcludeList Include="$(XunitTestBinBase)/readytorun/DynamicMethodGCStress/DynamicMethodGCStress/*"> <Issue>timeout</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/GitHub_22888/test22888/*"> <Issue>https://github.com/dotnet/runtime/issues/13703</Issue> </ExcludeList> </ItemGroup> <!-- All OS/Arch CoreCLR excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(RuntimeFlavor)' == 'coreclr' "> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/StackTracePreserve/StackTracePreserveTests/*"> <Issue>https://github.com/dotnet/runtime/issues/11213</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/mono/runningmono/*"> <Issue>This test is to verify we are running mono, and therefore only makes sense on mono.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Coverage/271010/**"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Coverage/smalloom/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/BackgroundGC/foregroundgc/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/LOHFragmentation/lohfragmentation/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/Allocation/finalizertest/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/collect/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/getgeneration/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/reregisterforfinalize/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/dev10bugs/536168/536168/*"> <Issue>https://github.com/dotnet/runtime/issues/5933</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/readytorun/r2rdump/BasicTests/R2RDumpTest/*"> <Issue>https://github.com/dotnet/runtime/issues/10888 https://github.com/dotnet/runtime/issues/11823 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_255294/DevDiv_255294/*"> <Issue>https://github.com/dotnet/runtime/issues/44341</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/rvastatics/RVAOrderingTest/*"> <Issue>https://github.com/dotnet/runtime/issues/55966</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/HardwareIntrinsics/X86/X86Base/Pause*/**"> <Issue>https://github.com/dotnet/runtime/issues/62423</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest.Basic/*"> <Issue>https://github.com/dotnet/runtime/issues/57786</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/MonoAPI/**"> <Issue>CoreCLR does not implement the mono embedding API</Issue> </ExcludeList> </ItemGroup> <!-- All Unix targets on all runtimes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetsWindows)' != 'true'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/arglist/vararg_TargetUnix/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> </ItemGroup> <!-- All Unix targets on CoreCLR Runtime --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetsWindows)' != 'true' and '$(RuntimeFlavor)' == 'coreclr' "> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/stackoverflow/stackoverflowtester/*"> <Issue>https://github.com/dotnet/runtime/issues/46175</Issue> </ExcludeList> </ItemGroup> <!-- Arm32 All OS --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm' or '$(AltJitArch)' == 'arm') and '$(RuntimeFlavor)' == 'coreclr' "> <ExcludeList Include="$(XunitTestBinBase)/CoreMangLib/cti/system/reflection/emit/DynMethodJumpStubTests/DynMethodJumpStubTests/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeArray1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/hugeSimpleExpr1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/HeapExpansion/pluggaps/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/v2.0-beta2/460373/460373/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/v2.0-beta1/149926/149926/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/v2.0-rtm/494226/494226/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/dev10bugs/536168/536168/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetAllocatedBytesForCurrentThread/*"> <Issue>https://github.com/dotnet/runtime/issues/</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit-finalize/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/v2.0-rtm/494226/494226/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/dev10bugs/536168/536168/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/NoGCRegion/NoGC/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/LeakWheel/leakwheel/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/CoreMangLib/system/span/SlowTailCallArgs/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/rngchk/RngchkStress3/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/ServerModel/servermodel/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitintry/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitincatch/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/rngchk/ArrayWithThread_o/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinroot/*"> <Issue>times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/Tailcall/TailcallVerifyWithPrefix/*"> <Issue>Depends on implicit tailcalls to be performed</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/arglist/vararg*/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/WindowsEventLog/WindowsEventLog_TargetUnix/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i53/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i13/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i03/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i33/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i63/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i73/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i83/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/tailcall/test_implicit_il_d/*"> <Issue>https://github.com/dotnet/runtime/issues/8891 Arm32 does not support implicit tailcalls</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/tailcall/test_implicit_il_r/*"> <Issue>https://github.com/dotnet/runtime/issues/8891 Arm32 does not support implicit tailcalls</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Stress/ABI/**/*"> <Issue>https://github.com/dotnet/runtime/issues/13241</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/eventpipe/eventpipe/*"> <Issue>TraceEvent can't parse unaligned floats on arm32</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/unittest/releaseondetach/*"> <Issue>https://github.com/dotnet/runtime/issues/64986</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/eventpipe/eventpipe_readevents/*"> <Issue>TraceEvent can't parse unaligned floats on arm32</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/regress/vsw/373472/**"> <Issue>Allocates large contiguous array that is not consistently available on 32-bit platforms</Issue> </ExcludeList> <!-- Arm32 does not support hardware intrinsics --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> </ItemGroup> <!-- Arm64 All OS --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm64' or '$(AltJitArch)' == 'arm64') and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/hugeexpr1/hugeexpr1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeArray/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeArray1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeField1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeField2/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/CoreMangLib/cti/system/string/StringFormat1/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/CoreMangLib/cti/system/string/StringFormat2/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_590772/DevDiv_590772/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_605447/DevDiv_605447/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_590771/DevDiv_590771/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_56953/Runtime_56953/*"> <Issue>https://github.com/dotnet/runtime/issues/57515</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Generics/GenericsTest/*"> <Issue>https://github.com/dotnet/runtime/issues/60036</Issue> </ExcludeList> <!-- Arm64 does not support Vector256 --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256_1/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <!-- Arm64 does not support X86 hardware intrinsics --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/X86/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> </ItemGroup> <!-- Windows all architecture excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetsWindows)' == 'true' and '$(RuntimeFlavor)' == 'coreclr'"> </ItemGroup> <!-- Windows x64 specific excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetArchitecture)' == 'x64' and '$(TargetsWindows)' == 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport_r/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/GitHub_34094/Test34094/*"> <Issue>https://github.com/dotnet/runtime/issues/57458</Issue> </ExcludeList> <!-- X64 does not support Vector64 --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64_1/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <!-- X64 does not support Arm hardware intrinsics --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> </ItemGroup> <!-- Windows x86 specific excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetArchitecture)' == 'x86' and '$(TargetsWindows)' == 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/Allocation/largeexceptiontest/*"> <Issue>https://github.com/dotnet/runtime/issues/5200 Test is useful to have because it can be run manually when making changes to the GC that can have effects in OOM scenarios, but not appropriate to run on our current test infrastructure.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/gettotalmemory/*"> <Issue>https://github.com/dotnet/runtime/issues/5200 Test is useful to have because it can be run manually when making changes to the GC that can have effects in OOM scenarios, but not appropriate to run on our current test infrastructure.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/keepalive/*"> <Issue>https://github.com/dotnet/runtime/issues/5200 Test is useful to have because it can be run manually when making changes to the GC that can have effects in OOM scenarios, but not appropriate to run on our current test infrastructure.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/LargeMemory/API/gc/suppressfinalize/*"> <Issue>https://github.com/dotnet/runtime/issues/5200 Test is useful to have because it can be run manually when making changes to the GC that can have effects in OOM scenarios, but not appropriate to run on our current test infrastructure.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/Tailcall/TailcallVerifyWithPrefix/*"> <Issue>Depends on implicit tailcalls to be performed</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_255294/DevDiv_255294/*"> <Issue>https://github.com/dotnet/runtime/issues/8034 The test causes OutOfMemory exception in crossgen mode.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport_r/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/regress/vsw/373472/**"> <Issue>Allocates large contiguous array that is not consistently available on 32-bit platforms</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/GitHub_34094/Test34094/*"> <Issue>https://github.com/dotnet/runtime/issues/57458</Issue> </ExcludeList> <!-- X86 does not support Vector64 --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64_1/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <!-- X86 does not support Arm hardware intrinsics --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> </ItemGroup> <!-- Windows arm32 specific excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm' or '$(AltJitArch)' == 'arm') and '$(TargetsWindows)' == 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/Convert/out_of_range_fp_to_int_conversions/*"> <Issue>https://github.com/dotnet/runtime/issues/49184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/Primitives/NETClientPrimitives/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/Primitives/NETClientPrimitivesInALC/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NativeClients/Primitives/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/Lifetime/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NativeClients/Licensing/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NativeClients/DefaultInterfaces/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/IDispatch/NETClientIDispatch/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/Aggregation/NETClientAggregation/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/Licensing/NETClientLicense/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/NETClients/ConsumeNETServer/ConsumeNETServer/*"> <Issue>https://github.com/dotnet/runtime/issues/11360</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/ThisCall/ThisCallTest/*"> <Issue>Native member function calling conventions not supported on Windows ARM32.</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/StdCallMemberFunction/StdCallMemberFunctionTest/*"> <Issue>Native member function calling conventions not supported on Windows ARM32.</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/PlatformDefaultMemberFunction/PlatformDefaultMemberFunctionTest/*"> <Issue>Native member function calling conventions not supported on Windows ARM32.</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/CdeclMemberFunction/CdeclMemberFunctionTest/*"> <Issue>Native member function calling conventions not supported on Windows ARM32.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b88793/b88793/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b37646/b37646/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/1/arglist_Target_ARM/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b41391/b41391/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i00/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i70/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i32/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i51/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b32374/b32374/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Varargs/VarargsTest/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/volatile/1/arglist_Target_ARM/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b28901/b28901/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i82/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i80/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/gc/misc/funclet/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30864/b30864/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30838/b30838/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_r/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i61/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i60/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i31/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-EJIT/V1-M12-Beta2/b26323/b26323/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b26324/b26324a/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b26324/b26324b/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i50/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i62/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b36472/b36472/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i72/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b37598/b37598/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b46867/b46867/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b409748/b409748/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i30/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16423/b16423/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/2/arglist_Target_ARM/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_d/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Coverage/arglist_pos/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b35784/b35784/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31746/b31746/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i12/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i52/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i81/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i11/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b41852/b41852/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i02/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i01/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i71/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31745/b31745/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b91248/b91248/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/4/arglist_Target_ARM/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i10/*"> <Issue>https://github.com/dotnet/runtime/issues/12979</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/regress/vsw/373472/**"> <Issue>Allocates large contiguous array that is not consistently available on 32-bit platforms</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/GitHub_45929/test45929/*"> <Issue>https://github.com/dotnet/runtime/issues/60152</Issue> </ExcludeList> </ItemGroup> <!-- Windows arm64 specific excludes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm64' or '$(AltJitArch)' == 'arm64') and '$(TargetsWindows)' == 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/Tailcall/TailcallVerifyWithPrefix/*"> <Issue>Condition17::Test1 checks that we tail call via helper when security cookie is needed; on arm64 we fast tail call in this case.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Regressions/dev10bugs/536168/536168/*"> <Issue>extremely memory/time intensive test</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/NoGCRegion/NoGC/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport_r/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport/*"> <Issue>Varargs supported on this platform</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/rngchk/RngchkStress3/*"> <Issue>Needs Triage</Issue> </ExcludeList> </ItemGroup> <!-- The following are x64 Unix failures on CoreCLR. --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetArchitecture)' == 'x64' and '$(TargetsWindows)' != 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/simple/ParallelCrashWorkerThreads/*"> <Issue>https://github.com/dotnet/runtime/issues/57621</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_d/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_r/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress1_r/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress3_r/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress1_do/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress3_do/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress1_ro/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/stress3_ro/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b41391/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b37646/*"> <Issue>https://github.com/dotnet/runtime/issues/10478 </Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/pinning/object-pin/*"> <Issue>Issue building native components for the test.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_18232/GitHub_18232/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_19022/GitHub_19022/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_19149/GitHub_19149/*"> <Issue>Needs Triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/rngchk/RngchkStress3/*"> <Issue>timeout</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_19601/Github_19601/*"> <Issue>Needs Triage</Issue> </ExcludeList> <!-- X64 does not support Vector64 --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64_1/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> <!-- X64 does not support Arm hardware intrinsics --> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/**"> <Issue>https://github.com/dotnet/runtime/issues/60154</Issue> </ExcludeList> </ItemGroup> <!-- Unix arm64 specific --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm64' or '$(AltJitArch)' == 'arm64') and '$(TargetsWindows)' != 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler/*"> <Issue>Test times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally/*"> <Issue>Test times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitintry/*"> <Issue>Test times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitincatch/*"> <Issue>Test times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/eh/FinallyExec/nonlocalexitinroot/*"> <Issue>Test times out</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlstack/*"> <Issue>Release only crash</Issue> </ExcludeList> </ItemGroup> <!-- Unix arm32 specific --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TargetArchitecture)' == 'arm' or '$(AltJitArch)' == 'arm') and '$(TargetsWindows)' != 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/regress/vsw/373472/**"> <Issue>Allocates large contiguous array that is not consistently available on 32-bit platforms</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_56953/Runtime_56953/*"> <Issue>https://github.com/dotnet/runtime/issues/57856</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/multiple/multiple/*"> <Issue>https://github.com/dotnet/runtime/issues/57875</Issue> </ExcludeList> </ItemGroup> <!-- Tests that need to be triaged for vararg usage as that is not supported --> <!-- Note these will only be excluded for unix platforms on all runtimes --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetsWindows)' != 'true' "> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/1/arglist*/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/2/arglist*/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/unaligned/4/arglist*/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/PREFIX/volatile/1/arglist*/*"> <Issue>needs triage</Issue> </ExcludeList> </ItemGroup> <!-- Tests that need to be triaged for vararg usage as that is not supported --> <!-- Note these will only be excluded for unix platforms on CoreCLR only --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TargetsWindows)' != 'true' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/gc/misc/funclet/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i00/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i01/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i02/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i03/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i10/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i11/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i12/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i13/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i30/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i31/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i32/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i33/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i50/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i51/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i52/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i53/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i60/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i61/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i62/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i63/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i70/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i71/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i72/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i73/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i80/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i81/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i82/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/mcc/interop/mcc_i83/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Coverage/arglist_pos/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_d/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/seq_il_r/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-EJIT/V1-M12-Beta2/b26323/b26323/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16423/b16423/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b26324/b26324a/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b26324/b26324b/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b28901/b28901/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30838/b30838/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30864/b30864/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b32374/b32374/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b35784/b35784/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b36472/b36472/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b37598/b37598/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b41391/b41391/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b46867/b46867/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31745/b31745/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31746/b31746/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b37646/b37646/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b41852/b41852/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b88793/b88793/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b91248/b91248/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b409748/b409748/*"> <Issue>needs triage</Issue> </ExcludeList> </ItemGroup> <!-- Failures while testing via ILLINK --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(RunTestsViaIllink)' == 'true'"> <ExcludeList Include="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/*"> <!-- Linker runs reset CORE_ROOT to the linked directory based on superpmicollect.exe. The test runs other benchmarks to collect superpmi data. These tests cannot run from the binaries generated wrt superpmicollect.exe --> <Issue>By Test Infrastructure design</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/RVAInit/nested/*"> <!-- Data refered from static field is dropped --> <Issue>Bug</Issue> </ExcludeList> </ItemGroup> <!-- Crossgen2 specific --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and ('$(TestBuildMode)' == 'crossgen2' or '$(TestBuildMode)' == 'crossgen') and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/NativeVarargs/NativeVarargsTest/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/CopyConstructorMarshaler/CopyConstructorMarshaler/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/ManagedCallingNative/ManagedCallingNative/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/LoadIjwFromModuleHandle/LoadIjwFromModuleHandle/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/NativeCallingManaged/NativeCallingManaged/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/FixupCallsHostWhenLoaded/FixupCallsHostWhenLoaded/*"> <Issue>https://github.com/dotnet/runtime/issues/38096</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/v2.1/DDB/B168384/LdfldaHack/*"> <Issue>https://github.com/dotnet/runtime/issues/615</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035/*"> <Issue>https://github.com/dotnet/runtime/issues/64419</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/*"> <Issue>Not compatible with crossgen2</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/PInvoke/MarshalStructAsLayoutExp/*"> <Issue>https://github.com/dotnet/runtime/issues/43461</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/dev10_715437/dev10_715437/*"> <Issue>https://github.com/dotnet/runtime/issues/43498</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_34170/Runtime_34170/*"> <Issue>https://github.com/dotnet/runtime/issues/53560</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/debugging/poisoning/poison/*"> <Issue>https://github.com/dotnet/runtime/issues/56148</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/hugeexpr1/*"> <Issue>https://github.com/dotnet/runtime/issues/62881</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/AdvSimd.Arm64_Part2_ro/*"> <Issue>https://github.com/dotnet/runtime/issues/63856</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/AdvSimd.Arm64_Part2_r/*"> <Issue>https://github.com/dotnet/runtime/issues/63856</Issue> </ExcludeList> </ItemGroup> <!-- NativeAOT specific --> <ItemGroup Condition="'$(XunitTestBinBase)' != '' and '$(TestBuildMode)' == 'nativeaot' and '$(RuntimeFlavor)' == 'coreclr'"> <ExcludeList Include="$(XunitTestBinBase)/nativeaot/SmokeTests/MultiModule/MultiModule/*"> <Issue>https://github.com/dotnet/runtime/issues/66191</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/callconvs/TestCallingConventions/*"> <Issue>https://github.com/dotnet/runtimelab/issues/153</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/compilerservices/RuntimeWrappedException/RuntimeWrappedException/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Wrapping non-exception throws</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/RefEmit/EmittingIgnoresAccessChecksToAttributeIsRespected/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Reflection.Emit</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25468/GitHub_25468/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: BinaryFormatter</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/stackoverflow/stackoverflowtester/*"> <Issue>Specific to CoreCLR</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/threading/coverage/OSThreadId/osthreadid/*"> <Issue>Accessing a reflection blocked internal detail</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/threading/paramthreadstart/ThreadStartBool/*"> <Issue>https://github.com/dotnet/runtimelab/issues/220</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/TieredCompilation/**"> <Issue>No crossgen folder under Core_Root</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/typeequivalence/simple/Simple/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Type equivalence</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/WeakReference/Finalize2/*"> <Issue>Expectations about finalization order</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/ilasm/PortablePdb/IlasmPortablePdbTests/*"> <Issue>Specific to CoreCLR</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/ilasm/System/Runtime/CompilerServices/MethodImplOptionsTests/*"> <Issue>Specific to CoreCLR</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ArrayMarshalling/SafeArray/SafeArrayTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: SAFEARRAY</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: COM</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ExecInDefAppDom/ExecInDefAppDom/*"> <Issue>Specific to CoreCLR</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ICustomMarshaler/ConflictingNames/MultipleALCs/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: AssemblyLoadContext.LoadFromAssemblyPath</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IJW/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: C++/CLI</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/LayoutClass/LayoutClassTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/163</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/MarshalAPI/FunctionPointer/FunctionPtrTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/164</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/MarshalAPI/IUnknown/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: COM</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/NativeLibrary/API/NativeLibraryTests/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/NativeLibrary/AssemblyLoadContext/ResolveUnmanagedDllTests/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackStressTest_TargetWindows/*"> <Issue>https://github.com/dotnet/runtimelab/issues/166</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackTests/*"> <Issue>https://github.com/dotnet/runtimelab/issues/206</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Array/MarshalArrayAsParam/AsDefault/AsDefaultTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/176: VARIANT marshalling</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/ArrayWithOffset/ArrayWithOffsetTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/170</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/AsAny/AsAnyTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/169</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Attributes/LCID/LCIDTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/171</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Attributes/SuppressGCTransition/SuppressGCTransitionTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/BestFitMapping/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/172</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/CriticalHandles/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/173</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/CustomMarshalers/CustomMarshalersTest/*"> <Issue>Specific to CoreCLR: Built-in COM Interop</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Decimal/DecimalTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/175</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Delegate/DelegateTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/176: IDispatch</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Generics/GenericsTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/177</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/IEnumerator/IEnumeratorTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: COM</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/CopyCtor/CopyCtorTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: C++/CLI</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/NativeCallManagedComVisible/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: COM</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SafeHandles/SafeHandleTests/*"> <Issue>https://github.com/dotnet/runtimelab/issues/168</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/ReversePInvoke/**/*"> <Issue>https://github.com/dotnet/runtimelab/issues/167</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Varargs/VarargsTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Varargs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Variant/VariantTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: VARIANT marshalling</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StringMarshalling/VBByRefStr/VBByRefStrTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/179</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/PInvoke/MarshalStructAsLayoutSeq/*"> <Issue>https://github.com/dotnet/runtimelab/issues/180</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalExpStruct/ReversePInvokeManaged/ReversePInvokeTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/180</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/DelegatePInvoke/DelegatePInvokeTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/180</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/ReversePInvoke/ReversePInvokeTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/180</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructPacking/StructPacking/*"> <Issue>https://github.com/dotnet/runtimelab/issues/181</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest/*"> <Issue>https://github.com/dotnet/runtimelab/issues/154</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/WinRT/WinRT/*"> <Issue>https://github.com/dotnet/runtimelab/issues/182</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/arglist/vararg_TargetWindows/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Varargs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/forceinlining/NegativeCases/*"> <Issue>https://github.com/dotnet/runtimelab/issues/183</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/pinvoke/calli_excep/*"> <Issue>https://github.com/dotnet/runtimelab/issues/166</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/tailcall/more_tailcalls/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Tailcalls</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/throwbox/fault/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throws</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/throwbox/filter/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throws</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/throwbox/finally/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throws</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/throwbox/rethrow/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throws</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector128_1/Vector128_1_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector128_1/Vector128_1_ro/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64_1/Vector64_1_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector64_1/Vector64_1_ro/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256_1/Vector256_1_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256_1/Vector256_1_ro/*"> <Issue>https://github.com/dotnet/runtimelab/issues/184</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/cse/hugeSimpleExpr1/*"> <Issue>https://github.com/dotnet/runtimelab/issues/190</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/inl/caninline_d/*"> <Issue>https://github.com/dotnet/runtimelab/issues/183</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/inl/caninline_do/*"> <Issue>https://github.com/dotnet/runtimelab/issues/183</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/inl/caninline_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/183</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/inl/caninline_ro/*"> <Issue>https://github.com/dotnet/runtimelab/issues/183</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Arrays/misc/_il_relinitializearray/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: RuntimeHelpers.InitializeArray</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Arrays/misc/_il_dbginitializearray/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: RuntimeHelpers.InitializeArray</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinfilter_il_d/*"> <Issue>https://github.com/dotnet/runtimelab/issues/188</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinfilter_il_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/188</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/interactions/throw1dimarray_d/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throw</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/interactions/throw1dimarray_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throw</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/interactions/throw2dimarray_d/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throw</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/eh/interactions/throw2dimarray_r/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Non-exception throw</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/ObjectStackAllocation/ObjectStackAllocationTests/*"> <Issue>Need to pass flag to enable object stack allocation in RyuJIT</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/Devirtualization/Comparer_get_Default/*"> <Issue>https://github.com/dotnet/runtimelab/issues/1136</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fasta/fasta-1/*"> <Issue>Multimodule incompatible (GVM)</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/regex-redux/regex-redux-1/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/regex-redux/regex-redux-5/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-1/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-6/*"> <Issue>Needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/Burgers/Burgers/*"> <Issue>Multimodule incompatible (GVM)</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Deserialize/*"> <Issue>Needs xunit.performance</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Serialize/*"> <Issue>Needs xunit.performance</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b68872/b68872/*"> <Issue>https://github.com/dotnet/runtimelab/issues/188</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b71120/b71120/**"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Varargs</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b353858/b353858/**"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Thorough checking of invalid inputs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/v2.2/ddb/b429039/b429039/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: RuntimeHelpers.InitializeArray</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/*"> <Issue>https://github.com/dotnet/runtimelab/issues/196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_19444/GitHub_19444/*"> <Issue>https://github.com/dotnet/runtimelab/issues/197</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_22583/GitHub_22583/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Type equivalence</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25020/GitHub_25020/*"> <Issue>https://github.com/dotnet/runtimelab/issues/154</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25027/GitHub_25027/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Thorough checking of invalid inputs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_35384/GitHub_35384/*"> <Issue>https://github.com/dotnet/runtimelab/issues/198</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_4044/GitHub_4044/*"> <Issue>https://github.com/dotnet/runtimelab/issues/188</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/*"> <Issue>CoreCLR test</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/AssemblyDependencyResolver/AssemblyDependencyResolverTests/AssemblyDependencyResolverTests/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/AssemblyLoadContext30Extensions/AssemblyLoadContext30Extensions/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest.Basic/*"> <Issue>AOT incompatible</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest.ResolutionFlow/*"> <Issue>AOT incompatible</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/DictionaryExpansion/DictionaryExpansion/*"> <Issue>https://github.com/dotnet/runtimelab/issues/154</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/Regressions/ASURT/ASURT150271/test3/*"> <Issue>Won't fix https://github.com/dotnet/corert/issues/2396</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/Instantiation/Negative/abstract01/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Thorough checking of invalid inputs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/MethodImpl/generics_override1/*"> <Issue>https://github.com/dotnet/runtimelab/issues/207</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/347422/b347422/*"> <Issue>https://github.com/dotnet/runtimelab/issues/194</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/529206/vsw529206ModuleCctor/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: compat for exceptions thrown from module cctor</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/asurt150271/test3/*"> <Issue>https://github.com/dotnet/runtimelab/issues/202</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TSAmbiguities/CollapsedInterfaces/HelloWorld/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Thorough checking of invalid inputs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TSAmbiguities/SameMethodImpl/Override/HelloWorld/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Thorough checking of invalid inputs</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/ByRefLocals/ByRefLocals/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/Statics/CollectibleStatics/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_64883/Runtime_64883/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/ContextualReflection/ContextualReflection/*"> <Issue>https://github.com/dotnet/runtimelab/issues/165</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/regressions/GitHub_15544/main/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: AssemblyName.GetAssemblyName</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/**/*"> <Issue>CoreCLR test</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/readytorun/**/*"> <Issue>CoreCLR test</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/Modifiers/modifiers/*"> <Issue>https://github.com/dotnet/runtimelab/issues/201</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/RefEmit/EmittingIgnoresAccessChecksToAttributeIsRespected\EmittingIgnoresAccessChecksToAttributeIsRespected/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Ref emit</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/SetValue/TrySetReadonlyStaticField/*"> <Issue>https://github.com/dotnet/runtimelab/issues/200</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/tracing/**/*"> <Issue>EventPipe</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b426654/b426654/*"> <Issue>https://github.com/dotnet/runtimelab/issues/208</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/v2.1/DDB/B168384/LdfldaHack/*"> <Issue>https://github.com/dotnet/runtime/issues/615</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_754566/DevDiv_754566/*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Complext tail calls</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection\DefaultInterfaceMethods\Emit\*"> <Issue>https://github.com/dotnet/runtimelab/issues/155: Reflection.Emit</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection\DefaultInterfaceMethods\GetInterfaceMapConsumer\*"> <Issue>https://github.com/dotnet/runtimelab/issues/861</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop\IDynamicInterfaceCastable\IDynamicInterfaceCastable\*"> <Issue>https://github.com/dotnet/runtimelab/issues/1442</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)\Interop\PInvoke\Variant\VariantTestBuiltInComDisabled\*"> <Issue>https://github.com/dotnet/runtimelab/issues/306</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)\Interop\PInvoke\Variant\VariantTestComWrappers\*"> <Issue>https://github.com/dotnet/runtimelab/issues/306</Issue> </ExcludeList> <!-- Complex constrained calls --> <!-- https://github.com/dotnet/runtimelab/issues/1431 --> <ExcludeList Include="$(XunitTestBinBase)/Regressions\coreclr\16354\notimplemented\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader\DefaultInterfaceMethods\constrainedcall\constrainedcall\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader\DefaultInterfaceMethods\constrainedcall\constrained2\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader\DefaultInterfaceMethods\constrainedcall\constrained2_gm\*" /> <!-- Catch(T) in shared code --> <!-- https://github.com/dotnet/runtimelab/issues/204 --> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\throwincatch_d\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\throwincatch_do\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\throwincatch_r\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\throwincatch_ro\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchnestedtype_d\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchnestedtype_do\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchnestedtype_r\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchnestedtype_ro\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchsimpletype_d\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchsimpletype_do\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchsimpletype_r\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\eh\generics\trycatchsimpletype_ro\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/InstructionCombining/ArrayLengthArithmetic/*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b441487/b441487/*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_21990/GitHub_21990/*" /> <!-- Arrays with non-zero lower bounds --> <!-- https://github.com/dotnet/runtimelab/issues/155 --> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_b\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_i4\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_objref\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_r4\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_r8\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_struct\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\huge\_il_relhuge_u8\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\misc\_il_dbgaddress\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\misc\_il_dbgldelem_get\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\misc\_il_reladdress\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\misc\_il_relgcarr\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\misc\_il_relldelem_get\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgfloat64_range1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgfloat64_range2\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgint32_1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgint32_m1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgint32_neg_range\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgint32_range1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_dbgint32_range2\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relfloat64_range1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relfloat64_range2\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relint32_1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relint32_m1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relint32_neg_range\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relint32_range1\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\Arrays\range\_il_relint32_range2\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\int64\arrays\_il_relhugedim\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\refany\_il_dbgarray2\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\refany\_il_dbgarray3\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\refany\_il_relarray3\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\tailcall\_il_dbgdeep_array_nz\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\tailcall\_il_reldeep_array_nz\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\VT\port\_il_dbghuge_gcref\*" /> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical\VT\port\_il_relhuge_gcref\*" /> <!-- Covariant returns --> <!-- https://github.com/dotnet/runtimelab/issues/205 --> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\Interfaces\UnitTest\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\Interfaces\UnsupportedScenario1\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\Interfaces\UnsupportedScenario2\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\Interfaces\UnsupportedScenario3\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\ReturnTypeValidation\ImplicitOverrideSameSigAsDecl\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\ReturnTypeValidation\OverrideSameSigAsDecl\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\Structs\IncompatibleOverride\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\AttributeTesting\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\CompatibleWithTest\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\UnitTest\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\UnitTest_GVM\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\UnitTestDelegates\*" /> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\MethodImpl\CovariantReturns\UnitTest\OverrideMoreDerivedReturn\*" /> <!-- Static virtual methods --> <ExcludeList Include="$(XunitTestBinBase)/Loader\classloader\StaticVirtualMethods\**" /> </ItemGroup> <!-- run.proj finds all the *.cmd/*.sh scripts in a test folder and creates corresponding test methods. Exclude these scripts to avoid creating such methods for the superpmicollect dependent test projects and running them separately from superpmicollect test. These should be excluded regardless of RuntimeFlavor/os/arch--> <ItemGroup Condition="'$(XunitTestBinBase)' != ''"> <ExcludeList Include="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/*" Exclude="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/superpmicollect.*"> <Issue>Do not run these scripts separately from superpmicollect test</Issue> </ExcludeList> </ItemGroup> <!-- Known failures for mono runtime on *all* architectures/operating systems in *all* runtime modes --> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono'" > <ExcludeList Include = "$(XUnitTestBinBase)/JIT/HardwareIntrinsics/X86/X86Base/Pause*/**"> <Issue>https://github.com/dotnet/runtime/issues/61693</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/reflection/GenericAttribute/**"> <Issue>https://github.com/dotnet/runtime/issues/56887</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/X86/Sse2.X64/StoreNonTemporal_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54176</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/X86/Sse2.X64/StoreNonTemporal_ro/**"> <Issue>https://github.com/dotnet/runtime/issues/54176</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/X86/Sse42.X64/Crc32_*/**"> <Issue>https://github.com/dotnet/runtime/issues/54185</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/Convert/out_of_range_fp_to_int_conversions/*"> <Issue>Mono does not define out of range fp to int conversions</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/DynamicPgo/**"> <Issue>Mono doesn't have a dynamic pgo or tiered compilation infrastructure</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/SIMD/Vector3Interop_r/*"> <Issue>https://github.com/dotnet/runtime/issues/46174</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/SIMD/Vector3Interop_ro/*"> <Issue>https://github.com/dotnet/runtime/issues/46174</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTestWithMcj/*"> <Issue>Tests features specific to coreclr</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/RuntimeConfiguration/*"> <Issue>Tests features specific to coreclr</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/ByRefLocals/**"> <Issue>https://github.com/dotnet/runtime/issues/40394</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/CollectibleAssemblies/Statics/**"> <Issue>https://github.com/dotnet/runtime/issues/40394</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/CopyCtor/**"> <Issue>Handling for Copy constructors isn't present in mono interop</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StringMarshalling/AnsiBSTR/AnsiBStrTest/**"> <Issue>Crashes during LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StringMarshalling/BSTR/BSTRTest/**"> <Issue>Crashes during LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/Structs/IncompatibleOverride/**"> <Issue>Crashes during LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/HwiOp/CompareVectorWithZero/**"> <Issue>https://github.com/dotnet/runtime/pull/65632#issuecomment-1046294324</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/InstructionCombining/DivToMul/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/StructABI/StructABI/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_15949/GitHub_15949/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_15291/GitHub_15291/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16928/b16928/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/osr/osr015/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/opt/rngchk/ArrayBound_o/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CctorsWithSideEffects/CctorThrowInlinedStatic/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/UnitTest/CompatibleWithTest/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CctorsWithSideEffects/CctorThrowMethodAccess/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/UnitTest/CompatibleWithTest/**"> <Issue>Doesn't pass after LLVM AOT compilation.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/StaticVirtualMethods/GenericContext/**"> <Issue>Static virtual methods are not yet implemented in the Mono runtime.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/StaticVirtualMethods/InterfaceVariance/**"> <Issue>Static virtual methods are not yet implemented in the Mono runtime.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/StaticVirtualMethods/NegativeTestCases/**"> <Issue>Static virtual methods are not yet implemented in the Mono runtime.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/exceptions/stackoverflow/stackoverflowtester/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/callconvs/TestCallingConventions/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/Collect1/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/CollectionCountTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetGCMemoryInfo/**"> <Issue>https://github.com/dotnet/runtime/issues/37950</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetGeneration/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetGeneration_fail/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetGenerationWR/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/GetTotalAllocatedBytes/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GC/MaxGeneration/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/GCSettings/InputValidation/**"> <Issue>https://github.com/dotnet/runtime/issues/46666</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)GC/API/WeakReference/Finalize2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)GC/API/WeakReference/Finalize2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/LOHCompaction/lohpin/**"> <Issue>https://github.com/dotnet/runtime/issues/46666</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/ReflectObj/reflectobj/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/API/WeakReference/NullHandle/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizeexcep/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizenested/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizearray/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizedest/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizearraysleep/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizeinherit/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Features/Finalizer/finalizeio/finalizeio/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/BaseFinal/basefinal/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/NDPin/ndpinfinal/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlbigleak/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinknoleak/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinknoleak2/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinkstay/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinkgen/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlbigleakthd/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlstack/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlcollect/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/nstructtun/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/finalnstruct/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/nstructresur/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/WeakReference/weakreffinal/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/Resurrection/continue/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/Rootmem/rootmem/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/SingLinkList/singlinkgen/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/LeakWheel/leakwheel/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/ReflectObj/reflectobj/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/FragMan/fragman/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/LeakGen/leakgen/**"> <Issue>PlatformDetection.IsPreciseGcSupported false on mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/GC/Scenarios/SingLinkList/singlinkgen/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ArrayMarshalling/ByValArray/MarshalArrayByValTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/Reflection/Reflection/**"> <Issue>https://github.com/dotnet/runtime/issues/34371</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/COM/ComWrappers/**"> <Issue>Not supported on Mono</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ICastable/Castable/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/IDynamicInterfaceCastable/IDynamicInterfaceCastable/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ICustomMarshaler/ConflictingNames/MultipleALCs/**"> <Issue>https://github.com/dotnet/runtime/issues/34072</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ICustomMarshaler/Primitives/ICustomMarshaler_TargetUnix/**"> <Issue>https://github.com/dotnet/runtime/issues/34374</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/LayoutClass/LayoutClassTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/MarshalAPI/FunctionPointer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/NativeLibrary/AssemblyLoadContext/ResolveUnmanagedDllTests/**"> <Issue>https://github.com/dotnet/runtime/issues/41180</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ObjectiveC/ObjectiveCMarshalAPI/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Array/MarshalArrayAsField/AsByValArray/AsByValArrayTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Array/MarshalArrayAsField/AsLPArray/AsLPArrayTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Array/MarshalArrayAsParam/AsDefault/AsDefaultTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Array/MarshalArrayAsParam/AsLPArray/AsLPArrayTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/ArrayWithOffset/ArrayWithOffsetTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/AsAny/AsAnyTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/CriticalHandles/ArrayTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/CriticalHandles/StructTest/StructTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/CriticalHandles/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/DateTime/DateTimeTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Decimal/DecimalTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Delegate/DelegateTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Generics/GenericsTest/GenericsTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SafeHandles/**"> <Issue>https://github.com/dotnet/runtime/issues/48084</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/PInvoke/Invalid/InvalidParamIndex/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/PInvoke/PassingByOut/PassingByOutTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/PInvoke/PassingByRef/PassingByRefTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/ReversePInvoke/PassingByOut/PassingByOutTest/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SizeParamIndex/ReversePInvoke/PassingByRef/PassingByRefTest/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StringMarshalling/LPSTR/LPSTRTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/PInvoke/MarshalStructAsLayoutSeq/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/ReversePInvoke/ReversePInvokeTest/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/StructPacking/StructPacking/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/Convert/ldind_conv/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/coverage/compiler/FilterToHandler/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/badldsfld_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/badldsfld_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/tailcall/more_tailcalls/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/tailcall/mutual_recursion/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Directed/newarr/newarr/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_il/**"> <Issue>https://github.com/dotnet/runtime/issues/54867</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/call/call05_large/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/call/call05_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh05_dynamic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh05_large/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh05_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh06_dynamic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh06_large/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh06_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh07_dynamic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh07_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh08_dynamic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh08_large/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh08_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Boxing/morph/sin3double/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/KeepAliveBoxOpt/**"> <Issue>Relies on precise finalization and thus precise GC</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/doublearray/dblarray2_cs_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/doublearray/dblarray2_cs_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/doublearray/dblarray2_cs_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/doublearray/dblarray2_cs_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/doublearray/dblarray3_cs_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Methodical/refany/lcs_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)JIT/Methodical/tailcall_v4/hijacking/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/opt/ObjectStackAllocation/ObjectStackAllocationTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Performance/CodeQuality/BilinearInterpol/BilinearInterpol/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31283/b31283/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b091942/b091942/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b441487/b441487/**"> <Issue>https://github.com/dotnet/runtime/issues/34383</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/v2.1/DDB/B168384/LdfldaHack/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/Dev11/Dev11_468598/Test_HndIndex_10_Plain/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/Dev11/Dev11_468598/Test_HndIndex_10_Reordered/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_545500/**"> <Issue>https://github.com/dotnet/runtime/issues/34084</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/devdiv_902271/DevDiv_902271/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_18144/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_18295/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_23411/**"> <Issue>https://github.com/dotnet/runtime/issues/34196</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_23791/**"> <Issue>https://github.com/dotnet/runtime/issues/34385</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_27169/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_27551/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_27678/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_35384/GitHub_35384/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_4044/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_34587/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/V1.2-M02/b10828/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/superpmi/superpmicollect/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/AssemblyDependencyResolver/AssemblyDependencyResolverTests/AssemblyDependencyResolverTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest.ResolutionFlow/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/binding/tracing/BinderTracingTest.Basic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/DefaultInterfaceMethods/reabstraction/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/Regressions/ASURT/ASURT150271/test3/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/Instantiation/Negative/abstract01/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/regressions/dev10_531793/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/Interfaces/**"> <Issue>https://github.com/dotnet/runtime/issues/37509</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/347422/b347422/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/GitHub_11371/Negative_ByRefLikeType/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/regressions/vsw529206/vsw529206ModuleCctor/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/rmv/il/RMV-2-15-12b/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TSAmbiguities/CollapsedInterfaces/HelloWorld/**"> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TSAmbiguities/SameMethodImpl/Override/HelloWorld/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CctorsWithSideEffects/CctorThrowLDFTNStaticMethod/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CctorsWithSideEffects/CctorThrowStaticFieldBFI/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CctorsWithSideEffects/TypeLoadInitExcepBFI/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CoreCLR/CctorThrowStaticFieldBFI/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/ContextualReflection/ContextualReflection/**"> <Issue>https://github.com/dotnet/runtime/issues/34072</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/elt/slowpatheltenter/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/elt/slowpatheltleave/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/unittest/metadatagetdispenser/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/profiler/rejit/rejit/rejit.sh"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/readytorun/**"> <Issue>These tests are not supposed to be run with mono.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/DefaultInterfaceMethods/Emit/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/DefaultInterfaceMethods/InvokeConsumer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/Modifiers/modifiers/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/SetValue/TrySetReadonlyStaticField/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/reflection/SetValue/TrySetReadonlyStaticField2/**"> <Issue>https://github.com/dotnet/runtime/issues/37903</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/15241/genericcontext/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/15647/interfacestatics/**"> <Issue>https://github.com/dotnet/runtime/issues/34390</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/16123/ambiguousconstraint/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/16355/variance/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/20616/UnicodeBug/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Regressions/coreclr/22021/consumer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/tracing/eventpipe/gcdump/gcdump/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/tracing/eventpipe/providervalidation/**"> <Issue>https://github.com/dotnet/runtime/issues/59296</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/tracing/eventpipe/rundownvalidation/**"> <Issue>https://github.com/dotnet/runtime/issues/54801</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/DllImportAttribute/DllImportPath/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/Generics/GenericsTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/DllImportAttribute/ExactSpelling/ExactSpellingTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Stress/ABI/pinvokes_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Stress/ABI/pinvokes_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Stress/ABI/stubs_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Stress/ABI/tailcalls_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Stress/ABI/tailcalls_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/debugging/poisoning/poison/**"> <Issue>Tests coreclr JIT's debug poisoning of address taken variables</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/debugging/debuginfo/**"> <Issue>Tests coreclr JIT's debug info generation</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/DisabledRuntimeMarshalling/**"> <Issue>https://github.com/dotnet/runtime/issues/64127</Issue> </ExcludeList> </ItemGroup> <!-- Known failures for mono runtime on *all* architectures/operating systems in interpreter runtime mode --> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono' and '$(RuntimeVariant)' == 'monointerpreter' "> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeArray1/**"> <Issue>https://github.com/dotnet/runtime/issues/46622</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54867</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_ro/**"> <Issue>https://github.com/dotnet/runtime/issues/54867</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_21990/**"> <Issue>https://github.com/dotnet/runtime/issues/46622</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/zeroinit/tail/**"> <Issue>https://github.com/dotnet/runtime/issues/37955</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow04_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/u_fld_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/u_fld_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh07_large/**"> <Issue>https://github.com/dotnet/runtime/issues/54395</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/verif/sniff/fg/ver_fg_13/**"> <Issue>https://github.com/dotnet/runtime/issues/54396</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r4nanconv_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/Statics/Misc/LiteralStatic/**"> <Issue>https://github.com/dotnet/runtime/issues/54560</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b59952/b59952/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16499/b16499b/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31547/b31547/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b45541/b45541/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b65176/b65176/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b27883/b27883/**"> <Issue>https://github.com/dotnet/runtime/issues/54394</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b34953/b34953/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30862/b30862/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30869/b30869/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b70964/b70964/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b63726/b63726/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/volatilstind_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b60142/b60142/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b53980/b53980/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b47093/b47093/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r4nanconv_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b45956/b45956/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b25701/b25701/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/volatilstind_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30892/b30892/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/volatilstind/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b44879/b44879/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b27873/b27873/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b71179/b71179/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b37578/b37578/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b28597/b28597/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b71120/b71120/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/refany/indcall_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b32614/b32614/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b50027/b50027/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b35354/b35354/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_605447/DevDiv_605447/**"> <Issue>https://github.com/dotnet/runtime/issues/54391</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/V1.2-M02/b102844/b102844/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/u_conv_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/casts/coverage/castclass_calli_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_362706/DevDiv_362706/**"> <Issue>https://github.com/dotnet/runtime/issues/54391</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/V2.0-Beta2/b309576/b309576/**"> <Issue>https://github.com/dotnet/runtime/issues/54391</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_578214/DevDiv_578214/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/ptr_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfinally_ind_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/casts/coverage/castclass_calli_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/instftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/valftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_710234/DevDiv_710234/**"> <Issue>https://github.com/dotnet/runtime/issues/54381</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfinally_ind_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-RTM/b530694/b530694/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/deep/deep1_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/valftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/deep/deep1_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/instftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/flowgraph/dev10_bug679955/volatileLocal2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/virtftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/virtftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/ftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/ptr_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/ftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow02_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Dynamo/dynamo/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_24846/GitHub_24846/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/huge_filter_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54388</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/M00/b108366/b108366/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/huge_filter_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow03_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1.2-M01/b00722/b00722/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/tailcall_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Coverage/b39946/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_487699/DevDiv_487699/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/tailcall_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54388</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinclassconstructor_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/SIMD/VectorMatrix_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/strswitchfinal_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_405852/DevDiv_405852/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_544983/DevDiv_544983/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/Localloc_do/**"> <Issue>https://github.com/dotnet/runtime/issues/54359</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/Misc/function_pointer/MutualThdRecur-fptr/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinclassconstructor_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1.2-M01/b13452/b13452/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/div_r8/**"> <Issue>https://github.com/dotnet/runtime/issues/54375</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/deep/deep1_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/instftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/flowgraph/dev10_bug679955/volatileLocal2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/virtftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/virtftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/ftn_t_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/ELEMENT_TYPE_IU/ptr_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/fptr/ftn_t_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow02_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Dynamo/dynamo/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/huge_filter_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/huge_filter_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54388</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow03_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/tailcall_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54388</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Coverage/b39946/**"> <Issue>https://github.com/dotnet/runtime/issues/54388</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/boxunbox/tailcall_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinclassconstructor_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/strswitchfinal_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_large/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/nstructresur/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/finalnstruct/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/strswitchfinal_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/strswitchfinal_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizearray/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow01_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b353858/b353858/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/SIMD/VectorMatrix_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/strswitchfinal_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/Localloc_do/**"> <Issue>https://github.com/dotnet/runtime/issues/54359</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/Misc/function_pointer/MutualThdRecur-fptr/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinclassconstructor_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_small/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/DefaultInterfaceMethods/diamondshape/diamondshape_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54399</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_dynamic/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/Localloc_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54359</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/Localloc_ro/**"> <Issue>https://github.com/dotnet/runtime/issues/54359</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/neg_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/Localloc_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54359</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b25459/b25459/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/zeroinit/init_struct/**"> <Issue>https://github.com/dotnet/runtime/issues/54373</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinclassconstructor_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/pinvoke/tail/**"> <Issue>https://github.com/dotnet/runtime/issues/54373</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b39946/b39946/**"> <Issue>https://github.com/dotnet/runtime/issues/54393</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/varargs/varargsupport/**"> <Issue>https://github.com/dotnet/runtime/issues/54401</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/varargs/varargsupport_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54401</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/M00/b109878/b109878/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/add_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/M00/b92726/b92726/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/DefaultInterfaceMethods/diamondshape/diamondshape_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54399</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/volatilldind_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/mul_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b84909/b84909/**"> <Issue>https://github.com/dotnet/runtime/issues/54392</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/volatilldind_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/rem_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/ckfinite_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/div_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/sub_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/ldc_ckfinite_r4/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/volatilldind/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/opt/rngchk/RngchkStress3/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Burgers/Burgers/**"> <Issue>https://github.com/dotnet/runtime/issues/54358</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/DelegatePInvoke/DelegatePInvokeTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinfilter_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/47624</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/basics/throwinfilter_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/47624</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)JIT/IL_Conformance/Old/Base/ckfinite/**"> <Issue>https://github.com/dotnet/runtime/issues/54376</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_64125/Runtime_64125/**"> <Issue>needs triage</Issue> </ExcludeList> <!-- End interpreter issues --> </ItemGroup> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono' and '$(RuntimeVariant)' == 'llvmaot' "> <ExcludeList Include = "$(XunitTestBinBase)JIT/Methodical/ELEMENT_TYPE_IU/u_conv_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/nullabletypes/isinstvaluetype_do/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Generics/Instantiation/Structs/struct01/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/opt/cse/HugeArray1/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Dynamo/dynamo/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/Finalizer/finalizeother/finalizearray/**"> <Issue>https://github.com/dotnet/runtime/issues/54113</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventactivityidcontrol/eventactivityidcontrol/**"> <Issue>needs triage</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono' and '$(RuntimeVariant)' == 'llvmfullaot' "> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case1/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case11/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case12/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case14/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case15/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case3/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case4/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case5/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case6/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case7/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case8/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case9/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/NestedStructs/case03/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/NestedStructs/case04/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/NestedStructs/case05/**"> <Issue>expected failure: overlapped structs fail at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/RefFields/Validate/**"> <Issue>expected failure: unsupported type with ref field fails at AOT compile time, not runtime</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/SuppressGCTransition/SuppressGCTransitionTest/**"> <Issue>https://github.com/dotnet/runtime/issues/57361</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest/**"> <Issue>https://github.com/dotnet/runtime/issues/57362</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/CdeclMemberFunction/CdeclMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/57361</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/PlatformDefaultMemberFunction/PlatformDefaultMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/57361</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/StdCallMemberFunction/StdCallMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/57361</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/ThisCall/ThisCallTest/*"> <Issue>https://github.com/dotnet/runtime/issues/57361</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57369</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57369</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)JIT/Methodical/ELEMENT_TYPE_IU/u_conv_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57369</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/DelegatePInvoke/DelegatePInvokeTest/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Vector2_3_4/Vector2_3_4/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/HandleRef/HandleRefTest/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/badendfinally/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/badendfinally*/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/ceeillegal/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/coverage/importer/Desktop/ceeillegal*/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/pinvoke/tail/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/perffix/primitivevt/callconv3_il_*/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/zeroinit/tail/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/deep_*_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/deep_*_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumps2_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumper4_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumper5_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumps2_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_small/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_large/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/localloc/verify/verify01_dynamic/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/misc/tailjump_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Boxing/misc/tailjump_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfinally_*_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfault_*_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfinally_*_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/SEH/catchfault_jmp_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/Invoke/25params/25paramMixed_*/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25020/GitHub_25020/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25027/GitHub_25027/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1.2-M01/b13452/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/WPF_3226/CSharpRepro/WPF_3226/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b353858/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_23861/GitHub_23861/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_279829/DevDiv_279829/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/verif/sniff/fg/ver_fg_13/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/localloc/call/call05_dynamic/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/ReturnTypeValidation/OverrideSameSigAsDecl/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/DictionaryExpansion/DictionaryExpansion/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/Regressions/ASURT/ASURT150271/test13/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/Statics/Misc/LiteralStatic/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/MethodImpl/generics_override1/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/UnitTest/UnitTest_GVM/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/ReturnTypeValidation/ImplicitOverrideSameSigAsDecl/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Regressions/coreclr/16354/notimplemented/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Serialize/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Deserialize/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_r*/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport/*"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/baseservices/varargs/varargsupport_r/*"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/TieredVtableMethodTests/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case2/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/localloc/ehverify/eh07_large/**"> <Issue>llvmfullaot: EH problem</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Exceptions/ForeignThread/ForeignThreadExceptions/**"> <Issue>llvmfullaot: EH problem</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/nullabletypes/Desktop/boxunboxvaluetype_*/**"> <Issue>https://github.com/dotnet/runtime/issues/57353</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/nullabletypes/castclassvaluetype_*/**"> <Issue>https://github.com/dotnet/runtime/issues/57353</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Roslyn/CscBench/**"> <Issue>https://github.com/dotnet/runtime/issues/57352</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/opt/virtualstubdispatch/bigvtbl/bigvtbl_cs*/**"> <Issue>https://github.com/dotnet/runtime/issues/57352</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256_1/**"> <Issue>https://github.com/dotnet/runtime/issues/57352</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/DefaultInterfaceMethods/constrainedcall/constrained2_gm/**"> <Issue>https://github.com/dotnet/runtime/issues/57512</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/DisabledRuntimeMarshalling/DisabledRuntimeMarshalling_Disabled_NativeAssemblyEnabled/**"> <Issue>This test includes an intentionally-invalid UnmanagedCallersOnly method. Invalid UnmanagedCallersOnly methods cause failures at AOT-time.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/HardwareIntrinsics/Arm/ArmBase/Yield_*/**"> <Issue>https://github.com/dotnet/runtime/issues/64179</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono' and ('$(RuntimeVariant)' == 'llvmfullaot' or '$(RuntimeVariant)' == 'llvmaot')"> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1.1-M1-Beta1/b143840/b143840/*"> <Issue>https://github.com/dotnet/runtime/issues/48914</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/eventsourceerror/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverseouter/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/bigevent/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/buffersize/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/complus_config/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/diagnosticport/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/eventsvalidation/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/pauseonstart/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processenvironment/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processinfo/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processinfo2/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/providervalidation/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverse/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/rundownvalidation/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/MonoAPI/MonoMono/Thunks/**"> <Issue>Test not expected to work with AOT</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition="'$(RuntimeFlavor)' == 'mono' and ('$(RuntimeVariant)' == 'llvmfullaot' or '$(RuntimeVariant)' == 'llvmaot') and '$(TargetArchitecture)' == 'arm64'"> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/MethodImpl/CovariantReturns/UnitTest/UnitTestMultiModule/**"> <Issue>https://github.com/dotnet/runtime/issues/57371</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case2/**"> <Issue>https://github.com/dotnet/runtime/issues/57350</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" '$(RuntimeFlavor)' == 'mono' and '$(TargetArchitecture)' == 'arm64' and '$(TargetsWindows)' != 'true' " > <ExcludeList Include="$(XunitTestBinBase)/baseservices/typeequivalence/simple/Simple/**"> <Issue>Doesn't compile with LLVM AOT.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/Variance/IL/Unbox002/**"> <Issue>Doesn't compile with LLVM AOT.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/Variance/IL/Unbox003/**"> <Issue>Doesn't compile with LLVM AOT.</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Loader/classloader/generics/Variance/IL/vsw543506/**"> <Issue>Doesn't compile with LLVM AOT.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/finallyexec/loopinfinally_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b44657/b44657/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b63726/b63726/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b60142/b60142/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_487699/DevDiv_487699/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r8nanconv_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/flowgraph/dev10_bug679955/volatileLocal2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r8nanconv_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b36302/b36302/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r4nanconv_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r4nanconv_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b53980/b53980/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_mutual_rec_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b27873/b27873/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b53994/b53994/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_406156/DevDiv_406156/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_370233/DevDiv_370233/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b73207/b73207/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_switch_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b25701/b25701/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b50027/b50027/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b34953/b34953/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30892/b30892/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_switch_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b32614/b32614/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b82247/b82247/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b59952/b59952/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b49435/b49435/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_mutual_rec_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b30862/b30862/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b45541/b45541/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b71003/b71003/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b31547/b31547/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b45956/b45956/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/div_r8/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow02_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Base/ckfinite/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/div_r4/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/rtchecks/overflow/overflow01_div/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Directed/StructABI/StructABI/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/M00/b108366/b108366/**"> <Issue>needs triage</Issue> </ExcludeList> </ItemGroup> <!-- These are known failures on mono-arm64 in the interpreter runtime variant --> <ItemGroup Condition=" '$(RuntimeFlavor)' == 'mono' and ('$(TargetArchitecture)' == 'arm64') and '$(TargetsWindows)' != 'true' and '$(RuntimeVariant)' == 'monointerpreter' " > <!-- The following issues only effect the Mono interpreter; there is currently no way to exclude based on that scenario --> <ExcludeList Include = "$(XunitTestBinBase)JIT/IL_Conformance/Old/Base/ckfinite/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/pauseonstart/**"> <Issue> needs triage </Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" '$(TargetArchitecture)' == 'wasm' " > <ExcludeList Include="$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54867</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Intrinsics/TypeIntrinsics_ro/**"> <Issue>https://github.com/dotnet/runtime/issues/54867</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector256_1/**"> <Issue>https://github.com/dotnet/runtime/issues/54122</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/HardwareIntrinsics/General/Vector128_1/**"> <Issue>https://github.com/dotnet/runtime/issues/54122</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/threading/DeadThreads/DeadThreads/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/threading/coverage/OSThreadId/osthreadid/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackStressTest_TargetUnix/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/API/NativeLibraryTests/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackTests/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/ICustomMarshaler/ConflictingNames/SameNameDifferentAssembly/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/HandleRef/HandleRefTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/MultipleAssembliesWithSamePInvoke/MAWSPITest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Pointer/NonBlittablePointer/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Vector2_3_4/Vector2_3_4/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/RuntimeHandles/RuntimeHandlesTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Int/PInvokeIntTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/PInvoke/SetLastError/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/SuppressGCTransition/SuppressGCTransitionTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallConv/UnmanagedCallConvTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest/**"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/LocallocLarge_d/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/LocallocLarge_do/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/LocallocLarge_ro/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CodeGenBringUpTests/LocallocLarge_r/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/ThisCall/ThisCallTest/*"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/StdCallMemberFunction/StdCallMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/PlatformDefaultMemberFunction/PlatformDefaultMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/CdeclMemberFunction/CdeclMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/41519</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CircularCctors/CircularCctorFourThreadsBFI/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/TypeInitialization/CoreCLR/CircularCctorThreeThreads03/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Loader/classloader/regressions/523654/test532654_b/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/opt/rngchk/ArrayWithThread_o/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/opt/cse/VolatileTest_op_mul/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/conv_ovf_r8_i/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/ldc_conv_ovf_r8_i/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/switchinfinally_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/switchinfinally_ro/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/switchinfinally_do/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/eh/interactions/switchinfinally_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/cctor/misc/threads1_cs_do/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b99969/b99969/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumps4_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/VT/callconv/jumps4_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r8nanconv_il_d/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/NaN/r8nanconv_il_r/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/gc_poll/InsertGCPoll/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_40444/Runtime_40444/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b426654/b426654/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/VS-ia64-JIT/V1.2-M01/b10827/b10827/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V2.0-Beta2/b425314/b425314/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_27924/GitHub_27924/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlbigleakthd/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinkgen/**"> <Issue>https://github.com/dotnet/runtime/issues/56804</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlcollect/**"> <Issue>https://github.com/dotnet/runtime/issues/56804</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CheckProjects/CheckProjects/**"> <Issue>https://github.com/dotnet/runtime/issues/41520</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/mandelbrot/mandelbrot-2/**"> <Issue>https://github.com/dotnet/runtime/issues/56814</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/spectralnorm/spectralnorm-3/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/binarytrees/binarytrees-5/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/binarytrees/binarytrees-6/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fasta/fasta-1/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/mandelbrot/mandelbrot-7/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Regressions/v2.0-beta2/452950/452950/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Stress/Framework/ReliabilityFramework/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/plug/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit-finalize/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit-threaded/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/LOHCompaction/lohcompactapi/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit_1/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/dlstack/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/THDChaos/thdchaos/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinkstay/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/FinalNStruct/nstructtun/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/BinTree/thdtreegrowingobj/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/DoublinkList/doublinknoleak2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/ServerModel/servermodel/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/THDList/thdlist/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/BinTree/thdtreelivingobj/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/NDPin/ndpinfinal/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Resurrection/continue/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/BinTree/thdtree/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/FinalizeTimeout/FinalizeTimeout/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/NoGCRegion/NoGC/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_3/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs_1/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/LargeMemory/API/gc/gettotalmemory/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Coverage/LargeObjectAlloc/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Coverage/LargeObjectAlloc2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventactivityidcontrol/eventactivityidcontrol/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/eventsourceerror/**"> <Issue> needs triage </Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Exceptions/ForeignThread/ForeignThreadExceptions/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/PortablePdb/IlasmPortablePdbTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/System/Runtime/CompilerServices/MethodImplOptionsTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/opt/Devirtualization/box2/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-6/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/ConsoleMandel/ConsoleMandel/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-1/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/RunBenchmarks/RunBenchmarks/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Roslyn/CscBench/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Span/Indexer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Bytemark/Bytemark/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fannkuch-redux/fannkuch-redux-2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/regex-redux/regex-redux-5/**"> <Issue>https://github.com/dotnet/runtime/issues/41472</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/RayTracer/RayTracer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_64125/Runtime_64125/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/JIT/Regression/JitBlue/Runtime_64883/Runtime_64883/*"> <Issue>Loads an assembly from file</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/incrementingeventcounter/**"> <Issue>System.Threading.Thread.UnsafeStart not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/eventcounter/**"> <Issue>System.Threading.Thread.UnsafeStart not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/runtimecounters/**"> <Issue>System.Threading.Thread.UnsafeStart not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/incrementingpollingcounter/**"> <Issue>System.Threading.Thread.UnsafeStart not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/pollingcounter/**"> <Issue>System.Threading.Thread.UnsafeStart not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventcounter/gh53564/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverse/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/bigevent/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient and system.diagnostics.process not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processinfo2/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient and system.diagnostics.process not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/diagnosticport/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processinfo/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient and system.diagnostics.process not supported</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/buffersize/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverseouter/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processenvironment/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/pauseonstart/**"> <Issue>Could not load legacy Microsoft.Diagnostics.Tools.RuntimeClient</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" $(TargetOS) == 'Android' " > <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/**"> <Issue>No crossgen folder under Core_Root</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Exceptions/ForeignThread/ForeignThreadExceptions/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_3/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_2/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs_1/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/System/Runtime/CompilerServices/MethodImplOptionsTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/ICustomMarshaler/ConflictingNames/SameNameDifferentAssembly/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackTests/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Vector2_3_4/Vector2_3_4/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/MultipleAssembliesWithSamePInvoke/MAWSPITest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Int/PInvokeIntTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Pointer/NonBlittablePointer/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/SetLastError/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/SuppressGCTransition/SuppressGCTransitionTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/RuntimeHandles/RuntimeHandlesTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/HandleRef/HandleRefTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CheckProjects/CheckProjects/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/ThisCall/ThisCallTest/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/StdCallMemberFunction/StdCallMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/PlatformDefaultMemberFunction/PlatformDefaultMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/CdeclMemberFunction/CdeclMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/eh/basics/throwinfinallyintryfilter2/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/jit64/hfa/main/testC/hfa_nd1C_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/LargeMemory/API/gc/gettotalmemory/**"> <Issue>https://github.com/dotnet/runtime/issues/54913</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/PortablePdb/IlasmPortablePdbTests/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/API/NativeLibraryTests/**"> <Issue>https://github.com/dotnet/runtime/issues/54905</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackStressTest_TargetUnix/**"> <Issue>https://github.com/dotnet/runtime/issues/54905</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/switch/switch5/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_void_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/recurse_ep_void_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/recurse_ep_void_il_r/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/switch/switch6/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/tailcall/test_void_il_d/**"> <Issue>https://github.com/dotnet/runtime/issues/54911</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-6/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Deserialize/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Span/SpanBench/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Span/Indexer/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/SeekUnroll/SeekUnroll/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Roslyn/CscBench/**"> <Issue>https://github.com/dotnet/runtime/issues/54908</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Serialize/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25468/GitHub_25468/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_36614/GitHub_36614/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/readytorun/multifolder/multifolder/**"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Features/HeapExpansion/bestfit-finalize/*"> <Issue>https://github.com/dotnet/runtime/issues/44643</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Regressions/v2.0-rtm/494226/494226/*"> <Issue>https://github.com/dotnet/runtime/issues/44643</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/ServerModel/servermodel/*"> <Issue>https://github.com/dotnet/runtime/issues/44643</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/gc_poll/InsertGCPoll/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/V8/Crypto/Crypto/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fasta/fasta-1/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/regex-redux/regex-redux-5/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/RayTracer/RayTracer/**"> <Issue>https://github.com/dotnet/runtime/issues/54906</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/complus_config/name_config_with_pid/**"> <Issue>https://github.com/dotnet/runtime/issues/54974</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallConv/UnmanagedCallConvTest/**"> <Issue>https://github.com/dotnet/runtime/issues/53077</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Dynamo/dynamo/**"> <Issue>https://github.com/dotnet/runtime/issues/53350</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/DelegatePInvoke/DelegatePInvokeTest/**"> <Issue>https://github.com/dotnet/runtime/issues/53351</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/**"> <Issue>https://github.com/dotnet/runtime/issues/53353</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/diagnosticport/**"> <Issue>Cannot run multiple apps on Android for subprocesses</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/pauseonstart/**"> <Issue>Cannot run multiple apps on Android for subprocesses</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/processenvironment/**"> <Issue>Cannot run multiple apps on Android for subprocesses</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverse/**"> <Issue>Cannot run multiple apps on Android for subprocesses</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/reverseouter/**"> <Issue>Cannot run multiple apps on Android for subprocesses</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" $(TargetOS) == 'Android' And '$(TargetArchitecture)' == 'arm64' " > <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fannkuch-redux/fannkuch-redux-5/**"> <Issue>https://github.com/dotnet/runtime/issues/52781</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" $(TargetOS) == 'Android' And '$(RuntimeVariant)' == 'monointerpreter' " > <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/mandelbrot/mandelbrot-7/**"> <Issue>https://github.com/dotnet/runtime/issues/55528</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" $(TargetOS) == 'iOSSimulator' " > <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/MultipleAssembliesWithSamePInvoke/MAWSPITest/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/RuntimeHandles/RuntimeHandlesTest/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Pointer/NonBlittablePointer/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Vector2_3_4/Vector2_3_4/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Primitives/Int/PInvokeIntTest/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Miscellaneous/HandleRef/HandleRefTest/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/ICustomMarshaler/ConflictingNames/SameNameDifferentAssembly/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/Attributes/SuppressGCTransition/SuppressGCTransitionTest/**"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/API/NativeLibraryTests/**"> <Issue>System.PlatformNotSupportedException: Operation is not supported on this platform</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackStressTest_TargetUnix/**"> <Issue>System.DllNotFoundException: DoesNotExist</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/NativeLibrary/Callback/CallbackTests/**"> <Issue>System.DllNotFoundException: DoesNotExist</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest/**"> <Issue>System.DllNotFoundException: UnmanagedCallersOnlyDll</Issue> </ExcludeList> <ExcludeList Include="$(XunitTestBinBase)/Interop/ObjectiveC/AutoReleaseTest/**"> <Issue>System.DllNotFoundException: ObjectiveC</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/SuppressGCTransition/SuppressGCTransitionTest/**"> <Issue>System.DllNotFoundException: SuppressGCTransitionNative</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_36614/GitHub_36614/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.assert, Version=2.4.1.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Methodical/gc_poll/InsertGCPoll/**"> <Issue>System.DllNotFoundException: GCPollNative</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/complus_config/name_config_with_pid/**"> <Issue>System.ArgumentNullException: Value cannot be null. (Parameter 'path1')</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/readytorun/multifolder/multifolder/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly '/.../Library/Developer/CoreSimulator/Devices/941235AB-7563-4D79-AC28-946B7AD2304A/data/Containers/Bundle/Application/40176A30-D8F5-4497-958A-6514E5C684FC/readytorun_multifolder.app/testdir-multifolder/../FolderA/FolderA/FolderA.dll' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Exceptions/ForeignThread/ForeignThreadExceptions/**"> <Issue>Failed to catch an exception! System.DllNotFoundException: ForeignThreadExceptionsNative</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs/**"> <Issue>USAGE: MultipleWR.exe num objects [track]</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/WeakReference/multipleWRs_1/**"> <Issue>USAGE: MultipleWR.exe num objects [track]</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_2/**"> <Issue>GC_API 0|1|2</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/API/GC/Collect_Optimized_3/**"> <Issue>GC_API 0|1|2</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/PortablePdb/IlasmPortablePdbTests/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.runner.utility.netcoreapp10, Version=2.4.1.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/ilasm/System/Runtime/CompilerServices/MethodImplOptionsTests/**"> <Issue>Environment variable is not set: 'CORE_ROOT'</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/LargeMemory/API/gc/gettotalmemory/**"> <Issue>System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/ThisCall/ThisCallTest/*"> <Issue>System.DllNotFoundException: ThisCallNative</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/StdCallMemberFunction/StdCallMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/PlatformDefaultMemberFunction/PlatformDefaultMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include="$(XUnitTestBinBase)/JIT/Directed/callconv/CdeclMemberFunction/CdeclMemberFunctionTest/*"> <Issue>https://github.com/dotnet/runtime/issues/50440</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Span/SpanBench/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Serialize/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fasta/fasta-1/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/regex-redux/regex-redux-5/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/RayTracer/RayTracer/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/V8/Crypto/Crypto/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Roslyn/CscBench/**"> <Issue>This test requires CORE_ROOT to be set</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/fannkuch-redux/fannkuch-redux-5/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/SIMD/SeekUnroll/SeekUnroll/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.assert, Version=2.4.1.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/reverse-complement/reverse-complement-6/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/BenchmarksGame/k-nucleotide/k-nucleotide-9/**"> <Issue>((null) error) * Assertion at runtime/src/mono/mono/metadata/assembly.c:2049, condition `is_ok (error)' not met, function:mono_assembly_load_friends, Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Serialization/Deserialize/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Performance/CodeQuality/Span/Indexer/**"> <Issue>System.IO.FileNotFoundException: Could not load file or assembly 'xunit.performance.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=67066efe964d3b03' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/CheckProjects/CheckProjects/*"> <Issue>CORE_ROOT must be set</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/GitHub_25468/GitHub_25468/**"> <Issue>Could not load file or assembly 'System.Drawing.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies.</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/JitBlue/DevDiv_461649/DevDiv_461649/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/PInvoke/SetLastError/SetLastErrorTest/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/UnmanagedCallConv/UnmanagedCallConvTest/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/Interop/StructMarshalling/ReversePInvoke/MarshalSeqStruct/DelegatePInvoke/DelegatePInvokeTest/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/tracing/eventpipe/eventsourceerror/eventsourceerror/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/IL_Conformance/Old/Conformance_Base/mul_ovf_u2/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b41126/b41126/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/GC/Scenarios/Dynamo/dynamo/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_DefaultMode_R2r/*"> <Issue>needs triage</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_DefaultMode_R2r/*"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_QuickJitForLoopsOff_R2r/*"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_QuickJitForLoopsOn_R2r/*"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_QuickJitOff_R2r/*"> <Issue>missing assembly</Issue> </ExcludeList> <ExcludeList Include = "$(XunitTestBinBase)/baseservices/TieredCompilation/BasicTest_QuickJitOn_R2r/*"> <Issue>missing assembly</Issue> </ExcludeList> </ItemGroup> <ItemGroup Condition=" '$(TargetArchitecture)' == 'wasm' or ('$(TargetOS)' == 'Android' or '$(TargetOS)' == 'iOSSimulator')"> <ExcludeList Include="$(XunitTestBinBase)/Interop/MonoAPI/**"> <Issue>mobile and wasm don't support tests with native libraries. wasm also needs static linking</Issue> </ExcludeList> </ItemGroup> </Project>
1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ErrorWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; namespace System.Runtime.InteropServices { // Wrapper that is converted to a variant with VT_ERROR. [EditorBrowsable(EditorBrowsableState.Never)] public sealed class ErrorWrapper { public ErrorWrapper(int errorCode) { ErrorCode = errorCode; } public ErrorWrapper(object errorCode) { if (!(errorCode is int)) throw new ArgumentException(SR.Arg_MustBeInt32, nameof(errorCode)); ErrorCode = (int)errorCode; } public ErrorWrapper(Exception e) { ErrorCode = Marshal.GetHRForException(e); } public int ErrorCode { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; namespace System.Runtime.InteropServices { // Wrapper that is converted to a variant with VT_ERROR. [EditorBrowsable(EditorBrowsableState.Never)] public sealed class ErrorWrapper { public ErrorWrapper(int errorCode) { ErrorCode = errorCode; } public ErrorWrapper(object errorCode) { if (!(errorCode is int)) throw new ArgumentException(SR.Arg_MustBeInt32, nameof(errorCode)); ErrorCode = (int)errorCode; } public ErrorWrapper(Exception e) { ErrorCode = Marshal.GetHRForException(e); } public int ErrorCode { get; } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Directed/coverage/oldtests/33objref_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="33objref.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="33objref.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/Interop/StructMarshalling/PInvoke/Struct.cs
using System; using System.Runtime.InteropServices; public class Common { public const int NumArrElements = 2; } //////////////////////////////struct definition/////////////////////////// [StructLayout(LayoutKind.Sequential)] public struct InnerSequential { public int f1; public float f2; public String f3; } [StructLayout(LayoutKind.Sequential)] struct IntWithInnerSequential { public int i1; public InnerSequential sequential; } [StructLayout(LayoutKind.Sequential)] struct SequentialWrapper { public InnerSequential sequential; } [StructLayout(LayoutKind.Sequential)] struct SequentialDoubleWrapper { public SequentialWrapper wrapper; } [StructLayout(LayoutKind.Sequential)] struct AggregateSequentialWrapper { public SequentialWrapper wrapper1; public InnerSequential sequential; public SequentialWrapper wrapper2; } [StructLayout(LayoutKind.Sequential)] public struct ComplexStruct { public int i; [MarshalAs(UnmanagedType.I1)] public bool b; [MarshalAs(UnmanagedType.LPStr)] public string str; public IntPtr pedding; public ScriptParamType type; } [StructLayout(LayoutKind.Explicit)] public struct ScriptParamType { [FieldOffset(0)] public int idata; [FieldOffset(8)] public bool bdata; [FieldOffset(8)] public double ddata; [FieldOffset(8)] public IntPtr ptrdata; } [StructLayout(LayoutKind.Explicit)] public struct INNER2 { [FieldOffset(0)] public int f1; [FieldOffset(4)] public float f2; [FieldOffset(8)] public String f3; } [StructLayout(LayoutKind.Explicit)] public struct InnerExplicit { [FieldOffset(0)] public int f1; [FieldOffset(0)] public float f2; [FieldOffset(8)] public String f3; } [StructLayout(LayoutKind.Sequential)]//struct containing one field of array type public struct InnerArraySequential { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Common.NumArrElements)] public InnerSequential[] arr; } [StructLayout(LayoutKind.Explicit, Pack = 8)] public struct InnerArrayExplicit { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Common.NumArrElements)] public InnerSequential[] arr; [FieldOffset(8)] public string f4; } [StructLayout(LayoutKind.Explicit)] public struct OUTER3 { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Common.NumArrElements)] public InnerSequential[] arr; [FieldOffset(24)] public string f4; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CharSetAnsiSequential { public string f1; public char f2; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct CharSetUnicodeSequential { public string f1; public char f2; } [StructLayout(LayoutKind.Sequential)] public struct NumberSequential { public Int64 i64; public UInt64 ui64; public Double d; public int i32; public uint ui32; public short s1; public ushort us1; public Int16 i16; public UInt16 ui16; public Single sgl; public Byte b; public SByte sb; } [StructLayout(LayoutKind.Sequential)] public struct S3 { public bool flag; [MarshalAs(UnmanagedType.LPStr)] public string str; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public int[] vals; } [StructLayout(LayoutKind.Sequential)] public struct S4 { public int age; public string name; } public enum Enum1 { e1 = 1, e2 = 3 }; [StructLayout(LayoutKind.Sequential)] public struct S5 { public S4 s4; public Enum1 ef; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct StringStructSequentialAnsi { public string first; public string last; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct StringStructSequentialUnicode { public string first; public string last; } [StructLayout(LayoutKind.Sequential)] public struct S8 { public string name; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string fullName; public bool gender; [MarshalAs(UnmanagedType.Error)] public int i32; [MarshalAs(UnmanagedType.Error)] public uint ui32; [MarshalAs(UnmanagedType.U2)] public UInt16 jobNum; [MarshalAs(UnmanagedType.I1)] public sbyte mySByte; } public struct S9 { [MarshalAs(UnmanagedType.Error)] public int i32; public TestDelegate1 myDelegate1; } public delegate void TestDelegate1(S9 myStruct); [StructLayout(LayoutKind.Sequential)] public struct IntegerStructSequential { public int i; } [StructLayout(LayoutKind.Sequential)] public struct OuterIntegerStructSequential { public int i; public IntegerStructSequential s_int; } [StructLayout(LayoutKind.Sequential)] public struct IncludeOuterIntegerStructSequential { public OuterIntegerStructSequential s; } [StructLayout(LayoutKind.Sequential)] public unsafe struct S11 { public int* i32; public int i; } [StructLayout(LayoutKind.Explicit)] public struct U { [FieldOffset(0)] public int i32; [FieldOffset(0)] public uint ui32; [FieldOffset(0)] public IntPtr iPtr; [FieldOffset(0)] public UIntPtr uiPtr; [FieldOffset(0)] public short s; [FieldOffset(0)] public ushort us; [FieldOffset(0)] public Byte b; [FieldOffset(0)] public SByte sb; [FieldOffset(0)] public long l; [FieldOffset(0)] public ulong ul; [FieldOffset(0)] public float f; [FieldOffset(0)] public Double d; } [StructLayout(LayoutKind.Explicit, Size = 2)] public struct ByteStructPack2Explicit { [FieldOffset(0)] public byte b1; [FieldOffset(1)] public byte b2; } [StructLayout(LayoutKind.Explicit, Size = 4)] public struct ShortStructPack4Explicit { [FieldOffset(0)] public short s1; [FieldOffset(2)] public short s2; } [StructLayout(LayoutKind.Explicit, Size = 8)] public struct IntStructPack8Explicit { [FieldOffset(0)] public int i1; [FieldOffset(4)] public int i2; } [StructLayout(LayoutKind.Explicit, Size = 16)] public struct LongStructPack16Explicit { [FieldOffset(0)] public long l1; [FieldOffset(8)] public long l2; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct AutoString { public string str; } [StructLayout(LayoutKind.Sequential)] public struct HFA { public float f1; public float f2; public float f3; public float f4; } [StructLayout(LayoutKind.Explicit)] public struct ExplicitHFA { [FieldOffset(0)] public float f1; [FieldOffset(4)] public float f2; [FieldOffset(8)] public float f3; [FieldOffset(12)] public float f4; } [StructLayout(LayoutKind.Explicit)] public unsafe struct ExplicitFixedHFA { [FieldOffset(0)] public float f1; [FieldOffset(4)] public float f2; [FieldOffset(8)] public fixed float fs[2]; } [StructLayout(LayoutKind.Explicit)] public struct OverlappingHFA { [FieldOffset(0)] public HFA hfa; [FieldOffset(0)] public ExplicitHFA explicitHfa; [FieldOffset(0)] public ExplicitFixedHFA explicitFixedHfa; } [StructLayout(LayoutKind.Sequential)] public struct DoubleHFA { public double d1; public double d2; } [StructLayout(LayoutKind.Sequential)] public struct ManyInts { public int i1; public int i2; public int i3; public int i4; public int i5; public int i6; public int i7; public int i8; public int i9; public int i10; public int i11; public int i12; public int i13; public int i14; public int i15; public int i16; public int i17; public int i18; public int i19; public int i20; public System.Collections.Generic.IEnumerator<int> GetEnumerator() { yield return i1; yield return i2; yield return i3; yield return i4; yield return i5; yield return i6; yield return i7; yield return i8; yield return i9; yield return i10; yield return i11; yield return i12; yield return i13; yield return i14; yield return i15; yield return i16; yield return i17; yield return i18; yield return i19; yield return i20; } } [StructLayout(LayoutKind.Sequential)] public struct MultipleBool { public bool b1; public bool b2; } [StructLayout(LayoutKind.Explicit)] public struct OverlappingLongFloat { [FieldOffset(0)] public long l; [FieldOffset(4)] public float f; } [StructLayout(LayoutKind.Explicit)] public struct OverlappingLongFloat2 { [FieldOffset(4)] public float f; [FieldOffset(0)] public long l; } [StructLayout(LayoutKind.Explicit)] public struct OverlappingMultipleEightbyte { [FieldOffset(8)] public int i; [FieldOffset(0), MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] public float[] arr; } [StructLayout(LayoutKind.Sequential)] public unsafe struct FixedBufferClassificationTestBlittable { public fixed int arr[3]; public float f; } [StructLayout(LayoutKind.Sequential)] public unsafe struct FixedBufferClassificationTest { public fixed int arr[3]; public NonBlittableFloat f; } // A non-blittable wrapper for a float value. // Used to force a type with a float field to be non-blittable // and take a different code path. [StructLayout(LayoutKind.Sequential)] public struct NonBlittableFloat { public NonBlittableFloat(float f) { arr = new []{f}; } [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] private float[] arr; public float F => arr[0]; } public struct Int32Wrapper { public int i; } [StructLayout(LayoutKind.Sequential)] public unsafe struct FixedArrayClassificationTest { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] public Int32Wrapper[] arr; public float f; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct UnicodeCharArrayClassification { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] public char[] arr; public float f; } delegate int IntIntDelegate(int a); [StructLayout(LayoutKind.Sequential)] public struct DelegateFieldMarshaling { public Delegate IntIntFunction; } public struct Int32CLongStruct { public int i; public CLong l; }
using System; using System.Runtime.InteropServices; public class Common { public const int NumArrElements = 2; } //////////////////////////////struct definition/////////////////////////// [StructLayout(LayoutKind.Sequential)] public struct InnerSequential { public int f1; public float f2; public String f3; } [StructLayout(LayoutKind.Sequential)] struct IntWithInnerSequential { public int i1; public InnerSequential sequential; } [StructLayout(LayoutKind.Sequential)] struct SequentialWrapper { public InnerSequential sequential; } [StructLayout(LayoutKind.Sequential)] struct SequentialDoubleWrapper { public SequentialWrapper wrapper; } [StructLayout(LayoutKind.Sequential)] struct AggregateSequentialWrapper { public SequentialWrapper wrapper1; public InnerSequential sequential; public SequentialWrapper wrapper2; } [StructLayout(LayoutKind.Sequential)] public struct ComplexStruct { public int i; [MarshalAs(UnmanagedType.I1)] public bool b; [MarshalAs(UnmanagedType.LPStr)] public string str; public IntPtr pedding; public ScriptParamType type; } [StructLayout(LayoutKind.Explicit)] public struct ScriptParamType { [FieldOffset(0)] public int idata; [FieldOffset(8)] public bool bdata; [FieldOffset(8)] public double ddata; [FieldOffset(8)] public IntPtr ptrdata; } [StructLayout(LayoutKind.Explicit)] public struct INNER2 { [FieldOffset(0)] public int f1; [FieldOffset(4)] public float f2; [FieldOffset(8)] public String f3; } [StructLayout(LayoutKind.Explicit)] public struct InnerExplicit { [FieldOffset(0)] public int f1; [FieldOffset(0)] public float f2; [FieldOffset(8)] public String f3; } [StructLayout(LayoutKind.Sequential)]//struct containing one field of array type public struct InnerArraySequential { [MarshalAs(UnmanagedType.ByValArray, SizeConst = Common.NumArrElements)] public InnerSequential[] arr; } [StructLayout(LayoutKind.Explicit, Pack = 8)] public struct InnerArrayExplicit { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Common.NumArrElements)] public InnerSequential[] arr; [FieldOffset(8)] public string f4; } [StructLayout(LayoutKind.Explicit)] public struct OUTER3 { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Common.NumArrElements)] public InnerSequential[] arr; [FieldOffset(24)] public string f4; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CharSetAnsiSequential { public string f1; public char f2; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct CharSetUnicodeSequential { public string f1; public char f2; } [StructLayout(LayoutKind.Sequential)] public struct NumberSequential { public Int64 i64; public UInt64 ui64; public Double d; public int i32; public uint ui32; public short s1; public ushort us1; public Int16 i16; public UInt16 ui16; public Single sgl; public Byte b; public SByte sb; } [StructLayout(LayoutKind.Sequential)] public struct S3 { public bool flag; [MarshalAs(UnmanagedType.LPStr)] public string str; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public int[] vals; } [StructLayout(LayoutKind.Sequential)] public struct S4 { public int age; public string name; } public enum Enum1 { e1 = 1, e2 = 3 }; [StructLayout(LayoutKind.Sequential)] public struct S5 { public S4 s4; public Enum1 ef; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct StringStructSequentialAnsi { public string first; public string last; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct StringStructSequentialUnicode { public string first; public string last; } [StructLayout(LayoutKind.Sequential)] public struct S8 { public string name; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string fullName; public bool gender; [MarshalAs(UnmanagedType.Error)] public int i32; [MarshalAs(UnmanagedType.Error)] public uint ui32; [MarshalAs(UnmanagedType.U2)] public UInt16 jobNum; [MarshalAs(UnmanagedType.I1)] public sbyte mySByte; } public struct S9 { [MarshalAs(UnmanagedType.Error)] public int i32; public TestDelegate1 myDelegate1; } public delegate void TestDelegate1(S9 myStruct); [StructLayout(LayoutKind.Sequential)] public struct IntegerStructSequential { public int i; } [StructLayout(LayoutKind.Sequential)] public struct OuterIntegerStructSequential { public int i; public IntegerStructSequential s_int; } [StructLayout(LayoutKind.Sequential)] public struct IncludeOuterIntegerStructSequential { public OuterIntegerStructSequential s; } [StructLayout(LayoutKind.Sequential)] public unsafe struct S11 { public int* i32; public int i; } [StructLayout(LayoutKind.Explicit)] public struct U { [FieldOffset(0)] public int i32; [FieldOffset(0)] public uint ui32; [FieldOffset(0)] public IntPtr iPtr; [FieldOffset(0)] public UIntPtr uiPtr; [FieldOffset(0)] public short s; [FieldOffset(0)] public ushort us; [FieldOffset(0)] public Byte b; [FieldOffset(0)] public SByte sb; [FieldOffset(0)] public long l; [FieldOffset(0)] public ulong ul; [FieldOffset(0)] public float f; [FieldOffset(0)] public Double d; } [StructLayout(LayoutKind.Explicit, Size = 2)] public struct ByteStructPack2Explicit { [FieldOffset(0)] public byte b1; [FieldOffset(1)] public byte b2; } [StructLayout(LayoutKind.Explicit, Size = 4)] public struct ShortStructPack4Explicit { [FieldOffset(0)] public short s1; [FieldOffset(2)] public short s2; } [StructLayout(LayoutKind.Explicit, Size = 8)] public struct IntStructPack8Explicit { [FieldOffset(0)] public int i1; [FieldOffset(4)] public int i2; } [StructLayout(LayoutKind.Explicit, Size = 16)] public struct LongStructPack16Explicit { [FieldOffset(0)] public long l1; [FieldOffset(8)] public long l2; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct AutoString { public string str; } [StructLayout(LayoutKind.Sequential)] public struct HFA { public float f1; public float f2; public float f3; public float f4; } [StructLayout(LayoutKind.Explicit)] public struct ExplicitHFA { [FieldOffset(0)] public float f1; [FieldOffset(4)] public float f2; [FieldOffset(8)] public float f3; [FieldOffset(12)] public float f4; } [StructLayout(LayoutKind.Explicit)] public unsafe struct ExplicitFixedHFA { [FieldOffset(0)] public float f1; [FieldOffset(4)] public float f2; [FieldOffset(8)] public fixed float fs[2]; } [StructLayout(LayoutKind.Explicit)] public struct OverlappingHFA { [FieldOffset(0)] public HFA hfa; [FieldOffset(0)] public ExplicitHFA explicitHfa; [FieldOffset(0)] public ExplicitFixedHFA explicitFixedHfa; } [StructLayout(LayoutKind.Sequential)] public struct DoubleHFA { public double d1; public double d2; } [StructLayout(LayoutKind.Sequential)] public struct ManyInts { public int i1; public int i2; public int i3; public int i4; public int i5; public int i6; public int i7; public int i8; public int i9; public int i10; public int i11; public int i12; public int i13; public int i14; public int i15; public int i16; public int i17; public int i18; public int i19; public int i20; public System.Collections.Generic.IEnumerator<int> GetEnumerator() { yield return i1; yield return i2; yield return i3; yield return i4; yield return i5; yield return i6; yield return i7; yield return i8; yield return i9; yield return i10; yield return i11; yield return i12; yield return i13; yield return i14; yield return i15; yield return i16; yield return i17; yield return i18; yield return i19; yield return i20; } } [StructLayout(LayoutKind.Sequential)] public struct MultipleBool { public bool b1; public bool b2; } [StructLayout(LayoutKind.Explicit)] public struct OverlappingLongFloat { [FieldOffset(0)] public long l; [FieldOffset(4)] public float f; } [StructLayout(LayoutKind.Explicit)] public struct OverlappingLongFloat2 { [FieldOffset(4)] public float f; [FieldOffset(0)] public long l; } [StructLayout(LayoutKind.Explicit)] public struct OverlappingMultipleEightbyte { [FieldOffset(8)] public int i; [FieldOffset(0), MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] public float[] arr; } [StructLayout(LayoutKind.Sequential)] public unsafe struct FixedBufferClassificationTestBlittable { public fixed int arr[3]; public float f; } [StructLayout(LayoutKind.Sequential)] public unsafe struct FixedBufferClassificationTest { public fixed int arr[3]; public NonBlittableFloat f; } // A non-blittable wrapper for a float value. // Used to force a type with a float field to be non-blittable // and take a different code path. [StructLayout(LayoutKind.Sequential)] public struct NonBlittableFloat { public NonBlittableFloat(float f) { arr = new []{f}; } [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] private float[] arr; public float F => arr[0]; } public struct Int32Wrapper { public int i; } [StructLayout(LayoutKind.Sequential)] public unsafe struct FixedArrayClassificationTest { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] public Int32Wrapper[] arr; public float f; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct UnicodeCharArrayClassification { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] public char[] arr; public float f; } delegate int IntIntDelegate(int a); [StructLayout(LayoutKind.Sequential)] public struct DelegateFieldMarshaling { public Delegate IntIntFunction; } public struct Int32CLongStruct { public int i; public CLong l; }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/baseservices/threading/generics/Monitor/EnterExit03.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="EnterExit03.cs" /> <Compile Include="MonitorHelper.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="EnterExit03.cs" /> <Compile Include="MonitorHelper.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/CodeGenBringUpTests/IntArraySum.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; using System.Runtime.CompilerServices; public class BringUpTest_IntArraySum { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static int IntArraySum(int []a, int n) { int sum = 0; for (int i = 0; i < n; ++i) sum += a[i]; return sum; } public static int Main() { int [] a = new int[5] {1, 2, 3, 4, 5}; int result = IntArraySum(a, a.Length); if (result == 15) return Pass; return Fail; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; using System.Runtime.CompilerServices; public class BringUpTest_IntArraySum { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static int IntArraySum(int []a, int n) { int sum = 0; for (int i = 0; i < n; ++i) sum += a[i]; return sum; } public static int Main() { int [] a = new int[5] {1, 2, 3, 4, 5}; int result = IntArraySum(a, a.Length); if (result == 15) return Pass; return Fail; } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/mono/mono/tests/test-lldb.cs
using System; using System.Threading; using System.Runtime.CompilerServices; public class Tests { public static void Main () { // Keep this at test-lldb.cs:9 Console.WriteLine ("Hello"); Thread.Sleep (100000); } }
using System; using System.Threading; using System.Runtime.CompilerServices; public class Tests { public static void Main () { // Keep this at test-lldb.cs:9 Console.WriteLine ("Hello"); Thread.Sleep (100000); } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/X86/Avx1/HorizontalAdd.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; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Avx.IsSupported) { using (TestTable<float> floatTable = new TestTable<float>(new float[8] {22, -1, -50, 0, 22, -1, -50, 0 }, new float[8] { 22, -1, -50, 0, 22, -1, -50, 0 }, new float[8])) using (TestTable<double> doubleTable = new TestTable<double>(new double[4] { 1, -5, 100, 0 }, new double[4] { 22, -1, -50, 0 }, new double[4])) { var vf1 = Unsafe.Read<Vector256<float>>(floatTable.inArray1Ptr); var vf2 = Unsafe.Read<Vector256<float>>(floatTable.inArray2Ptr); var vf3 = Avx.HorizontalAdd(vf1, vf2); Unsafe.Write(floatTable.outArrayPtr, vf3); if (!floatTable.CheckResult((left, right, result) => (left[0] + left[1] == result[0]) && (right[0] + right[1] == result[2]) && (left[2] + left[3] == result[1]) && (right[2] + right[3] == result[3]) && (left[4] + left[5] == result[4]) && (right[4] + right[5] == result[6]) && (left[6] + left[7] == result[5]) && (right[6] + right[7] == result[7]))) { Console.WriteLine("Avx HorizontalAdd failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } var vd1 = Unsafe.Read<Vector256<double>>(doubleTable.inArray1Ptr); var vd2 = Unsafe.Read<Vector256<double>>(doubleTable.inArray2Ptr); var vd3 = Avx.HorizontalAdd(vd1, vd2); Unsafe.Write(doubleTable.outArrayPtr, vd3); if (!doubleTable.CheckResult((left, right, result) => (left[0] + left[1] == result[0]) && (right[0] + right[1] == result[1]) && (left[2] + left[3] == result[2]) && (right[2] + right[3] == result[3]))) { Console.WriteLine("Avx HorizontalAdd failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray1; public T[] inArray2; public T[] outArray; public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer(); public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle1; GCHandle inHandle2; GCHandle outHandle; public TestTable(T[] a, T[] b, T[] c) { this.inArray1 = a; this.inArray2 = b; this.outArray = c; inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned); inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T[], T[], T[], bool> check) { return check(inArray1, inArray2, outArray); } public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } } } }
// 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; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Avx.IsSupported) { using (TestTable<float> floatTable = new TestTable<float>(new float[8] {22, -1, -50, 0, 22, -1, -50, 0 }, new float[8] { 22, -1, -50, 0, 22, -1, -50, 0 }, new float[8])) using (TestTable<double> doubleTable = new TestTable<double>(new double[4] { 1, -5, 100, 0 }, new double[4] { 22, -1, -50, 0 }, new double[4])) { var vf1 = Unsafe.Read<Vector256<float>>(floatTable.inArray1Ptr); var vf2 = Unsafe.Read<Vector256<float>>(floatTable.inArray2Ptr); var vf3 = Avx.HorizontalAdd(vf1, vf2); Unsafe.Write(floatTable.outArrayPtr, vf3); if (!floatTable.CheckResult((left, right, result) => (left[0] + left[1] == result[0]) && (right[0] + right[1] == result[2]) && (left[2] + left[3] == result[1]) && (right[2] + right[3] == result[3]) && (left[4] + left[5] == result[4]) && (right[4] + right[5] == result[6]) && (left[6] + left[7] == result[5]) && (right[6] + right[7] == result[7]))) { Console.WriteLine("Avx HorizontalAdd failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } var vd1 = Unsafe.Read<Vector256<double>>(doubleTable.inArray1Ptr); var vd2 = Unsafe.Read<Vector256<double>>(doubleTable.inArray2Ptr); var vd3 = Avx.HorizontalAdd(vd1, vd2); Unsafe.Write(doubleTable.outArrayPtr, vd3); if (!doubleTable.CheckResult((left, right, result) => (left[0] + left[1] == result[0]) && (right[0] + right[1] == result[1]) && (left[2] + left[3] == result[2]) && (right[2] + right[3] == result[3]))) { Console.WriteLine("Avx HorizontalAdd failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray1; public T[] inArray2; public T[] outArray; public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer(); public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle1; GCHandle inHandle2; GCHandle outHandle; public TestTable(T[] a, T[] b, T[] c) { this.inArray1 = a; this.inArray2 = b; this.outArray = c; inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned); inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T[], T[], T[], bool> check) { return check(inArray1, inArray2, outArray); } public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Private.CoreLib/src/System/Threading/TimerQueue.Windows.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; namespace System.Threading { internal sealed partial class TimerQueue { private static long TickCount64 { get { // We need to keep our notion of time synchronized with the calls to SleepEx that drive // the underlying native timer. In Win8, SleepEx does not count the time the machine spends // sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time, // so we will get out of sync with SleepEx if we use that method. // // So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent // in sleep/hibernate mode. if (Environment.IsWindows8OrAbove) { // Based on its documentation the QueryUnbiasedInterruptTime() function validates // the argument is non-null. In this case we are always supplying an argument, // so will skip return value validation. bool success = Interop.Kernel32.QueryUnbiasedInterruptTime(out ulong time100ns); Debug.Assert(success); return (long)(time100ns / 10_000); // convert from 100ns to milliseconds } else { return Environment.TickCount64; } } } } }
// 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; namespace System.Threading { internal sealed partial class TimerQueue { private static long TickCount64 { get { // We need to keep our notion of time synchronized with the calls to SleepEx that drive // the underlying native timer. In Win8, SleepEx does not count the time the machine spends // sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time, // so we will get out of sync with SleepEx if we use that method. // // So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent // in sleep/hibernate mode. if (Environment.IsWindows8OrAbove) { // Based on its documentation the QueryUnbiasedInterruptTime() function validates // the argument is non-null. In this case we are always supplying an argument, // so will skip return value validation. bool success = Interop.Kernel32.QueryUnbiasedInterruptTime(out ulong time100ns); Debug.Assert(success); return (long)(time100ns / 10_000); // convert from 100ns to milliseconds } else { return Environment.TickCount64; } } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/General/Vector128_1/op_OnesComplement.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_OnesComplementByte() { var test = new VectorUnaryOpTest__op_OnesComplementByte(); // 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 VectorUnaryOpTest__op_OnesComplementByte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.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<Byte> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__op_OnesComplementByte testClass) { var result = ~_fld1; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Vector128<Byte> _clsVar1; private Vector128<Byte> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__op_OnesComplementByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public VectorUnaryOpTest__op_OnesComplementByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, new Byte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = ~Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector128<Byte>).GetMethod("op_OnesComplement", new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = ~_clsVar1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var result = ~op1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__op_OnesComplementByte(); var result = ~test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = ~_fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = ~test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Byte> op1, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Byte[] firstOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (byte)(~firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (byte)(~firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_OnesComplement<Byte>(Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_OnesComplementByte() { var test = new VectorUnaryOpTest__op_OnesComplementByte(); // 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 VectorUnaryOpTest__op_OnesComplementByte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.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<Byte> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__op_OnesComplementByte testClass) { var result = ~_fld1; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Vector128<Byte> _clsVar1; private Vector128<Byte> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__op_OnesComplementByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public VectorUnaryOpTest__op_OnesComplementByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, new Byte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = ~Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector128<Byte>).GetMethod("op_OnesComplement", new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = ~_clsVar1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var result = ~op1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__op_OnesComplementByte(); var result = ~test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = ~_fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = ~test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Byte> op1, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Byte[] firstOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (byte)(~firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (byte)(~firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_OnesComplement<Byte>(Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.ComponentModel.Composition/tests/System/ComponentModel/Composition/ComponentModelTestTypes.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.ComponentModel.Composition { public class CallbackExecuteCodeDuringCompose { public CallbackExecuteCodeDuringCompose(Action callback) { this.callback = callback; } [Export("MyOwnCallbackContract")] public string ExportValue { get { callback(); return string.Empty; } } [Import("MyOwnCallbackContract")] public string ImportValue { get; set; } private Action callback; } public class CallbackImportNotify : IPartImportsSatisfiedNotification { private Action callback; public CallbackImportNotify(Action callback) { this.callback = callback; } [Import(AllowDefault = true)] public ICompositionService ImportSomethingSoIGetImportCompletedCalled { get; set; } public void OnImportsSatisfied() { this.callback(); } } public class ExportValueTypeFactory { [Export("{AssemblyCatalogResolver}FactoryValueType")] public int Value { get { return 18; } } } public class ExportValueTypeSingleton { [Export("{AssemblyCatalogResolver}SingletonValueType")] public int Value { get { return 17; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.ComponentModel.Composition { public class CallbackExecuteCodeDuringCompose { public CallbackExecuteCodeDuringCompose(Action callback) { this.callback = callback; } [Export("MyOwnCallbackContract")] public string ExportValue { get { callback(); return string.Empty; } } [Import("MyOwnCallbackContract")] public string ImportValue { get; set; } private Action callback; } public class CallbackImportNotify : IPartImportsSatisfiedNotification { private Action callback; public CallbackImportNotify(Action callback) { this.callback = callback; } [Import(AllowDefault = true)] public ICompositionService ImportSomethingSoIGetImportCompletedCalled { get; set; } public void OnImportsSatisfied() { this.callback(); } } public class ExportValueTypeFactory { [Export("{AssemblyCatalogResolver}FactoryValueType")] public int Value { get { return 18; } } } public class ExportValueTypeSingleton { [Export("{AssemblyCatalogResolver}SingletonValueType")] public int Value { get { return 17; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/Loader/classloader/explicitlayout/objrefandnonobjrefoverlap/case15.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // struct // int // struct // objref (delegate) using System; using System.Runtime.InteropServices; public class Foo{ public int i=42; public int getI(){return i;} } public class Bar{ private int i=1; public int getI(){return i;} } public delegate void FooDelegate(Object o); public delegate void BarDelegate(Object o); public struct WrapFoo { public FooDelegate o; } public struct WrapBar { public BarDelegate o; } [ StructLayout( LayoutKind.Explicit )] public struct MyUnion1 { [ FieldOffset( 0 )] public int i; [ FieldOffset( 0 )] public WrapBar o; } [ StructLayout( LayoutKind.Explicit )] public struct MyUnion2 { [ FieldOffset( 0 )] public int i; [ FieldOffset( 0 )] public WrapFoo o; } public class Test{ public static void MyCallback(Object o){ return; } public static int Main(string[] args){ bool caught=false; try{ Go(); } catch(TypeLoadException e){ caught=true; Console.WriteLine(e); } if(caught){ Console.WriteLine("PASS: caught expected exception"); return 100; } else{ Console.WriteLine("FAIL: was allowed to overlap an objref with a scalar."); return 101; } } public static void Go(){ MyUnion2 u2; MyUnion1 u1; u1.i = 0; u1.o.o = new BarDelegate(MyCallback); u2.i = 0; u2.o.o = new FooDelegate(MyCallback); // write the Foo's objref value now in u2.o into the int field of u1, // thereby overwriting the Bar objref that had been in u1.o. u1.i = u2.i; // Not doing further checks on delegate specific function calls. Unless the bug regresses, // the test case should never reach this point. Even it does, the lack of TypeLoadException // and the mere execution and returning of this method will indicate failure for the test. } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // struct // int // struct // objref (delegate) using System; using System.Runtime.InteropServices; public class Foo{ public int i=42; public int getI(){return i;} } public class Bar{ private int i=1; public int getI(){return i;} } public delegate void FooDelegate(Object o); public delegate void BarDelegate(Object o); public struct WrapFoo { public FooDelegate o; } public struct WrapBar { public BarDelegate o; } [ StructLayout( LayoutKind.Explicit )] public struct MyUnion1 { [ FieldOffset( 0 )] public int i; [ FieldOffset( 0 )] public WrapBar o; } [ StructLayout( LayoutKind.Explicit )] public struct MyUnion2 { [ FieldOffset( 0 )] public int i; [ FieldOffset( 0 )] public WrapFoo o; } public class Test{ public static void MyCallback(Object o){ return; } public static int Main(string[] args){ bool caught=false; try{ Go(); } catch(TypeLoadException e){ caught=true; Console.WriteLine(e); } if(caught){ Console.WriteLine("PASS: caught expected exception"); return 100; } else{ Console.WriteLine("FAIL: was allowed to overlap an objref with a scalar."); return 101; } } public static void Go(){ MyUnion2 u2; MyUnion1 u1; u1.i = 0; u1.o.o = new BarDelegate(MyCallback); u2.i = 0; u2.o.o = new FooDelegate(MyCallback); // write the Foo's objref value now in u2.o into the int field of u1, // thereby overwriting the Bar objref that had been in u1.o. u1.i = u2.i; // Not doing further checks on delegate specific function calls. Unless the bug regresses, // the test case should never reach this point. Even it does, the lack of TypeLoadException // and the mere execution and returning of this method will indicate failure for the test. } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/General/Vector256/OnesComplement.UInt16.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 OnesComplementUInt16() { var test = new VectorUnaryOpTest__OnesComplementUInt16(); // 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 VectorUnaryOpTest__OnesComplementUInt16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt16> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__OnesComplementUInt16 testClass) { var result = Vector256.OnesComplement(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static Vector256<UInt16> _clsVar1; private Vector256<UInt16> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__OnesComplementUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); } public VectorUnaryOpTest__OnesComplementUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, new UInt16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.OnesComplement( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.OnesComplement), new Type[] { typeof(Vector256<UInt16>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.OnesComplement), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.OnesComplement( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr); var result = Vector256.OnesComplement(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__OnesComplementUInt16(); var result = Vector256.OnesComplement(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.OnesComplement(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.OnesComplement(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<UInt16> op1, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (ushort)(~firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (ushort)(~firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.OnesComplement)}<UInt16>(Vector256<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void OnesComplementUInt16() { var test = new VectorUnaryOpTest__OnesComplementUInt16(); // 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 VectorUnaryOpTest__OnesComplementUInt16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt16> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__OnesComplementUInt16 testClass) { var result = Vector256.OnesComplement(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static Vector256<UInt16> _clsVar1; private Vector256<UInt16> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__OnesComplementUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); } public VectorUnaryOpTest__OnesComplementUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, new UInt16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.OnesComplement( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.OnesComplement), new Type[] { typeof(Vector256<UInt16>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.OnesComplement), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.OnesComplement( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr); var result = Vector256.OnesComplement(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__OnesComplementUInt16(); var result = Vector256.OnesComplement(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.OnesComplement(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.OnesComplement(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<UInt16> op1, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (ushort)(~firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (ushort)(~firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.OnesComplement)}<UInt16>(Vector256<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Private.Xml/tests/XPath/XmlDocument/XmlDocumentXPathTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using XPathTests.Common; namespace XPathTests.Common { public static partial class Utils { private static readonly ICreateNavigator _navigatorCreator = new CreateNavigatorFromXmlDocument(); public static readonly string ResourceFilesPath = "System.Xml.XPath.XmlDocument.Tests.TestData."; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using XPathTests.Common; namespace XPathTests.Common { public static partial class Utils { private static readonly ICreateNavigator _navigatorCreator = new CreateNavigatorFromXmlDocument(); public static readonly string ResourceFilesPath = "System.Xml.XPath.XmlDocument.Tests.TestData."; } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Directed/cmov/Int_Xor_Op_cs_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Int_Xor_Op.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Int_Xor_Op.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFunction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; namespace System.Xml.Xsl.Qil { /// <summary> /// An anonymous QilExpression function node. /// </summary> /// <remarks> /// <para>Function is a block, so it may introduce assignments (scoped to the function body). /// Additionally, it has an argument list, which will be assigned values /// when the function is invoked.</para> /// <para>The XmlType property defines the expected return type of this function. /// Normally, this should be the same as its definition's types, so setting the function /// definition changes the function's types. In some rare cases, a compiler may wish to /// override the types after setting the function's definition (for example, an XQuery /// might define a function's return type to be wider than its definition would imply.)</para> /// </remarks> internal sealed class QilFunction : QilReference { private QilNode _arguments, _definition, _sideEffects; //----------------------------------------------- // Constructor //----------------------------------------------- /// <summary> /// Construct a node /// </summary> public QilFunction(QilNodeType nodeType, QilNode arguments, QilNode definition, QilNode sideEffects, XmlQueryType resultType) : base(nodeType) { _arguments = arguments; _definition = definition; _sideEffects = sideEffects; this.xmlType = resultType; } //----------------------------------------------- // IList<QilNode> methods -- override //----------------------------------------------- public override int Count { get { return 3; } } public override QilNode this[int index] { get { return index switch { 0 => _arguments, 1 => _definition, 2 => _sideEffects, _ => throw new IndexOutOfRangeException(), }; } set { switch (index) { case 0: _arguments = value; break; case 1: _definition = value; break; case 2: _sideEffects = value; break; default: throw new IndexOutOfRangeException(); } } } //----------------------------------------------- // QilFunction methods //----------------------------------------------- /// <summary> /// Formal arguments of this function. /// </summary> public QilList Arguments { get { return (QilList)_arguments; } set { _arguments = value; } } /// <summary> /// Body of this function. /// </summary> public QilNode Definition { get { return _definition; } set { _definition = value; } } /// <summary> /// QilNodeType.True if this function might have side-effects. /// </summary> public bool MaybeSideEffects { get { return _sideEffects.NodeType == QilNodeType.True; } set { _sideEffects.NodeType = value ? QilNodeType.True : QilNodeType.False; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; namespace System.Xml.Xsl.Qil { /// <summary> /// An anonymous QilExpression function node. /// </summary> /// <remarks> /// <para>Function is a block, so it may introduce assignments (scoped to the function body). /// Additionally, it has an argument list, which will be assigned values /// when the function is invoked.</para> /// <para>The XmlType property defines the expected return type of this function. /// Normally, this should be the same as its definition's types, so setting the function /// definition changes the function's types. In some rare cases, a compiler may wish to /// override the types after setting the function's definition (for example, an XQuery /// might define a function's return type to be wider than its definition would imply.)</para> /// </remarks> internal sealed class QilFunction : QilReference { private QilNode _arguments, _definition, _sideEffects; //----------------------------------------------- // Constructor //----------------------------------------------- /// <summary> /// Construct a node /// </summary> public QilFunction(QilNodeType nodeType, QilNode arguments, QilNode definition, QilNode sideEffects, XmlQueryType resultType) : base(nodeType) { _arguments = arguments; _definition = definition; _sideEffects = sideEffects; this.xmlType = resultType; } //----------------------------------------------- // IList<QilNode> methods -- override //----------------------------------------------- public override int Count { get { return 3; } } public override QilNode this[int index] { get { return index switch { 0 => _arguments, 1 => _definition, 2 => _sideEffects, _ => throw new IndexOutOfRangeException(), }; } set { switch (index) { case 0: _arguments = value; break; case 1: _definition = value; break; case 2: _sideEffects = value; break; default: throw new IndexOutOfRangeException(); } } } //----------------------------------------------- // QilFunction methods //----------------------------------------------- /// <summary> /// Formal arguments of this function. /// </summary> public QilList Arguments { get { return (QilList)_arguments; } set { _arguments = value; } } /// <summary> /// Body of this function. /// </summary> public QilNode Definition { get { return _definition; } set { _definition = value; } } /// <summary> /// QilNodeType.True if this function might have side-effects. /// </summary> public bool MaybeSideEffects { get { return _sideEffects.NodeType == QilNodeType.True; } set { _sideEffects.NodeType = value ? QilNodeType.True : QilNodeType.False; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/installer/tests/TestUtils/Command.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace Microsoft.DotNet.Cli.Build.Framework { public class Command { private StringWriter _stdOutCapture; private StringWriter _stdErrCapture; private Action<string> _stdOutForward; private Action<string> _stdErrForward; private Action<string> _stdOutHandler; private Action<string> _stdErrHandler; private bool _running = false; private bool _quietBuildReporter = false; public Process Process { get; } // Priority order of runnable suffixes to look for and run private static readonly string[] RunnableSuffixes = OperatingSystem.IsWindows() ? new string[] { ".exe", ".cmd", ".bat" } : new string[] { string.Empty }; private Command(string executable, string args) { // Set the things we need var psi = new ProcessStartInfo() { FileName = executable, Arguments = args }; Process = new Process() { StartInfo = psi }; } public static Command Create(string executable, params string[] args) { return Create(executable, ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args)); } public static Command Create(string executable, IEnumerable<string> args) { return Create(executable, ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args)); } public static Command Create(string executable, string args) { ResolveExecutablePath(ref executable, ref args); return new Command(executable, args); } private static void ResolveExecutablePath(ref string executable, ref string args) { foreach (string suffix in RunnableSuffixes) { var fullExecutable = Path.GetFullPath(Path.Combine( AppContext.BaseDirectory, executable + suffix)); if (File.Exists(fullExecutable)) { executable = fullExecutable; // In priority order we've found the best runnable extension, so break. break; } } // On Windows, we want to avoid using "cmd" if possible (it mangles the colors, and a bunch of other things) // So, do a quick path search to see if we can just directly invoke it var useCmd = ShouldUseCmd(executable); if (useCmd) { var comSpec = System.Environment.GetEnvironmentVariable("ComSpec"); // cmd doesn't like "foo.exe ", so we need to ensure that if // args is empty, we just run "foo.exe" if (!string.IsNullOrEmpty(args)) { executable = (executable + " " + args).Replace("\"", "\\\""); } args = $"/C \"{executable}\""; executable = comSpec; } } private static bool ShouldUseCmd(string executable) { if (OperatingSystem.IsWindows()) { var extension = Path.GetExtension(executable); if (!string.IsNullOrEmpty(extension)) { return !string.Equals(extension, ".exe", StringComparison.Ordinal); } else if (executable.Contains(Path.DirectorySeparatorChar)) { // It's a relative path without an extension if (File.Exists(executable + ".exe")) { // It refers to an exe! return false; } } else { // Search the path to see if we can find it foreach (var path in System.Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator)) { var candidate = Path.Combine(path, executable + ".exe"); if (File.Exists(candidate)) { // We found an exe! return false; } } } // It's a non-exe :( return true; } // Non-windows never uses cmd return false; } public Command Environment(IDictionary<string, string> env) { if (env == null) { return this; } foreach (var item in env) { Process.StartInfo.Environment[item.Key] = item.Value; } return this; } public Command Environment(string key, string value) { Process.StartInfo.Environment[key] = value; return this; } public Command QuietBuildReporter() { _quietBuildReporter = true; return this; } public CommandResult Execute() { return Execute(false); } public Command Start() { ThrowIfRunning(); _running = true; if (Process.StartInfo.RedirectStandardOutput) { Process.OutputDataReceived += (sender, args) => { ProcessData(args.Data, _stdOutCapture, _stdOutForward, _stdOutHandler); }; } if (Process.StartInfo.RedirectStandardError) { Process.ErrorDataReceived += (sender, args) => { ProcessData(args.Data, _stdErrCapture, _stdErrForward, _stdErrHandler); }; } Process.EnableRaisingEvents = true; ReportExecBegin(); // Retry if we hit ETXTBSY due to Linux race // https://github.com/dotnet/runtime/issues/58964 for (int i = 0; ; i++) { try { Process.Start(); break; } catch (Win32Exception e) when (i < 4 && e.Message.Contains("Text file busy")) { Thread.Sleep(i * 20); } } if (Process.StartInfo.RedirectStandardOutput) { Process.BeginOutputReadLine(); } if (Process.StartInfo.RedirectStandardError) { Process.BeginErrorReadLine(); } return this; } public CommandResult WaitForExit(bool fExpectedToFail, int timeoutMilliseconds = Timeout.Infinite) { ReportExecWaitOnExit(); int exitCode; if (!Process.WaitForExit(timeoutMilliseconds)) { exitCode = -1; } else { exitCode = Process.ExitCode; } ReportExecEnd(exitCode, fExpectedToFail); return new CommandResult( Process.StartInfo, exitCode, _stdOutCapture?.GetStringBuilder()?.ToString(), _stdErrCapture?.GetStringBuilder()?.ToString()); } public CommandResult Execute(bool fExpectedToFail) { Start(); return WaitForExit(fExpectedToFail); } public Command WorkingDirectory(string projectDirectory) { Process.StartInfo.WorkingDirectory = projectDirectory; return this; } public Command WithUserProfile(string userprofile) { string userDir; if (OperatingSystem.IsWindows()) { userDir = "USERPROFILE"; } else { userDir = "HOME"; } Process.StartInfo.Environment[userDir] = userprofile; return this; } public Command EnvironmentVariable(string name, string value) { if (value == null) { value = ""; } Process.StartInfo.Environment[name] = value; return this; } public Command CaptureStdOut() { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; _stdOutCapture = new StringWriter(); return this; } public Command CaptureStdErr() { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; _stdErrCapture = new StringWriter(); return this; } public Command ForwardStdOut(TextWriter to = null) { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; if (to == null) { _stdOutForward = Reporter.Output.WriteLine; } else { _stdOutForward = to.WriteLine; } return this; } public Command ForwardStdErr(TextWriter to = null) { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; if (to == null) { _stdErrForward = Reporter.Error.WriteLine; } else { _stdErrForward = to.WriteLine; } return this; } public Command OnOutputLine(Action<string> handler) { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; if (_stdOutHandler != null) { throw new InvalidOperationException("Already handling stdout!"); } _stdOutHandler = handler; return this; } public Command OnErrorLine(Action<string> handler) { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; if (_stdErrHandler != null) { throw new InvalidOperationException("Already handling stderr!"); } _stdErrHandler = handler; return this; } private string FormatProcessInfo(ProcessStartInfo info, bool includeWorkingDirectory) { string prefix = includeWorkingDirectory ? $"{info.WorkingDirectory}> {info.FileName}" : info.FileName; if (string.IsNullOrWhiteSpace(info.Arguments)) { return prefix; } return prefix + " " + info.Arguments; } private void ReportExecBegin() { if (!_quietBuildReporter) { BuildReporter.BeginSection("EXEC", FormatProcessInfo(Process.StartInfo, includeWorkingDirectory: false)); } } private void ReportExecWaitOnExit() { if (!_quietBuildReporter) { BuildReporter.SectionComment("EXEC", $"Waiting for process {Process.Id} to exit..."); } } private void ReportExecEnd(int exitCode, bool fExpectedToFail) { if (!_quietBuildReporter) { bool success = exitCode == 0; string msgExpectedToFail = ""; if (fExpectedToFail) { success = !success; msgExpectedToFail = "failed as expected and "; } var message = $"{FormatProcessInfo(Process.StartInfo, includeWorkingDirectory: !success)} {msgExpectedToFail}exited with {exitCode}"; BuildReporter.EndSection( "EXEC", success ? message.Green() : message.Red().Bold(), success); } } private void ThrowIfRunning([CallerMemberName] string memberName = null) { if (_running) { throw new InvalidOperationException($"Unable to invoke {memberName} after the command has been run"); } } private void ProcessData(string data, StringWriter capture, Action<string> forward, Action<string> handler) { if (data == null) { return; } if (capture != null) { capture.WriteLine(data); } forward?.Invoke(data); handler?.Invoke(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; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace Microsoft.DotNet.Cli.Build.Framework { public class Command { private StringWriter _stdOutCapture; private StringWriter _stdErrCapture; private Action<string> _stdOutForward; private Action<string> _stdErrForward; private Action<string> _stdOutHandler; private Action<string> _stdErrHandler; private bool _running = false; private bool _quietBuildReporter = false; public Process Process { get; } // Priority order of runnable suffixes to look for and run private static readonly string[] RunnableSuffixes = OperatingSystem.IsWindows() ? new string[] { ".exe", ".cmd", ".bat" } : new string[] { string.Empty }; private Command(string executable, string args) { // Set the things we need var psi = new ProcessStartInfo() { FileName = executable, Arguments = args }; Process = new Process() { StartInfo = psi }; } public static Command Create(string executable, params string[] args) { return Create(executable, ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args)); } public static Command Create(string executable, IEnumerable<string> args) { return Create(executable, ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(args)); } public static Command Create(string executable, string args) { ResolveExecutablePath(ref executable, ref args); return new Command(executable, args); } private static void ResolveExecutablePath(ref string executable, ref string args) { foreach (string suffix in RunnableSuffixes) { var fullExecutable = Path.GetFullPath(Path.Combine( AppContext.BaseDirectory, executable + suffix)); if (File.Exists(fullExecutable)) { executable = fullExecutable; // In priority order we've found the best runnable extension, so break. break; } } // On Windows, we want to avoid using "cmd" if possible (it mangles the colors, and a bunch of other things) // So, do a quick path search to see if we can just directly invoke it var useCmd = ShouldUseCmd(executable); if (useCmd) { var comSpec = System.Environment.GetEnvironmentVariable("ComSpec"); // cmd doesn't like "foo.exe ", so we need to ensure that if // args is empty, we just run "foo.exe" if (!string.IsNullOrEmpty(args)) { executable = (executable + " " + args).Replace("\"", "\\\""); } args = $"/C \"{executable}\""; executable = comSpec; } } private static bool ShouldUseCmd(string executable) { if (OperatingSystem.IsWindows()) { var extension = Path.GetExtension(executable); if (!string.IsNullOrEmpty(extension)) { return !string.Equals(extension, ".exe", StringComparison.Ordinal); } else if (executable.Contains(Path.DirectorySeparatorChar)) { // It's a relative path without an extension if (File.Exists(executable + ".exe")) { // It refers to an exe! return false; } } else { // Search the path to see if we can find it foreach (var path in System.Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator)) { var candidate = Path.Combine(path, executable + ".exe"); if (File.Exists(candidate)) { // We found an exe! return false; } } } // It's a non-exe :( return true; } // Non-windows never uses cmd return false; } public Command Environment(IDictionary<string, string> env) { if (env == null) { return this; } foreach (var item in env) { Process.StartInfo.Environment[item.Key] = item.Value; } return this; } public Command Environment(string key, string value) { Process.StartInfo.Environment[key] = value; return this; } public Command QuietBuildReporter() { _quietBuildReporter = true; return this; } public CommandResult Execute() { return Execute(false); } public Command Start() { ThrowIfRunning(); _running = true; if (Process.StartInfo.RedirectStandardOutput) { Process.OutputDataReceived += (sender, args) => { ProcessData(args.Data, _stdOutCapture, _stdOutForward, _stdOutHandler); }; } if (Process.StartInfo.RedirectStandardError) { Process.ErrorDataReceived += (sender, args) => { ProcessData(args.Data, _stdErrCapture, _stdErrForward, _stdErrHandler); }; } Process.EnableRaisingEvents = true; ReportExecBegin(); // Retry if we hit ETXTBSY due to Linux race // https://github.com/dotnet/runtime/issues/58964 for (int i = 0; ; i++) { try { Process.Start(); break; } catch (Win32Exception e) when (i < 4 && e.Message.Contains("Text file busy")) { Thread.Sleep(i * 20); } } if (Process.StartInfo.RedirectStandardOutput) { Process.BeginOutputReadLine(); } if (Process.StartInfo.RedirectStandardError) { Process.BeginErrorReadLine(); } return this; } public CommandResult WaitForExit(bool fExpectedToFail, int timeoutMilliseconds = Timeout.Infinite) { ReportExecWaitOnExit(); int exitCode; if (!Process.WaitForExit(timeoutMilliseconds)) { exitCode = -1; } else { exitCode = Process.ExitCode; } ReportExecEnd(exitCode, fExpectedToFail); return new CommandResult( Process.StartInfo, exitCode, _stdOutCapture?.GetStringBuilder()?.ToString(), _stdErrCapture?.GetStringBuilder()?.ToString()); } public CommandResult Execute(bool fExpectedToFail) { Start(); return WaitForExit(fExpectedToFail); } public Command WorkingDirectory(string projectDirectory) { Process.StartInfo.WorkingDirectory = projectDirectory; return this; } public Command WithUserProfile(string userprofile) { string userDir; if (OperatingSystem.IsWindows()) { userDir = "USERPROFILE"; } else { userDir = "HOME"; } Process.StartInfo.Environment[userDir] = userprofile; return this; } public Command EnvironmentVariable(string name, string value) { if (value == null) { value = ""; } Process.StartInfo.Environment[name] = value; return this; } public Command CaptureStdOut() { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; _stdOutCapture = new StringWriter(); return this; } public Command CaptureStdErr() { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; _stdErrCapture = new StringWriter(); return this; } public Command ForwardStdOut(TextWriter to = null) { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; if (to == null) { _stdOutForward = Reporter.Output.WriteLine; } else { _stdOutForward = to.WriteLine; } return this; } public Command ForwardStdErr(TextWriter to = null) { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; if (to == null) { _stdErrForward = Reporter.Error.WriteLine; } else { _stdErrForward = to.WriteLine; } return this; } public Command OnOutputLine(Action<string> handler) { ThrowIfRunning(); Process.StartInfo.RedirectStandardOutput = true; if (_stdOutHandler != null) { throw new InvalidOperationException("Already handling stdout!"); } _stdOutHandler = handler; return this; } public Command OnErrorLine(Action<string> handler) { ThrowIfRunning(); Process.StartInfo.RedirectStandardError = true; if (_stdErrHandler != null) { throw new InvalidOperationException("Already handling stderr!"); } _stdErrHandler = handler; return this; } private string FormatProcessInfo(ProcessStartInfo info, bool includeWorkingDirectory) { string prefix = includeWorkingDirectory ? $"{info.WorkingDirectory}> {info.FileName}" : info.FileName; if (string.IsNullOrWhiteSpace(info.Arguments)) { return prefix; } return prefix + " " + info.Arguments; } private void ReportExecBegin() { if (!_quietBuildReporter) { BuildReporter.BeginSection("EXEC", FormatProcessInfo(Process.StartInfo, includeWorkingDirectory: false)); } } private void ReportExecWaitOnExit() { if (!_quietBuildReporter) { BuildReporter.SectionComment("EXEC", $"Waiting for process {Process.Id} to exit..."); } } private void ReportExecEnd(int exitCode, bool fExpectedToFail) { if (!_quietBuildReporter) { bool success = exitCode == 0; string msgExpectedToFail = ""; if (fExpectedToFail) { success = !success; msgExpectedToFail = "failed as expected and "; } var message = $"{FormatProcessInfo(Process.StartInfo, includeWorkingDirectory: !success)} {msgExpectedToFail}exited with {exitCode}"; BuildReporter.EndSection( "EXEC", success ? message.Green() : message.Red().Bold(), success); } } private void ThrowIfRunning([CallerMemberName] string memberName = null) { if (_running) { throw new InvalidOperationException($"Unable to invoke {memberName} after the command has been run"); } } private void ProcessData(string data, StringWriter capture, Action<string> forward, Action<string> handler) { if (data == null) { return; } if (capture != null) { capture.WriteLine(data); } forward?.Invoke(data); handler?.Invoke(data); } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.IO.Ports/tests/SerialStream/BeginRead.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.IO.PortsTests; using System.Linq; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class SerialStream_BeginRead : PortsTest { // The number of random bytes to receive for read method testing private const int numRndBytesToRead = 16; // The number of random bytes to receive for large input buffer testing private const int largeNumRndBytesToRead = 2048; // When we test Read and do not care about actually reading anything we must still // create an byte array to pass into the method the following is the size of the // byte array used in this situation private const int defaultByteArraySize = 1; private const int defaultByteOffset = 0; private const int defaultByteCount = 1; // The maximum buffer size when an exception occurs private const int maxBufferSizeForException = 255; // The maximum buffer size when an exception is not expected private const int maxBufferSize = 8; // Maximum time to wait for processing the read command to complete private const int MAX_WAIT_READ_COMPLETE = 1000; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void Buffer_Null() { VerifyReadException<ArgumentNullException>(null, 0, 1); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEG1() { VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], -1, defaultByteCount); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEGRND() { var rndGen = new Random(-55); VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], rndGen.Next(int.MinValue, 0), defaultByteCount); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_MinInt() { VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], int.MinValue, defaultByteCount); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEG1() { VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], defaultByteOffset, -1); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEGRND() { var rndGen = new Random(-55); VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], defaultByteOffset, rndGen.Next(int.MinValue, 0)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_MinInt() { VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], defaultByteOffset, int.MinValue); } [ConditionalFact(nameof(HasOneSerialPort))] public void OffsetCount_EQ_Length_Plus_1() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(0, bufferLength); int count = bufferLength + 1 - offset; VerifyReadException<ArgumentException>(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasOneSerialPort))] public void OffsetCount_GT_Length() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(0, bufferLength); int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue); VerifyReadException<ArgumentException>(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_GT_Length() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(bufferLength, int.MaxValue); int count = defaultByteCount; VerifyReadException<ArgumentException>(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_GT_Length() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = defaultByteOffset; int count = rndGen.Next(bufferLength + 1, int.MaxValue); VerifyReadException<ArgumentException>(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void OffsetCount_EQ_Length() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = rndGen.Next(0, bufferLength - 1); int count = bufferLength - offset; VerifyRead(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void Offset_EQ_Length_Minus_1() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = bufferLength - 1; var count = 1; VerifyRead(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void Count_EQ_Length() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); var offset = 0; int count = bufferLength; VerifyRead(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void LargeInputBuffer() { int bufferLength = largeNumRndBytesToRead; var offset = 0; int count = bufferLength; VerifyRead(new byte[bufferLength], offset, count, largeNumRndBytesToRead); } [ConditionalFact(nameof(HasNullModem))] public void Callback() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var callbackHandler = new CallbackHandler(); int elapsedTime; Debug.WriteLine("Verifying BeginRead with a callback specified"); com1.Open(); com2.Open(); IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(new byte[numRndBytesToRead], 0, numRndBytesToRead, callbackHandler.Callback, null); callbackHandler.BeginReadAsyncResult = readAsyncResult; Assert.Null(readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously, "Should not have completed sync (read)"); Assert.False(readAsyncResult.IsCompleted, "Should not have completed yet"); com2.Write(new byte[numRndBytesToRead], 0, numRndBytesToRead); // callbackHandler.ReadAsyncResult guarantees that the callback has been calledhowever it does not gauarentee that // the code calling the callback has finished it's processing IAsyncResult callbackReadAsyncResult = callbackHandler.ReadAysncResult; // No we have to wait for the callbackHandler to complete elapsedTime = 0; while (!callbackReadAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_READ_COMPLETE) { Thread.Sleep(10); elapsedTime += 10; } Assert.Null(callbackReadAsyncResult.AsyncState); Assert.False(callbackReadAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)"); Assert.True(callbackReadAsyncResult.IsCompleted, "Should have completed (cback)"); Assert.Null(readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously, "Should not have completed sync (read)"); Assert.True(readAsyncResult.IsCompleted, "Should have completed (read)"); } } [ConditionalFact(nameof(HasNullModem))] public void Callback_EndReadonCallback() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var callbackHandler = new CallbackHandler(com1); int elapsedTime; Debug.WriteLine("Verifying BeginRead with a callback that calls EndRead"); com1.Open(); com2.Open(); IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(new byte[numRndBytesToRead], 0, numRndBytesToRead, callbackHandler.Callback, null); callbackHandler.BeginReadAsyncResult = readAsyncResult; Assert.Null(readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously); Assert.False(readAsyncResult.IsCompleted); com2.Write(new byte[numRndBytesToRead], 0, numRndBytesToRead); // callbackHandler.ReadAsyncResult guarantees that the callback has been calledhowever it does not gauarentee that // the code calling the callback has finished it's processing IAsyncResult callbackReadAsyncResult = callbackHandler.ReadAysncResult; // No we have to wait for the callbackHandler to complete elapsedTime = 0; while (!callbackReadAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_READ_COMPLETE) { Thread.Sleep(10); elapsedTime += 10; } Assert.Null(callbackReadAsyncResult.AsyncState); Assert.False(callbackReadAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)"); Assert.True(callbackReadAsyncResult.IsCompleted, "Should have completed (cback)"); Assert.Null(readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously, "Should not have completed sync (read)"); Assert.True(readAsyncResult.IsCompleted, "Should have completed (read)"); } } [ConditionalFact(nameof(HasNullModem))] public void Callback_State() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var callbackHandler = new CallbackHandler(); int elapsedTime; Debug.WriteLine("Verifying BeginRead with a callback and state specified"); com1.Open(); com2.Open(); IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(new byte[numRndBytesToRead], 0, numRndBytesToRead, callbackHandler.Callback, this); callbackHandler.BeginReadAsyncResult = readAsyncResult; Assert.Equal(this, readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously); Assert.False(readAsyncResult.IsCompleted); com2.Write(new byte[numRndBytesToRead], 0, numRndBytesToRead); // callbackHandler.ReadAsyncResult guarantees that the callback has been calledhowever it does not gauarentee that // the code calling the callback has finished it's processing IAsyncResult callbackReadAsyncResult = callbackHandler.ReadAysncResult; // No we have to wait for the callbackHandler to complete elapsedTime = 0; while (!callbackReadAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_READ_COMPLETE) { Thread.Sleep(10); elapsedTime += 10; } Assert.Equal(this, callbackReadAsyncResult.AsyncState); Assert.False(callbackReadAsyncResult.CompletedSynchronously); Assert.True(callbackReadAsyncResult.IsCompleted); Assert.Equal(this, readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously); Assert.True(readAsyncResult.IsCompleted); } } #endregion #region Verification for Test Cases private void VerifyReadException<T>(byte[] buffer, int offset, int count) where T : Exception { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { int bufferLength = null == buffer ? 0 : buffer.Length; Debug.WriteLine("Verifying read method throws {0} buffer.Lenght={1}, offset={2}, count={3}", typeof(T), bufferLength, offset, count); com.Open(); Action a = () => com.BaseStream.BeginRead(buffer, offset, count, null, null); Assert.Throws<T>(a); } } private void VerifyRead(byte[] buffer, int offset, int count) { VerifyRead(buffer, offset, count, numRndBytesToRead); } private void VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(-55); var bytesToWrite = new byte[numberOfBytesToRead]; // Generate random bytes for (var i = 0; i < bytesToWrite.Length; i++) { var randByte = (byte)rndGen.Next(0, 256); bytesToWrite[i] = randByte; } // Generate some random bytes in the buffer rndGen.NextBytes(buffer); Debug.WriteLine("Verifying read method buffer.Lenght={0}, offset={1}, count={2} with {3} random chars", buffer.Length, offset, count, bytesToWrite.Length); com1.ReadTimeout = 500; com1.Open(); com2.Open(); VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, buffer, offset, count); } } private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) { var buffer = new byte[bytesToWrite.Length]; int totalBytesRead; int bytesToRead; var oldRcvBuffer = (byte[])rcvBuffer.Clone(); var callbackHandler = new CallbackHandler(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250); totalBytesRead = 0; bytesToRead = com1.BytesToRead; do { IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(rcvBuffer, offset, count, callbackHandler.Callback, this); readAsyncResult.AsyncWaitHandle.WaitOne(); callbackHandler.BeginReadAsyncResult = readAsyncResult; int bytesRead = com1.BaseStream.EndRead(readAsyncResult); IAsyncResult asyncResult = callbackHandler.ReadAysncResult; Assert.Equal(this, asyncResult.AsyncState); Assert.False(asyncResult.CompletedSynchronously); Assert.True(asyncResult.IsCompleted); Assert.Equal(this, readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously); Assert.True(readAsyncResult.IsCompleted); if ((bytesToRead > bytesRead && count != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead)) { // If we have not read all of the characters that we should have Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (bytesToWrite.Length < totalBytesRead + bytesRead) { // If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent"); } VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, bytesRead); Array.Copy(rcvBuffer, offset, buffer, totalBytesRead, bytesRead); totalBytesRead += bytesRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } oldRcvBuffer = (byte[])rcvBuffer.Clone(); bytesToRead = com1.BytesToRead; } while (0 != com1.BytesToRead); // While there are more bytes to read // Compare the bytes that were written with the ones we read Assert.Equal(bytesToWrite, buffer.Take(bytesToWrite.Length).ToArray()); } private void VerifyBuffer(byte[] actualBuffer, byte[] expectedBuffer, int offset, int count) { // Verify all character before the offset for (var i = 0; i < offset; i++) { if (actualBuffer[i] != expectedBuffer[i]) { Fail("ERROR!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]); } } // Verify all character after the offset + count for (int i = offset + count; i < actualBuffer.Length; i++) { if (actualBuffer[i] != expectedBuffer[i]) { Fail("ERROR!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]); } } } private class CallbackHandler { private IAsyncResult _readAysncResult; private IAsyncResult _beginReadAsyncResult; private readonly SerialPort _com; public CallbackHandler() : this(null) { } public CallbackHandler(SerialPort com) { _com = com; } public void Callback(IAsyncResult readAysncResult) { lock (this) { _readAysncResult = readAysncResult; Assert.True(readAysncResult.IsCompleted, "IAsyncResult passed into callback is not completed"); while (null == _beginReadAsyncResult) { Monitor.Wait(this); } if (null != _beginReadAsyncResult && !_beginReadAsyncResult.IsCompleted) { Fail("Err_7907azpu Expected IAsyncResult returned from begin read to not be completed"); } if (null != _com) { _com.BaseStream.EndRead(_beginReadAsyncResult); if (!_beginReadAsyncResult.IsCompleted) { Fail("Err_6498afead Expected IAsyncResult returned from begin read to not be completed"); } if (!readAysncResult.IsCompleted) { Fail("Err_1398ehpo Expected IAsyncResult passed into callback to not be completed"); } } Monitor.Pulse(this); } } public IAsyncResult ReadAysncResult { get { lock (this) { while (null == _readAysncResult) { Monitor.Wait(this); } return _readAysncResult; } } } public IAsyncResult BeginReadAsyncResult { get { return _beginReadAsyncResult; } set { lock (this) { _beginReadAsyncResult = value; Monitor.Pulse(this); } } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.IO.PortsTests; using System.Linq; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class SerialStream_BeginRead : PortsTest { // The number of random bytes to receive for read method testing private const int numRndBytesToRead = 16; // The number of random bytes to receive for large input buffer testing private const int largeNumRndBytesToRead = 2048; // When we test Read and do not care about actually reading anything we must still // create an byte array to pass into the method the following is the size of the // byte array used in this situation private const int defaultByteArraySize = 1; private const int defaultByteOffset = 0; private const int defaultByteCount = 1; // The maximum buffer size when an exception occurs private const int maxBufferSizeForException = 255; // The maximum buffer size when an exception is not expected private const int maxBufferSize = 8; // Maximum time to wait for processing the read command to complete private const int MAX_WAIT_READ_COMPLETE = 1000; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void Buffer_Null() { VerifyReadException<ArgumentNullException>(null, 0, 1); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEG1() { VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], -1, defaultByteCount); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEGRND() { var rndGen = new Random(-55); VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], rndGen.Next(int.MinValue, 0), defaultByteCount); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_MinInt() { VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], int.MinValue, defaultByteCount); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEG1() { VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], defaultByteOffset, -1); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEGRND() { var rndGen = new Random(-55); VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], defaultByteOffset, rndGen.Next(int.MinValue, 0)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_MinInt() { VerifyReadException<ArgumentOutOfRangeException>(new byte[defaultByteArraySize], defaultByteOffset, int.MinValue); } [ConditionalFact(nameof(HasOneSerialPort))] public void OffsetCount_EQ_Length_Plus_1() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(0, bufferLength); int count = bufferLength + 1 - offset; VerifyReadException<ArgumentException>(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasOneSerialPort))] public void OffsetCount_GT_Length() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(0, bufferLength); int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue); VerifyReadException<ArgumentException>(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_GT_Length() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(bufferLength, int.MaxValue); int count = defaultByteCount; VerifyReadException<ArgumentException>(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_GT_Length() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = defaultByteOffset; int count = rndGen.Next(bufferLength + 1, int.MaxValue); VerifyReadException<ArgumentException>(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void OffsetCount_EQ_Length() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = rndGen.Next(0, bufferLength - 1); int count = bufferLength - offset; VerifyRead(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void Offset_EQ_Length_Minus_1() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = bufferLength - 1; var count = 1; VerifyRead(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void Count_EQ_Length() { var rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); var offset = 0; int count = bufferLength; VerifyRead(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void LargeInputBuffer() { int bufferLength = largeNumRndBytesToRead; var offset = 0; int count = bufferLength; VerifyRead(new byte[bufferLength], offset, count, largeNumRndBytesToRead); } [ConditionalFact(nameof(HasNullModem))] public void Callback() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var callbackHandler = new CallbackHandler(); int elapsedTime; Debug.WriteLine("Verifying BeginRead with a callback specified"); com1.Open(); com2.Open(); IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(new byte[numRndBytesToRead], 0, numRndBytesToRead, callbackHandler.Callback, null); callbackHandler.BeginReadAsyncResult = readAsyncResult; Assert.Null(readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously, "Should not have completed sync (read)"); Assert.False(readAsyncResult.IsCompleted, "Should not have completed yet"); com2.Write(new byte[numRndBytesToRead], 0, numRndBytesToRead); // callbackHandler.ReadAsyncResult guarantees that the callback has been calledhowever it does not gauarentee that // the code calling the callback has finished it's processing IAsyncResult callbackReadAsyncResult = callbackHandler.ReadAysncResult; // No we have to wait for the callbackHandler to complete elapsedTime = 0; while (!callbackReadAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_READ_COMPLETE) { Thread.Sleep(10); elapsedTime += 10; } Assert.Null(callbackReadAsyncResult.AsyncState); Assert.False(callbackReadAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)"); Assert.True(callbackReadAsyncResult.IsCompleted, "Should have completed (cback)"); Assert.Null(readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously, "Should not have completed sync (read)"); Assert.True(readAsyncResult.IsCompleted, "Should have completed (read)"); } } [ConditionalFact(nameof(HasNullModem))] public void Callback_EndReadonCallback() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var callbackHandler = new CallbackHandler(com1); int elapsedTime; Debug.WriteLine("Verifying BeginRead with a callback that calls EndRead"); com1.Open(); com2.Open(); IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(new byte[numRndBytesToRead], 0, numRndBytesToRead, callbackHandler.Callback, null); callbackHandler.BeginReadAsyncResult = readAsyncResult; Assert.Null(readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously); Assert.False(readAsyncResult.IsCompleted); com2.Write(new byte[numRndBytesToRead], 0, numRndBytesToRead); // callbackHandler.ReadAsyncResult guarantees that the callback has been calledhowever it does not gauarentee that // the code calling the callback has finished it's processing IAsyncResult callbackReadAsyncResult = callbackHandler.ReadAysncResult; // No we have to wait for the callbackHandler to complete elapsedTime = 0; while (!callbackReadAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_READ_COMPLETE) { Thread.Sleep(10); elapsedTime += 10; } Assert.Null(callbackReadAsyncResult.AsyncState); Assert.False(callbackReadAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)"); Assert.True(callbackReadAsyncResult.IsCompleted, "Should have completed (cback)"); Assert.Null(readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously, "Should not have completed sync (read)"); Assert.True(readAsyncResult.IsCompleted, "Should have completed (read)"); } } [ConditionalFact(nameof(HasNullModem))] public void Callback_State() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var callbackHandler = new CallbackHandler(); int elapsedTime; Debug.WriteLine("Verifying BeginRead with a callback and state specified"); com1.Open(); com2.Open(); IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(new byte[numRndBytesToRead], 0, numRndBytesToRead, callbackHandler.Callback, this); callbackHandler.BeginReadAsyncResult = readAsyncResult; Assert.Equal(this, readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously); Assert.False(readAsyncResult.IsCompleted); com2.Write(new byte[numRndBytesToRead], 0, numRndBytesToRead); // callbackHandler.ReadAsyncResult guarantees that the callback has been calledhowever it does not gauarentee that // the code calling the callback has finished it's processing IAsyncResult callbackReadAsyncResult = callbackHandler.ReadAysncResult; // No we have to wait for the callbackHandler to complete elapsedTime = 0; while (!callbackReadAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_READ_COMPLETE) { Thread.Sleep(10); elapsedTime += 10; } Assert.Equal(this, callbackReadAsyncResult.AsyncState); Assert.False(callbackReadAsyncResult.CompletedSynchronously); Assert.True(callbackReadAsyncResult.IsCompleted); Assert.Equal(this, readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously); Assert.True(readAsyncResult.IsCompleted); } } #endregion #region Verification for Test Cases private void VerifyReadException<T>(byte[] buffer, int offset, int count) where T : Exception { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { int bufferLength = null == buffer ? 0 : buffer.Length; Debug.WriteLine("Verifying read method throws {0} buffer.Lenght={1}, offset={2}, count={3}", typeof(T), bufferLength, offset, count); com.Open(); Action a = () => com.BaseStream.BeginRead(buffer, offset, count, null, null); Assert.Throws<T>(a); } } private void VerifyRead(byte[] buffer, int offset, int count) { VerifyRead(buffer, offset, count, numRndBytesToRead); } private void VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(-55); var bytesToWrite = new byte[numberOfBytesToRead]; // Generate random bytes for (var i = 0; i < bytesToWrite.Length; i++) { var randByte = (byte)rndGen.Next(0, 256); bytesToWrite[i] = randByte; } // Generate some random bytes in the buffer rndGen.NextBytes(buffer); Debug.WriteLine("Verifying read method buffer.Lenght={0}, offset={1}, count={2} with {3} random chars", buffer.Length, offset, count, bytesToWrite.Length); com1.ReadTimeout = 500; com1.Open(); com2.Open(); VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, buffer, offset, count); } } private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) { var buffer = new byte[bytesToWrite.Length]; int totalBytesRead; int bytesToRead; var oldRcvBuffer = (byte[])rcvBuffer.Clone(); var callbackHandler = new CallbackHandler(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250); totalBytesRead = 0; bytesToRead = com1.BytesToRead; do { IAsyncResult readAsyncResult = com1.BaseStream.BeginRead(rcvBuffer, offset, count, callbackHandler.Callback, this); readAsyncResult.AsyncWaitHandle.WaitOne(); callbackHandler.BeginReadAsyncResult = readAsyncResult; int bytesRead = com1.BaseStream.EndRead(readAsyncResult); IAsyncResult asyncResult = callbackHandler.ReadAysncResult; Assert.Equal(this, asyncResult.AsyncState); Assert.False(asyncResult.CompletedSynchronously); Assert.True(asyncResult.IsCompleted); Assert.Equal(this, readAsyncResult.AsyncState); Assert.False(readAsyncResult.CompletedSynchronously); Assert.True(readAsyncResult.IsCompleted); if ((bytesToRead > bytesRead && count != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead)) { // If we have not read all of the characters that we should have Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (bytesToWrite.Length < totalBytesRead + bytesRead) { // If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent"); } VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, bytesRead); Array.Copy(rcvBuffer, offset, buffer, totalBytesRead, bytesRead); totalBytesRead += bytesRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } oldRcvBuffer = (byte[])rcvBuffer.Clone(); bytesToRead = com1.BytesToRead; } while (0 != com1.BytesToRead); // While there are more bytes to read // Compare the bytes that were written with the ones we read Assert.Equal(bytesToWrite, buffer.Take(bytesToWrite.Length).ToArray()); } private void VerifyBuffer(byte[] actualBuffer, byte[] expectedBuffer, int offset, int count) { // Verify all character before the offset for (var i = 0; i < offset; i++) { if (actualBuffer[i] != expectedBuffer[i]) { Fail("ERROR!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]); } } // Verify all character after the offset + count for (int i = offset + count; i < actualBuffer.Length; i++) { if (actualBuffer[i] != expectedBuffer[i]) { Fail("ERROR!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]); } } } private class CallbackHandler { private IAsyncResult _readAysncResult; private IAsyncResult _beginReadAsyncResult; private readonly SerialPort _com; public CallbackHandler() : this(null) { } public CallbackHandler(SerialPort com) { _com = com; } public void Callback(IAsyncResult readAysncResult) { lock (this) { _readAysncResult = readAysncResult; Assert.True(readAysncResult.IsCompleted, "IAsyncResult passed into callback is not completed"); while (null == _beginReadAsyncResult) { Monitor.Wait(this); } if (null != _beginReadAsyncResult && !_beginReadAsyncResult.IsCompleted) { Fail("Err_7907azpu Expected IAsyncResult returned from begin read to not be completed"); } if (null != _com) { _com.BaseStream.EndRead(_beginReadAsyncResult); if (!_beginReadAsyncResult.IsCompleted) { Fail("Err_6498afead Expected IAsyncResult returned from begin read to not be completed"); } if (!readAysncResult.IsCompleted) { Fail("Err_1398ehpo Expected IAsyncResult passed into callback to not be completed"); } } Monitor.Pulse(this); } } public IAsyncResult ReadAysncResult { get { lock (this) { while (null == _readAysncResult) { Monitor.Wait(this); } return _readAysncResult; } } } public IAsyncResult BeginReadAsyncResult { get { return _beginReadAsyncResult; } set { lock (this) { _beginReadAsyncResult = value; Monitor.Pulse(this); } } } } #endregion } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/Common/src/System/Net/Sockets/SocketType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if SYSTEM_NET_SOCKETS_DLL namespace System.Net.Sockets { public #else namespace System.Net.Internals { internal #endif // Specifies the type of socket an instance of the System.Net.Sockets.Socket class represents. enum SocketType { Stream = 1, // stream socket Dgram = 2, // datagram socket Raw = 3, // raw-protocol interface Rdm = 4, // reliably-delivered message Seqpacket = 5, // sequenced packet stream Unknown = -1, // Unknown socket type } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if SYSTEM_NET_SOCKETS_DLL namespace System.Net.Sockets { public #else namespace System.Net.Internals { internal #endif // Specifies the type of socket an instance of the System.Net.Sockets.Socket class represents. enum SocketType { Stream = 1, // stream socket Dgram = 2, // datagram socket Raw = 3, // raw-protocol interface Rdm = 4, // reliably-delivered message Seqpacket = 5, // sequenced packet stream Unknown = -1, // Unknown socket type } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/General/Vector256/EqualsAll.UInt64.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 EqualsAllUInt64() { var test = new VectorBooleanBinaryOpTest__EqualsAllUInt64(); // 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__EqualsAllUInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); 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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1; public Vector256<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__EqualsAllUInt64 testClass) { var result = Vector256.EqualsAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector256<UInt64> _clsVar1; private static Vector256<UInt64> _clsVar2; private Vector256<UInt64> _fld1; private Vector256<UInt64> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__EqualsAllUInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); } public VectorBooleanBinaryOpTest__EqualsAllUInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.EqualsAll( Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_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.EqualsAll), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.EqualsAll), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt64)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.EqualsAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr); var result = Vector256.EqualsAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__EqualsAllUInt64(); var result = Vector256.EqualsAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.EqualsAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.EqualsAll(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<UInt64> op1, Vector256<UInt64> op2, bool result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt64[] left, UInt64[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] == right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.EqualsAll)}<UInt64>(Vector256<UInt64>, Vector256<UInt64>): {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 EqualsAllUInt64() { var test = new VectorBooleanBinaryOpTest__EqualsAllUInt64(); // 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__EqualsAllUInt64 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); 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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1; public Vector256<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__EqualsAllUInt64 testClass) { var result = Vector256.EqualsAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector256<UInt64> _clsVar1; private static Vector256<UInt64> _clsVar2; private Vector256<UInt64> _fld1; private Vector256<UInt64> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__EqualsAllUInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); } public VectorBooleanBinaryOpTest__EqualsAllUInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.EqualsAll( Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_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.EqualsAll), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.EqualsAll), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt64)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.EqualsAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr); var result = Vector256.EqualsAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__EqualsAllUInt64(); var result = Vector256.EqualsAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.EqualsAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.EqualsAll(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<UInt64> op1, Vector256<UInt64> op2, bool result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt64>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt64[] left, UInt64[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] == right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.EqualsAll)}<UInt64>(Vector256<UInt64>, Vector256<UInt64>): {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,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/General/Vector128_1/op_BitwiseAnd.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 op_BitwiseAndInt16() { var test = new VectorBinaryOpTest__op_BitwiseAndInt16(); // 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_BitwiseAndInt16 { 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 != 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<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 Vector128<Int16> _fld1; public Vector128<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<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_BitwiseAndInt16 testClass) { var result = _fld1 & _fld2; 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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_BitwiseAndInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public VectorBinaryOpTest__op_BitwiseAndInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr) & Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector128<Int16>).GetMethod("op_BitwiseAnd", new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(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<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_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_BitwiseAndInt16(); 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(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (short)(left[0] & right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (short)(left[i] & right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_BitwiseAnd<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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_BitwiseAndInt16() { var test = new VectorBinaryOpTest__op_BitwiseAndInt16(); // 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_BitwiseAndInt16 { 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 != 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<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 Vector128<Int16> _fld1; public Vector128<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<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_BitwiseAndInt16 testClass) { var result = _fld1 & _fld2; 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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_BitwiseAndInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public VectorBinaryOpTest__op_BitwiseAndInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr) & Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector128<Int16>).GetMethod("op_BitwiseAnd", new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(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<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_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_BitwiseAndInt16(); 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(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (short)(left[0] & right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (short)(left[i] & right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_BitwiseAnd<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/installer/tests/Assets/TestProjects/StartupHookWithoutStartupHookType/StartupHookWithoutStartupHookType.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 StartupHookWrongType { public static void Initialize() { // This hook should not be called because it doesn't have the // correct type name (StartupHook). Instead, the startup hook // provider code should throw an exception. Console.WriteLine("Hello from startup hook!"); } }
// 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 StartupHookWrongType { public static void Initialize() { // This hook should not be called because it doesn't have the // correct type name (StartupHook). Instead, the startup hook // provider code should throw an exception. Console.WriteLine("Hello from startup hook!"); } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.IO.FileSystem/tests/Enumeration/SymbolicLinksTests.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.IO.Enumeration; using System.Linq; using Xunit; namespace System.IO.Tests.Enumeration { [ConditionalClass(typeof(MountHelper), nameof(MountHelper.CanCreateSymbolicLinks))] public class Enumeration_SymbolicLinksTests : BaseSymbolicLinks { [Fact] public void EnumerateDirectories_LinksWithCycles_ShouldNotThrow() { DirectoryInfo testDirectory = CreateDirectoryContainingSelfReferencingSymbolicLink(); IEnumerable<string> enumerable = new FileSystemEnumerable<string>( testDirectory.FullName, (ref FileSystemEntry entry) => entry.ToFullPath(), // Skipping attributes would force a disk hit which enters the cyclic symlink new EnumerationOptions(){ AttributesToSkip = 0 }) { ShouldIncludePredicate = (ref FileSystemEntry entry) => entry.IsDirectory }; // Windows differentiates between dir symlinks and file symlinks int expected = OperatingSystem.IsWindows() ? 1 : 0; Assert.Equal(expected, enumerable.Count()); } [Fact] public void EnumerateFiles_LinksWithCycles_ShouldNotThrow() { DirectoryInfo testDirectory = CreateDirectoryContainingSelfReferencingSymbolicLink(); IEnumerable<string> enumerable = new FileSystemEnumerable<string>( testDirectory.FullName, (ref FileSystemEntry entry) => entry.ToFullPath(), // Skipping attributes would force a disk hit which enters the cyclic symlink new EnumerationOptions(){ AttributesToSkip = 0 }) { ShouldIncludePredicate = (ref FileSystemEntry entry) => !entry.IsDirectory }; // Windows differentiates between dir symlinks and file symlinks int expected = OperatingSystem.IsWindows() ? 0 : 1; Assert.Equal(expected, enumerable.Count()); } [Fact] public void EnumerateFileSystemEntries_LinksWithCycles_ShouldNotThrow() { DirectoryInfo testDirectory = CreateDirectoryContainingSelfReferencingSymbolicLink(); IEnumerable<string> enumerable = new FileSystemEnumerable<string>( testDirectory.FullName, (ref FileSystemEntry entry) => entry.ToFullPath(), // Skipping attributes would force a disk hit which enters the cyclic symlink new EnumerationOptions(){ AttributesToSkip = 0 }); Assert.Single(enumerable); } [Theory] [InlineData(false, false)] // OK [InlineData(false, true)] // throw [InlineData(true, false)] // throw, OK on Unix [InlineData(true, true)] // throw public void EnumerateGet_SelfReferencingLink_Instance(bool recurse, bool linkAsRoot) { var options = new EnumerationOptions() { RecurseSubdirectories = recurse }; DirectoryInfo testDirectory = linkAsRoot ? CreateSelfReferencingSymbolicLink() : CreateDirectoryContainingSelfReferencingSymbolicLink(); // Unix doesn't have a problem when it steps in a self-referencing link through the directory recursion. if ((!recurse || !OperatingSystem.IsWindows()) && !linkAsRoot) { testDirectory.EnumerateFileSystemInfos("*", options).Count(); testDirectory.GetFileSystemInfos("*", options).Count(); testDirectory.EnumerateDirectories("*", options).Count(); testDirectory.GetDirectories("*", options).Count(); testDirectory.EnumerateFiles("*", options).Count(); testDirectory.GetFiles("*", options).Count(); } else { Assert.Throws<IOException>(() => testDirectory.EnumerateFileSystemInfos("*", options).Count()); Assert.Throws<IOException>(() => testDirectory.GetFileSystemInfos("*", options).Count()); Assert.Throws<IOException>(() => testDirectory.EnumerateDirectories("*", options).Count()); Assert.Throws<IOException>(() => testDirectory.GetDirectories("*", options).Count()); Assert.Throws<IOException>(() => testDirectory.EnumerateFiles("*", options).Count()); Assert.Throws<IOException>(() => testDirectory.GetFiles("*", options).Count()); } } [Theory] [InlineData(false, false)] // OK [InlineData(false, true)] // throw [InlineData(true, false)] // throw, OK on Unix [InlineData(true, true)] // throw public void EnumerateGet_SelfReferencingLink_Static(bool recurse, bool linkAsRoot) { var options = new EnumerationOptions() { RecurseSubdirectories = recurse }; DirectoryInfo testDirectory = linkAsRoot ? CreateSelfReferencingSymbolicLink() : CreateDirectoryContainingSelfReferencingSymbolicLink(); // Unix doesn't have a problem when it steps in a self-referencing link through the directory recursion. if ((!recurse || !OperatingSystem.IsWindows()) && !linkAsRoot) { Directory.EnumerateFileSystemEntries(testDirectory.FullName, "*", options).Count(); Directory.GetFileSystemEntries(testDirectory.FullName, "*", options).Count(); Directory.EnumerateDirectories(testDirectory.FullName, "*", options).Count(); Directory.GetDirectories(testDirectory.FullName, "*", options).Count(); Directory.EnumerateFiles(testDirectory.FullName, "*", options).Count(); Directory.GetFiles(testDirectory.FullName, "*", options).Count(); } else { Assert.Throws<IOException>(() => Directory.EnumerateFileSystemEntries(testDirectory.FullName, "*", options).Count()); Assert.Throws<IOException>(() => Directory.GetFileSystemEntries(testDirectory.FullName, "*", options).Count()); Assert.Throws<IOException>(() => Directory.EnumerateDirectories(testDirectory.FullName, "*", options).Count()); Assert.Throws<IOException>(() => Directory.GetDirectories(testDirectory.FullName, "*", options).Count()); Assert.Throws<IOException>(() => Directory.EnumerateFiles(testDirectory.FullName, "*", options).Count()); Assert.Throws<IOException>(() => Directory.GetFiles(testDirectory.FullName, "*", options).Count()); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser)] public void PropertiesArePopulatedLazily() { Assert.True(Directory.EnumerateFileSystemEntries("/dev/fd").Count() >= 0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO.Enumeration; using System.Linq; using Xunit; namespace System.IO.Tests.Enumeration { [ConditionalClass(typeof(MountHelper), nameof(MountHelper.CanCreateSymbolicLinks))] public class Enumeration_SymbolicLinksTests : BaseSymbolicLinks { [Fact] public void EnumerateDirectories_LinksWithCycles_ShouldNotThrow() { DirectoryInfo testDirectory = CreateDirectoryContainingSelfReferencingSymbolicLink(); IEnumerable<string> enumerable = new FileSystemEnumerable<string>( testDirectory.FullName, (ref FileSystemEntry entry) => entry.ToFullPath(), // Skipping attributes would force a disk hit which enters the cyclic symlink new EnumerationOptions(){ AttributesToSkip = 0 }) { ShouldIncludePredicate = (ref FileSystemEntry entry) => entry.IsDirectory }; // Windows differentiates between dir symlinks and file symlinks int expected = OperatingSystem.IsWindows() ? 1 : 0; Assert.Equal(expected, enumerable.Count()); } [Fact] public void EnumerateFiles_LinksWithCycles_ShouldNotThrow() { DirectoryInfo testDirectory = CreateDirectoryContainingSelfReferencingSymbolicLink(); IEnumerable<string> enumerable = new FileSystemEnumerable<string>( testDirectory.FullName, (ref FileSystemEntry entry) => entry.ToFullPath(), // Skipping attributes would force a disk hit which enters the cyclic symlink new EnumerationOptions(){ AttributesToSkip = 0 }) { ShouldIncludePredicate = (ref FileSystemEntry entry) => !entry.IsDirectory }; // Windows differentiates between dir symlinks and file symlinks int expected = OperatingSystem.IsWindows() ? 0 : 1; Assert.Equal(expected, enumerable.Count()); } [Fact] public void EnumerateFileSystemEntries_LinksWithCycles_ShouldNotThrow() { DirectoryInfo testDirectory = CreateDirectoryContainingSelfReferencingSymbolicLink(); IEnumerable<string> enumerable = new FileSystemEnumerable<string>( testDirectory.FullName, (ref FileSystemEntry entry) => entry.ToFullPath(), // Skipping attributes would force a disk hit which enters the cyclic symlink new EnumerationOptions(){ AttributesToSkip = 0 }); Assert.Single(enumerable); } [Theory] [InlineData(false, false)] // OK [InlineData(false, true)] // throw [InlineData(true, false)] // throw, OK on Unix [InlineData(true, true)] // throw public void EnumerateGet_SelfReferencingLink_Instance(bool recurse, bool linkAsRoot) { var options = new EnumerationOptions() { RecurseSubdirectories = recurse }; DirectoryInfo testDirectory = linkAsRoot ? CreateSelfReferencingSymbolicLink() : CreateDirectoryContainingSelfReferencingSymbolicLink(); // Unix doesn't have a problem when it steps in a self-referencing link through the directory recursion. if ((!recurse || !OperatingSystem.IsWindows()) && !linkAsRoot) { testDirectory.EnumerateFileSystemInfos("*", options).Count(); testDirectory.GetFileSystemInfos("*", options).Count(); testDirectory.EnumerateDirectories("*", options).Count(); testDirectory.GetDirectories("*", options).Count(); testDirectory.EnumerateFiles("*", options).Count(); testDirectory.GetFiles("*", options).Count(); } else { Assert.Throws<IOException>(() => testDirectory.EnumerateFileSystemInfos("*", options).Count()); Assert.Throws<IOException>(() => testDirectory.GetFileSystemInfos("*", options).Count()); Assert.Throws<IOException>(() => testDirectory.EnumerateDirectories("*", options).Count()); Assert.Throws<IOException>(() => testDirectory.GetDirectories("*", options).Count()); Assert.Throws<IOException>(() => testDirectory.EnumerateFiles("*", options).Count()); Assert.Throws<IOException>(() => testDirectory.GetFiles("*", options).Count()); } } [Theory] [InlineData(false, false)] // OK [InlineData(false, true)] // throw [InlineData(true, false)] // throw, OK on Unix [InlineData(true, true)] // throw public void EnumerateGet_SelfReferencingLink_Static(bool recurse, bool linkAsRoot) { var options = new EnumerationOptions() { RecurseSubdirectories = recurse }; DirectoryInfo testDirectory = linkAsRoot ? CreateSelfReferencingSymbolicLink() : CreateDirectoryContainingSelfReferencingSymbolicLink(); // Unix doesn't have a problem when it steps in a self-referencing link through the directory recursion. if ((!recurse || !OperatingSystem.IsWindows()) && !linkAsRoot) { Directory.EnumerateFileSystemEntries(testDirectory.FullName, "*", options).Count(); Directory.GetFileSystemEntries(testDirectory.FullName, "*", options).Count(); Directory.EnumerateDirectories(testDirectory.FullName, "*", options).Count(); Directory.GetDirectories(testDirectory.FullName, "*", options).Count(); Directory.EnumerateFiles(testDirectory.FullName, "*", options).Count(); Directory.GetFiles(testDirectory.FullName, "*", options).Count(); } else { Assert.Throws<IOException>(() => Directory.EnumerateFileSystemEntries(testDirectory.FullName, "*", options).Count()); Assert.Throws<IOException>(() => Directory.GetFileSystemEntries(testDirectory.FullName, "*", options).Count()); Assert.Throws<IOException>(() => Directory.EnumerateDirectories(testDirectory.FullName, "*", options).Count()); Assert.Throws<IOException>(() => Directory.GetDirectories(testDirectory.FullName, "*", options).Count()); Assert.Throws<IOException>(() => Directory.EnumerateFiles(testDirectory.FullName, "*", options).Count()); Assert.Throws<IOException>(() => Directory.GetFiles(testDirectory.FullName, "*", options).Count()); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser)] public void PropertiesArePopulatedLazily() { Assert.True(Directory.EnumerateFileSystemEntries("/dev/fd").Count() >= 0); } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftLogicalRoundedSaturate.Vector128.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.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 ShiftLogicalRoundedSaturate_Vector128_SByte() { var test = new SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte(); 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__ShiftLogicalRoundedSaturate_Vector128_SByte { 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(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); 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<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* 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<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(SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte testClass) { var result = AdvSimd.ShiftLogicalRoundedSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(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<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = 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 SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte() { 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 SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte() { 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, new SByte[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.ShiftLogicalRoundedSaturate( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_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.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_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.ShiftLogicalRoundedSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(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.ShiftLogicalRoundedSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLogicalRoundedSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(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<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftLogicalRoundedSaturate(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((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftLogicalRoundedSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte(); var result = AdvSimd.ShiftLogicalRoundedSaturate(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__ShiftLogicalRoundedSaturate_Vector128_SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLogicalRoundedSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(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.ShiftLogicalRoundedSaturate(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.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&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<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; 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>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLogicalRoundedSaturate(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLogicalRoundedSaturate)}<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: ({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 ShiftLogicalRoundedSaturate_Vector128_SByte() { var test = new SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte(); 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__ShiftLogicalRoundedSaturate_Vector128_SByte { 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(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); 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<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* 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<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(SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte testClass) { var result = AdvSimd.ShiftLogicalRoundedSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(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<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = 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 SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte() { 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 SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte() { 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, new SByte[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.ShiftLogicalRoundedSaturate( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_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.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_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.ShiftLogicalRoundedSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(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.ShiftLogicalRoundedSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLogicalRoundedSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(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<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftLogicalRoundedSaturate(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((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftLogicalRoundedSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShiftLogicalRoundedSaturate_Vector128_SByte(); var result = AdvSimd.ShiftLogicalRoundedSaturate(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__ShiftLogicalRoundedSaturate_Vector128_SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLogicalRoundedSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(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.ShiftLogicalRoundedSaturate(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.ShiftLogicalRoundedSaturate( AdvSimd.LoadVector128((SByte*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&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<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; 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>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLogicalRoundedSaturate(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLogicalRoundedSaturate)}<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: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/op_Equality.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_EqualityByte() { var test = new VectorBooleanBinaryOpTest__op_EqualityByte(); // 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__op_EqualityByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Byte> _fld1; public Vector64<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__op_EqualityByte testClass) { var result = _fld1 == _fld2; testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector64<Byte> _clsVar1; private static Vector64<Byte> _clsVar2; private Vector64<Byte> _fld1; private Vector64<Byte> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__op_EqualityByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); } public VectorBooleanBinaryOpTest__op_EqualityByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr) == Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector64<Byte>).GetMethod("op_Equality", new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _clsVar1 == _clsVar2; ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); var result = op1 == op2; ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__op_EqualityByte(); var result = test._fld1 == test._fld2; ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = _fld1 == _fld2; ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = 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(Vector64<Byte> op1, Vector64<Byte> op2, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] == right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_Equality<Byte>(Vector64<Byte>, Vector64<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_EqualityByte() { var test = new VectorBooleanBinaryOpTest__op_EqualityByte(); // 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__op_EqualityByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Byte> _fld1; public Vector64<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__op_EqualityByte testClass) { var result = _fld1 == _fld2; testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector64<Byte> _clsVar1; private static Vector64<Byte> _clsVar2; private Vector64<Byte> _fld1; private Vector64<Byte> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__op_EqualityByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); } public VectorBooleanBinaryOpTest__op_EqualityByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr) == Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector64<Byte>).GetMethod("op_Equality", new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _clsVar1 == _clsVar2; ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); var result = op1 == op2; ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__op_EqualityByte(); var result = test._fld1 == test._fld2; ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = _fld1 == _fld2; ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = 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(Vector64<Byte> op1, Vector64<Byte> op2, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] == right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.op_Equality<Byte>(Vector64<Byte>, Vector64<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Methodical/explicit/rotate/rotarg_valref_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="rotarg_valref.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="rotarg_valref.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.IO.Hashing/src/System/IO/Hashing/BitOperations.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; namespace System.Numerics { internal static class BitOperations { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint RotateLeft(uint value, int offset) => (value << offset) | (value >> (32 - offset)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong RotateLeft(ulong value, int offset) => (value << offset) | (value >> (64 - offset)); } }
// 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; namespace System.Numerics { internal static class BitOperations { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint RotateLeft(uint value, int offset) => (value << offset) | (value >> (32 - offset)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong RotateLeft(ulong value, int offset) => (value << offset) | (value >> (64 - offset)); } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Private.Xml/tests/XmlReader/ReadContentAs/ReadAsCharTests.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.Xml.Tests { public class CharTests { [Fact] public static void ReadContentAsChar1() { var reader = Utils.CreateFragmentReader("<a>2000-02-29T23:59:59+13:60</a>"); reader.PositionOnElement("a"); reader.Read(); Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(char), null)); } } }
// 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.Xml.Tests { public class CharTests { [Fact] public static void ReadContentAsChar1() { var reader = Utils.CreateFragmentReader("<a>2000-02-29T23:59:59+13:60</a>"); reader.PositionOnElement("a"); reader.Read(); Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(char), null)); } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/Interop/PInvoke/Array/MarshalArrayAsField/AsLPArray/AsLPArrayTest.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="*.cs" /> </ItemGroup> <ItemGroup> <CMakeProjectReference Include="..\LPArrayNative\CMakeLists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="*.cs" /> </ItemGroup> <ItemGroup> <CMakeProjectReference Include="..\LPArrayNative\CMakeLists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/coreclr/tools/Common/TypeSystem/IL/CoreRTILProvider.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 Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.IL.Stubs; using Debug = System.Diagnostics.Debug; namespace Internal.IL { public sealed class CoreRTILProvider : ILProvider { private MethodIL TryGetRuntimeImplementedMethodIL(MethodDesc method) { // Provides method bodies for runtime implemented methods. It can return null for // methods that are treated specially by the codegen. Debug.Assert(method.IsRuntimeImplemented); TypeDesc owningType = method.OwningType; if (owningType.IsDelegate) { return DelegateMethodILEmitter.EmitIL(method); } return null; } /// <summary> /// Provides method bodies for intrinsics recognized by the compiler. /// It can return null if it's not an intrinsic recognized by the compiler, /// but an intrinsic e.g. recognized by codegen. /// </summary> private MethodIL TryGetIntrinsicMethodIL(MethodDesc method) { Debug.Assert(method.IsIntrinsic); MetadataType owningType = method.OwningType as MetadataType; if (owningType == null) return null; switch (owningType.Name) { case "Interlocked": { if (owningType.Namespace == "System.Threading") return InterlockedIntrinsics.EmitIL(method); } break; case "Unsafe": { if (owningType.Namespace == "System.Runtime.CompilerServices") return UnsafeIntrinsics.EmitIL(method); } break; case "MemoryMarshal": { if (owningType.Namespace == "System.Runtime.InteropServices") return MemoryMarshalIntrinsics.EmitIL(method); } break; case "Volatile": { if (owningType.Namespace == "System.Threading") return VolatileIntrinsics.EmitIL(method); } break; case "Debug": { if (owningType.Namespace == "System.Diagnostics" && method.Name == "DebugBreak") return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.break_, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null); } break; case "RuntimeAugments": { if (owningType.Namespace == "Internal.Runtime.Augments" && method.Name == "GetCanonType") return GetCanonTypeIntrinsic.EmitIL(method); } break; case "MethodTable": { if (owningType.Namespace == "Internal.Runtime" && method.Name == "get_SupportsRelativePointers") { ILOpcode value = method.Context.Target.SupportsRelativePointers ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0; return new ILStubMethodIL(method, new byte[] { (byte)value, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null); } } break; } return null; } /// <summary> /// Provides method bodies for intrinsics recognized by the compiler that /// are specialized per instantiation. It can return null if the intrinsic /// is not recognized. /// </summary> private MethodIL TryGetPerInstantiationIntrinsicMethodIL(MethodDesc method) { Debug.Assert(method.IsIntrinsic); MetadataType owningType = method.OwningType.GetTypeDefinition() as MetadataType; if (owningType == null) return null; string methodName = method.Name; switch (owningType.Name) { case "Activator": { TypeSystemContext context = owningType.Context; if (methodName == "CreateInstance" && method.Signature.Length == 0 && method.HasInstantiation && method.Instantiation[0] is TypeDesc activatedType && activatedType != context.UniversalCanonType && activatedType.IsValueType && activatedType.GetParameterlessConstructor() == null) { ILEmitter emit = new ILEmitter(); ILCodeStream codeStream = emit.NewCodeStream(); var t = emit.NewLocal(context.GetSignatureVariable(0, method: true)); codeStream.EmitLdLoca(t); codeStream.Emit(ILOpcode.initobj, emit.NewToken(context.GetSignatureVariable(0, method: true))); codeStream.EmitLdLoc(t); codeStream.Emit(ILOpcode.ret); return new InstantiatedMethodIL(method, emit.Link(method.GetMethodDefinition())); } } break; case "RuntimeHelpers": { if (owningType.Namespace == "System.Runtime.CompilerServices") return RuntimeHelpersIntrinsics.EmitIL(method); } break; case "Comparer`1": { if (methodName == "Create" && owningType.Namespace == "System.Collections.Generic") return ComparerIntrinsics.EmitComparerCreate(method); } break; case "EqualityComparer`1": { if (methodName == "Create" && owningType.Namespace == "System.Collections.Generic") return ComparerIntrinsics.EmitEqualityComparerCreate(method); } break; case "ComparerHelpers": { if (owningType.Namespace != "Internal.IntrinsicSupport") return null; if (methodName == "EnumOnlyCompare") { //calls CompareTo for underlyingType to avoid boxing TypeDesc elementType = method.Instantiation[0]; if (!elementType.IsEnum) return null; TypeDesc underlyingType = elementType.UnderlyingType; TypeDesc returnType = method.Context.GetWellKnownType(WellKnownType.Int32); MethodDesc underlyingCompareToMethod = underlyingType.GetKnownMethod("CompareTo", new MethodSignature( MethodSignatureFlags.None, genericParameterCount: 0, returnType: returnType, parameters: new TypeDesc[] {underlyingType})); ILEmitter emitter = new ILEmitter(); var codeStream = emitter.NewCodeStream(); codeStream.EmitLdArga(0); codeStream.EmitLdArg(1); codeStream.Emit(ILOpcode.call, emitter.NewToken(underlyingCompareToMethod)); codeStream.Emit(ILOpcode.ret); return emitter.Link(method); } } break; case "EqualityComparerHelpers": { if (owningType.Namespace != "Internal.IntrinsicSupport") return null; if (methodName == "EnumOnlyEquals") { // EnumOnlyEquals would basically like to do this: // static bool EnumOnlyEquals<T>(T x, T y) where T: struct => x == y; // This is not legal though. // We don't want to do this: // static bool EnumOnlyEquals<T>(T x, T y) where T: struct => x.Equals(y); // Because it would box y. // So we resort to some per-instantiation magic. TypeDesc elementType = method.Instantiation[0]; if (!elementType.IsEnum) return null; ILOpcode convInstruction; if (((DefType)elementType).InstanceFieldSize.AsInt <= 4) { convInstruction = ILOpcode.conv_i4; } else { Debug.Assert(((DefType)elementType).InstanceFieldSize.AsInt == 8); convInstruction = ILOpcode.conv_i8; } return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.ldarg_0, (byte)convInstruction, (byte)ILOpcode.ldarg_1, (byte)convInstruction, (byte)ILOpcode.prefix1, unchecked((byte)ILOpcode.ceq), (byte)ILOpcode.ret, }, Array.Empty<LocalVariableDefinition>(), null); } else if (methodName == "GetComparerForReferenceTypesOnly") { TypeDesc elementType = method.Instantiation[0]; if (!elementType.IsRuntimeDeterminedSubtype && !elementType.IsCanonicalSubtype(CanonicalFormKind.Any) && !elementType.IsGCPointer) { return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.ldnull, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null); } } else if (methodName == "StructOnlyEquals") { TypeDesc elementType = method.Instantiation[0]; if (!elementType.IsRuntimeDeterminedSubtype && !elementType.IsCanonicalSubtype(CanonicalFormKind.Any) && !elementType.IsGCPointer) { Debug.Assert(elementType.IsValueType); TypeSystemContext context = elementType.Context; MetadataType helperType = context.SystemModule.GetKnownType("Internal.IntrinsicSupport", "EqualityComparerHelpers"); MethodDesc methodToCall; if (elementType.IsEnum) { methodToCall = helperType.GetKnownMethod("EnumOnlyEquals", null).MakeInstantiatedMethod(elementType); } else if (elementType.IsNullable && ComparerIntrinsics.ImplementsIEquatable(elementType.Instantiation[0])) { methodToCall = helperType.GetKnownMethod("StructOnlyEqualsNullable", null).MakeInstantiatedMethod(elementType.Instantiation[0]); } else if (ComparerIntrinsics.ImplementsIEquatable(elementType)) { methodToCall = helperType.GetKnownMethod("StructOnlyEqualsIEquatable", null).MakeInstantiatedMethod(elementType); } else { methodToCall = helperType.GetKnownMethod("StructOnlyNormalEquals", null).MakeInstantiatedMethod(elementType); } return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.ldarg_0, (byte)ILOpcode.ldarg_1, (byte)ILOpcode.call, 1, 0, 0, 0, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), new object[] { methodToCall }); } } } break; } return null; } public override MethodIL GetMethodIL(MethodDesc method) { if (method is EcmaMethod ecmaMethod) { if (ecmaMethod.IsIntrinsic) { MethodIL result = TryGetIntrinsicMethodIL(ecmaMethod); if (result != null) return result; } if (ecmaMethod.IsRuntimeImplemented) { MethodIL result = TryGetRuntimeImplementedMethodIL(ecmaMethod); if (result != null) return result; } MethodIL methodIL = EcmaMethodIL.Create(ecmaMethod); if (methodIL != null) return methodIL; return null; } else if (method is MethodForInstantiatedType || method is InstantiatedMethod) { // Intrinsics specialized per instantiation if (method.IsIntrinsic) { MethodIL methodIL = TryGetPerInstantiationIntrinsicMethodIL(method); if (methodIL != null) return methodIL; } var methodDefinitionIL = GetMethodIL(method.GetTypicalMethodDefinition()); if (methodDefinitionIL == null) return null; return new InstantiatedMethodIL(method, methodDefinitionIL); } else if (method is ILStubMethod) { return ((ILStubMethod)method).EmitIL(); } else if (method is ArrayMethod) { return ArrayMethodILEmitter.EmitIL((ArrayMethod)method); } else { Debug.Assert(!(method is PInvokeTargetNativeMethod), "Who is asking for IL of PInvokeTargetNativeMethod?"); 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 Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.IL.Stubs; using Debug = System.Diagnostics.Debug; namespace Internal.IL { public sealed class CoreRTILProvider : ILProvider { private MethodIL TryGetRuntimeImplementedMethodIL(MethodDesc method) { // Provides method bodies for runtime implemented methods. It can return null for // methods that are treated specially by the codegen. Debug.Assert(method.IsRuntimeImplemented); TypeDesc owningType = method.OwningType; if (owningType.IsDelegate) { return DelegateMethodILEmitter.EmitIL(method); } return null; } /// <summary> /// Provides method bodies for intrinsics recognized by the compiler. /// It can return null if it's not an intrinsic recognized by the compiler, /// but an intrinsic e.g. recognized by codegen. /// </summary> private MethodIL TryGetIntrinsicMethodIL(MethodDesc method) { Debug.Assert(method.IsIntrinsic); MetadataType owningType = method.OwningType as MetadataType; if (owningType == null) return null; switch (owningType.Name) { case "Interlocked": { if (owningType.Namespace == "System.Threading") return InterlockedIntrinsics.EmitIL(method); } break; case "Unsafe": { if (owningType.Namespace == "System.Runtime.CompilerServices") return UnsafeIntrinsics.EmitIL(method); } break; case "MemoryMarshal": { if (owningType.Namespace == "System.Runtime.InteropServices") return MemoryMarshalIntrinsics.EmitIL(method); } break; case "Volatile": { if (owningType.Namespace == "System.Threading") return VolatileIntrinsics.EmitIL(method); } break; case "Debug": { if (owningType.Namespace == "System.Diagnostics" && method.Name == "DebugBreak") return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.break_, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null); } break; case "RuntimeAugments": { if (owningType.Namespace == "Internal.Runtime.Augments" && method.Name == "GetCanonType") return GetCanonTypeIntrinsic.EmitIL(method); } break; case "MethodTable": { if (owningType.Namespace == "Internal.Runtime" && method.Name == "get_SupportsRelativePointers") { ILOpcode value = method.Context.Target.SupportsRelativePointers ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0; return new ILStubMethodIL(method, new byte[] { (byte)value, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null); } } break; } return null; } /// <summary> /// Provides method bodies for intrinsics recognized by the compiler that /// are specialized per instantiation. It can return null if the intrinsic /// is not recognized. /// </summary> private MethodIL TryGetPerInstantiationIntrinsicMethodIL(MethodDesc method) { Debug.Assert(method.IsIntrinsic); MetadataType owningType = method.OwningType.GetTypeDefinition() as MetadataType; if (owningType == null) return null; string methodName = method.Name; switch (owningType.Name) { case "Activator": { TypeSystemContext context = owningType.Context; if (methodName == "CreateInstance" && method.Signature.Length == 0 && method.HasInstantiation && method.Instantiation[0] is TypeDesc activatedType && activatedType != context.UniversalCanonType && activatedType.IsValueType && activatedType.GetParameterlessConstructor() == null) { ILEmitter emit = new ILEmitter(); ILCodeStream codeStream = emit.NewCodeStream(); var t = emit.NewLocal(context.GetSignatureVariable(0, method: true)); codeStream.EmitLdLoca(t); codeStream.Emit(ILOpcode.initobj, emit.NewToken(context.GetSignatureVariable(0, method: true))); codeStream.EmitLdLoc(t); codeStream.Emit(ILOpcode.ret); return new InstantiatedMethodIL(method, emit.Link(method.GetMethodDefinition())); } } break; case "RuntimeHelpers": { if (owningType.Namespace == "System.Runtime.CompilerServices") return RuntimeHelpersIntrinsics.EmitIL(method); } break; case "Comparer`1": { if (methodName == "Create" && owningType.Namespace == "System.Collections.Generic") return ComparerIntrinsics.EmitComparerCreate(method); } break; case "EqualityComparer`1": { if (methodName == "Create" && owningType.Namespace == "System.Collections.Generic") return ComparerIntrinsics.EmitEqualityComparerCreate(method); } break; case "ComparerHelpers": { if (owningType.Namespace != "Internal.IntrinsicSupport") return null; if (methodName == "EnumOnlyCompare") { //calls CompareTo for underlyingType to avoid boxing TypeDesc elementType = method.Instantiation[0]; if (!elementType.IsEnum) return null; TypeDesc underlyingType = elementType.UnderlyingType; TypeDesc returnType = method.Context.GetWellKnownType(WellKnownType.Int32); MethodDesc underlyingCompareToMethod = underlyingType.GetKnownMethod("CompareTo", new MethodSignature( MethodSignatureFlags.None, genericParameterCount: 0, returnType: returnType, parameters: new TypeDesc[] {underlyingType})); ILEmitter emitter = new ILEmitter(); var codeStream = emitter.NewCodeStream(); codeStream.EmitLdArga(0); codeStream.EmitLdArg(1); codeStream.Emit(ILOpcode.call, emitter.NewToken(underlyingCompareToMethod)); codeStream.Emit(ILOpcode.ret); return emitter.Link(method); } } break; case "EqualityComparerHelpers": { if (owningType.Namespace != "Internal.IntrinsicSupport") return null; if (methodName == "EnumOnlyEquals") { // EnumOnlyEquals would basically like to do this: // static bool EnumOnlyEquals<T>(T x, T y) where T: struct => x == y; // This is not legal though. // We don't want to do this: // static bool EnumOnlyEquals<T>(T x, T y) where T: struct => x.Equals(y); // Because it would box y. // So we resort to some per-instantiation magic. TypeDesc elementType = method.Instantiation[0]; if (!elementType.IsEnum) return null; ILOpcode convInstruction; if (((DefType)elementType).InstanceFieldSize.AsInt <= 4) { convInstruction = ILOpcode.conv_i4; } else { Debug.Assert(((DefType)elementType).InstanceFieldSize.AsInt == 8); convInstruction = ILOpcode.conv_i8; } return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.ldarg_0, (byte)convInstruction, (byte)ILOpcode.ldarg_1, (byte)convInstruction, (byte)ILOpcode.prefix1, unchecked((byte)ILOpcode.ceq), (byte)ILOpcode.ret, }, Array.Empty<LocalVariableDefinition>(), null); } else if (methodName == "GetComparerForReferenceTypesOnly") { TypeDesc elementType = method.Instantiation[0]; if (!elementType.IsRuntimeDeterminedSubtype && !elementType.IsCanonicalSubtype(CanonicalFormKind.Any) && !elementType.IsGCPointer) { return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.ldnull, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null); } } else if (methodName == "StructOnlyEquals") { TypeDesc elementType = method.Instantiation[0]; if (!elementType.IsRuntimeDeterminedSubtype && !elementType.IsCanonicalSubtype(CanonicalFormKind.Any) && !elementType.IsGCPointer) { Debug.Assert(elementType.IsValueType); TypeSystemContext context = elementType.Context; MetadataType helperType = context.SystemModule.GetKnownType("Internal.IntrinsicSupport", "EqualityComparerHelpers"); MethodDesc methodToCall; if (elementType.IsEnum) { methodToCall = helperType.GetKnownMethod("EnumOnlyEquals", null).MakeInstantiatedMethod(elementType); } else if (elementType.IsNullable && ComparerIntrinsics.ImplementsIEquatable(elementType.Instantiation[0])) { methodToCall = helperType.GetKnownMethod("StructOnlyEqualsNullable", null).MakeInstantiatedMethod(elementType.Instantiation[0]); } else if (ComparerIntrinsics.ImplementsIEquatable(elementType)) { methodToCall = helperType.GetKnownMethod("StructOnlyEqualsIEquatable", null).MakeInstantiatedMethod(elementType); } else { methodToCall = helperType.GetKnownMethod("StructOnlyNormalEquals", null).MakeInstantiatedMethod(elementType); } return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.ldarg_0, (byte)ILOpcode.ldarg_1, (byte)ILOpcode.call, 1, 0, 0, 0, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), new object[] { methodToCall }); } } } break; } return null; } public override MethodIL GetMethodIL(MethodDesc method) { if (method is EcmaMethod ecmaMethod) { if (ecmaMethod.IsIntrinsic) { MethodIL result = TryGetIntrinsicMethodIL(ecmaMethod); if (result != null) return result; } if (ecmaMethod.IsRuntimeImplemented) { MethodIL result = TryGetRuntimeImplementedMethodIL(ecmaMethod); if (result != null) return result; } MethodIL methodIL = EcmaMethodIL.Create(ecmaMethod); if (methodIL != null) return methodIL; return null; } else if (method is MethodForInstantiatedType || method is InstantiatedMethod) { // Intrinsics specialized per instantiation if (method.IsIntrinsic) { MethodIL methodIL = TryGetPerInstantiationIntrinsicMethodIL(method); if (methodIL != null) return methodIL; } var methodDefinitionIL = GetMethodIL(method.GetTypicalMethodDefinition()); if (methodDefinitionIL == null) return null; return new InstantiatedMethodIL(method, methodDefinitionIL); } else if (method is ILStubMethod) { return ((ILStubMethod)method).EmitIL(); } else if (method is ArrayMethod) { return ArrayMethodILEmitter.EmitIL((ArrayMethod)method); } else { Debug.Assert(!(method is PInvokeTargetNativeMethod), "Who is asking for IL of PInvokeTargetNativeMethod?"); return null; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/Common/src/Interop/Unix/System.Native/Interop.FChMod.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FChMod", SetLastError = true)] internal static partial int FChMod(SafeFileHandle fd, int mode); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FChMod", SetLastError = true)] internal static partial int FChMod(SafeFileHandle fd, int mode); } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/ColorBlend.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.Drawing.Drawing2D { public sealed class ColorBlend { public ColorBlend() { Colors = new Color[1]; Positions = new float[1]; } public ColorBlend(int count) { Colors = new Color[count]; Positions = new float[count]; } public Color[] Colors { get; set; } public float[] Positions { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Drawing.Drawing2D { public sealed class ColorBlend { public ColorBlend() { Colors = new Color[1]; Positions = new float[1]; } public ColorBlend(int count) { Colors = new Color[count]; Positions = new float[count]; } public Color[] Colors { get; set; } public float[] Positions { get; set; } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Methodical/cctor/simple/precise2_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="precise2.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="precise2.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/mono/mono/tests/interface-2.cs
using System; public interface I1 { int M1() { return 100; } } public interface I2 : I1 { int I1.M1() { return 200; } } public interface I3 : I1 { int I1.M1() { return 300; } } public interface I4 : I1 { int I1.M1() { return 400; } } class Test10 : I1, I2, I3, I4 { //void I1.M1() { System.Console.WriteLine("I1.I1.M1"); } public int M1() { return 0; } } public interface I1t { int M1t() { return 100; } } public interface I2t : I1t { int I1t.M1t() { return 200; } } public interface I3t : I1t { int I1t.M1t() { return 300; } } public interface I4t : I1t { int I1t.M1t() { return 400; } } class Test10t : I1t, I2t, I3t, I4t { int I1t.M1t() { return 0; } public int M1t() { return 10; } } public interface IName { string Name { get; } } public interface IOther<T> { T other { get; } string Name { get; } } public class Name1 : IName { public string Name { get { return "ClassName"; } } string IName.Name { get { return "InterfaceName"; } } } public class Name2 : IName, IOther<int> { public string Name { get { return "ClassName"; } } string IName.Name { get { return "InterfaceName"; } } public int other { get { return 43; } } } public class Test { public static int test_0_override() { var name1 = new Name1(); var name2 = new Name2(); IName iName1 = name1; IName iName2 = name2; if (!iName1.Name.Equals("InterfaceName")) return 10; if (!iName2.Name.Equals("InterfaceName")) return 20; if (!name1.Name.Equals("ClassName")) return 30; if (!name2.Name.Equals("ClassName")) return 40; return 0; } public static int test_0_dim_override() { I1 var = new Test10(); if (var.M1() != 0) return var.M1(); I1t var2 = new Test10t(); return var2.M1t(); } public static int Main (string[] args) { return TestDriver.RunTests (typeof (Test), args); } }
using System; public interface I1 { int M1() { return 100; } } public interface I2 : I1 { int I1.M1() { return 200; } } public interface I3 : I1 { int I1.M1() { return 300; } } public interface I4 : I1 { int I1.M1() { return 400; } } class Test10 : I1, I2, I3, I4 { //void I1.M1() { System.Console.WriteLine("I1.I1.M1"); } public int M1() { return 0; } } public interface I1t { int M1t() { return 100; } } public interface I2t : I1t { int I1t.M1t() { return 200; } } public interface I3t : I1t { int I1t.M1t() { return 300; } } public interface I4t : I1t { int I1t.M1t() { return 400; } } class Test10t : I1t, I2t, I3t, I4t { int I1t.M1t() { return 0; } public int M1t() { return 10; } } public interface IName { string Name { get; } } public interface IOther<T> { T other { get; } string Name { get; } } public class Name1 : IName { public string Name { get { return "ClassName"; } } string IName.Name { get { return "InterfaceName"; } } } public class Name2 : IName, IOther<int> { public string Name { get { return "ClassName"; } } string IName.Name { get { return "InterfaceName"; } } public int other { get { return 43; } } } public class Test { public static int test_0_override() { var name1 = new Name1(); var name2 = new Name2(); IName iName1 = name1; IName iName2 = name2; if (!iName1.Name.Equals("InterfaceName")) return 10; if (!iName2.Name.Equals("InterfaceName")) return 20; if (!name1.Name.Equals("ClassName")) return 30; if (!name2.Name.Equals("ClassName")) return 40; return 0; } public static int test_0_dim_override() { I1 var = new Test10(); if (var.M1() != 0) return var.M1(); I1t var2 = new Test10t(); return var2.M1t(); } public static int Main (string[] args) { return TestDriver.RunTests (typeof (Test), args); } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/As.Double.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 AsDouble() { var test = new VectorAs__AsDouble(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // 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 VectorAs__AsDouble { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector64<Double> value; value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector64<Double> value; value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<byte> byteResult = value.As<Double, byte>(); ValidateResult(byteResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<double> doubleResult = value.As<Double, double>(); ValidateResult(doubleResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<short> shortResult = value.As<Double, short>(); ValidateResult(shortResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<int> intResult = value.As<Double, int>(); ValidateResult(intResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<long> longResult = value.As<Double, long>(); ValidateResult(longResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<sbyte> sbyteResult = value.As<Double, sbyte>(); ValidateResult(sbyteResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<float> floatResult = value.As<Double, float>(); ValidateResult(floatResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<ushort> ushortResult = value.As<Double, ushort>(); ValidateResult(ushortResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<uint> uintResult = value.As<Double, uint>(); ValidateResult(uintResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<ulong> ulongResult = value.As<Double, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector64<Double> value; value = Vector64.Create(TestLibrary.Generator.GetDouble()); object byteResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsByte)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<byte>)(byteResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object doubleResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsDouble)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<double>)(doubleResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object shortResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt16)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<short>)(shortResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object intResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt32)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<int>)(intResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object longResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt64)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<long>)(longResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object sbyteResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsSByte)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<sbyte>)(sbyteResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object floatResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsSingle)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<float>)(floatResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object ushortResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt16)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<ushort>)(ushortResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object uintResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt32)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<uint>)(uintResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object ulongResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt64)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector64<T> result, Vector64<Double> value, [CallerMemberName] string method = "") where T : struct { Double[] resultElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result); Double[] valueElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(Double[] resultElements, Double[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Double>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); 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 AsDouble() { var test = new VectorAs__AsDouble(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // 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 VectorAs__AsDouble { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector64<Double> value; value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector64<Double> value; value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<byte> byteResult = value.As<Double, byte>(); ValidateResult(byteResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<double> doubleResult = value.As<Double, double>(); ValidateResult(doubleResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<short> shortResult = value.As<Double, short>(); ValidateResult(shortResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<int> intResult = value.As<Double, int>(); ValidateResult(intResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<long> longResult = value.As<Double, long>(); ValidateResult(longResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<sbyte> sbyteResult = value.As<Double, sbyte>(); ValidateResult(sbyteResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<float> floatResult = value.As<Double, float>(); ValidateResult(floatResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<ushort> ushortResult = value.As<Double, ushort>(); ValidateResult(ushortResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<uint> uintResult = value.As<Double, uint>(); ValidateResult(uintResult, value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); Vector64<ulong> ulongResult = value.As<Double, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector64<Double> value; value = Vector64.Create(TestLibrary.Generator.GetDouble()); object byteResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsByte)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<byte>)(byteResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object doubleResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsDouble)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<double>)(doubleResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object shortResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt16)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<short>)(shortResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object intResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt32)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<int>)(intResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object longResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsInt64)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<long>)(longResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object sbyteResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsSByte)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<sbyte>)(sbyteResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object floatResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsSingle)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<float>)(floatResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object ushortResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt16)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<ushort>)(ushortResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object uintResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt32)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<uint>)(uintResult), value); value = Vector64.Create(TestLibrary.Generator.GetDouble()); object ulongResult = typeof(Vector64) .GetMethod(nameof(Vector64.AsUInt64)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector64<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector64<T> result, Vector64<Double> value, [CallerMemberName] string method = "") where T : struct { Double[] resultElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result); Double[] valueElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(Double[] resultElements, Double[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Double>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/SIMD/AddingSequence_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="AddingSequence.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="AddingSequence.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.OSX.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; namespace System.Net.Security { internal sealed class CipherSuitesPolicyPal { internal uint[] TlsCipherSuites { get; private set; } internal CipherSuitesPolicyPal(IEnumerable<TlsCipherSuite> allowedCipherSuites) { TlsCipherSuites = allowedCipherSuites.Select((cs) => (uint)cs).ToArray(); } internal IEnumerable<TlsCipherSuite> GetCipherSuites() { return TlsCipherSuites.Select((cs) => (TlsCipherSuite)cs); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; namespace System.Net.Security { internal sealed class CipherSuitesPolicyPal { internal uint[] TlsCipherSuites { get; private set; } internal CipherSuitesPolicyPal(IEnumerable<TlsCipherSuite> allowedCipherSuites) { TlsCipherSuites = allowedCipherSuites.Select((cs) => (uint)cs).ToArray(); } internal IEnumerable<TlsCipherSuite> GetCipherSuites() { return TlsCipherSuites.Select((cs) => (TlsCipherSuite)cs); } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Intrinsics/BinaryPrimitivesReverseEndianness_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="BinaryPrimitivesReverseEndianness.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="BinaryPrimitivesReverseEndianness.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreRT.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.Reflection; using System.Runtime.InteropServices; using Internal.Reflection.Augments; // This type is just stubbed out to be harmonious with CoreCLR namespace System.Runtime.Loader { public partial class AssemblyLoadContext { internal static Assembly[] GetLoadedAssemblies() => ReflectionAugments.ReflectionCoreCallbacks.GetLoadedAssemblies(); public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { return Assembly.Load(assemblyName); } private static IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext, bool isCollectible) { return IntPtr.Zero; } private static void PrepareForAssemblyLoadContextRelease(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyLoadContextStrong) { } public static AssemblyLoadContext? GetLoadContext(Assembly assembly) { return Default; } public void SetProfileOptimizationRoot(string directoryPath) { } public void StartProfileOptimization(string profile) { } private Assembly InternalLoadFromPath(string? assemblyPath, string? nativeImagePath) { // TODO: This is not passing down the AssemblyLoadContext, // so it won't actually work properly when multiple assemblies with the same identity get loaded. return ReflectionAugments.ReflectionCoreCallbacks.Load(assemblyPath); } internal Assembly InternalLoad(byte[] arrAssembly, byte[] arrSymbols) { return ReflectionAugments.ReflectionCoreCallbacks.Load(arrAssembly, arrSymbols); } private void ReferenceUnreferencedEvents() { // Dummy method to avoid CS0067 "Event is never used" warning. // These are defined in the shared partition and it's not worth the ifdeffing. _ = AssemblyLoad; _ = ResourceResolve; _ = _resolving; _ = TypeResolve; _ = AssemblyResolve; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using System.Runtime.InteropServices; using Internal.Reflection.Augments; // This type is just stubbed out to be harmonious with CoreCLR namespace System.Runtime.Loader { public partial class AssemblyLoadContext { internal static Assembly[] GetLoadedAssemblies() => ReflectionAugments.ReflectionCoreCallbacks.GetLoadedAssemblies(); public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { return Assembly.Load(assemblyName); } private static IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext, bool isCollectible) { return IntPtr.Zero; } private static void PrepareForAssemblyLoadContextRelease(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyLoadContextStrong) { } public static AssemblyLoadContext? GetLoadContext(Assembly assembly) { return Default; } public void SetProfileOptimizationRoot(string directoryPath) { } public void StartProfileOptimization(string profile) { } private Assembly InternalLoadFromPath(string? assemblyPath, string? nativeImagePath) { // TODO: This is not passing down the AssemblyLoadContext, // so it won't actually work properly when multiple assemblies with the same identity get loaded. return ReflectionAugments.ReflectionCoreCallbacks.Load(assemblyPath); } internal Assembly InternalLoad(byte[] arrAssembly, byte[] arrSymbols) { return ReflectionAugments.ReflectionCoreCallbacks.Load(arrAssembly, arrSymbols); } private void ReferenceUnreferencedEvents() { // Dummy method to avoid CS0067 "Event is never used" warning. // These are defined in the shared partition and it's not worth the ifdeffing. _ = AssemblyLoad; _ = ResourceResolve; _ = _resolving; _ = TypeResolve; _ = AssemblyResolve; } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/ReversedServer/IpcEndpointInfo.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.Diagnostics; namespace Microsoft.Diagnostics.NETCore.Client { /// <summary> /// Represents a runtine instance connection to a reversed diagnostics server. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] internal struct IpcEndpointInfo { internal IpcEndpointInfo(IpcEndpoint endpoint, int processId, Guid runtimeInstanceCookie) { Endpoint = endpoint; ProcessId = processId; RuntimeInstanceCookie = runtimeInstanceCookie; } /// <summary> /// An endpoint used to retrieve diagnostic information from the associated runtime instance. /// </summary> public IpcEndpoint Endpoint { get; } /// <summary> /// The identifier of the process that is unique within its process namespace. /// </summary> public int ProcessId { get; } /// <summary> /// The unique identifier of the runtime instance. /// </summary> public Guid RuntimeInstanceCookie { get; } internal string DebuggerDisplay => FormattableString.Invariant($"PID={ProcessId}, Cookie={RuntimeInstanceCookie}"); } }
// 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.Diagnostics; namespace Microsoft.Diagnostics.NETCore.Client { /// <summary> /// Represents a runtine instance connection to a reversed diagnostics server. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] internal struct IpcEndpointInfo { internal IpcEndpointInfo(IpcEndpoint endpoint, int processId, Guid runtimeInstanceCookie) { Endpoint = endpoint; ProcessId = processId; RuntimeInstanceCookie = runtimeInstanceCookie; } /// <summary> /// An endpoint used to retrieve diagnostic information from the associated runtime instance. /// </summary> public IpcEndpoint Endpoint { get; } /// <summary> /// The identifier of the process that is unique within its process namespace. /// </summary> public int ProcessId { get; } /// <summary> /// The unique identifier of the runtime instance. /// </summary> public Guid RuntimeInstanceCookie { get; } internal string DebuggerDisplay => FormattableString.Invariant($"PID={ProcessId}, Cookie={RuntimeInstanceCookie}"); } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/Interop/COM/NETServer/NETServer.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>library</OutputType> <CLRTestKind>SharedLibrary</CLRTestKind> </PropertyGroup> <ItemGroup> <Compile Include="*.cs" /> <Compile Include="../ServerContracts/Server.Contracts.cs" /> <Compile Include="../ServerContracts/ServerGuids.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>library</OutputType> <CLRTestKind>SharedLibrary</CLRTestKind> </PropertyGroup> <ItemGroup> <Compile Include="*.cs" /> <Compile Include="../ServerContracts/Server.Contracts.cs" /> <Compile Include="../ServerContracts/ServerGuids.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.Enumerators.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System; namespace System.Reflection.Metadata { public partial class BlobBuilder { // internal for testing internal struct Chunks : IEnumerable<BlobBuilder>, IEnumerator<BlobBuilder>, IEnumerator { private readonly BlobBuilder _head; private BlobBuilder _next; private BlobBuilder? _currentOpt; internal Chunks(BlobBuilder builder) { Debug.Assert(builder.IsHead); _head = builder; _next = builder.FirstChunk; _currentOpt = null; } object IEnumerator.Current => Current; public BlobBuilder Current => _currentOpt!; public bool MoveNext() { if (_currentOpt == _head) { return false; } if (_currentOpt == _head._nextOrPrevious) { _currentOpt = _head; return true; } _currentOpt = _next; _next = _next._nextOrPrevious; return true; } public void Reset() { _currentOpt = null; _next = _head.FirstChunk; } void IDisposable.Dispose() { } // IEnumerable: public Chunks GetEnumerator() => this; IEnumerator<BlobBuilder> IEnumerable<BlobBuilder>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public struct Blobs : IEnumerable<Blob>, IEnumerator<Blob>, IEnumerator { private Chunks _chunks; internal Blobs(BlobBuilder builder) { _chunks = new Chunks(builder); } object IEnumerator.Current => Current; public Blob Current { get { var current = _chunks.Current; if (current != null) { return new Blob(current._buffer, 0, current.Length); } else { return default(Blob); } } } public bool MoveNext() => _chunks.MoveNext(); public void Reset() => _chunks.Reset(); void IDisposable.Dispose() { } // IEnumerable: public Blobs GetEnumerator() => this; IEnumerator<Blob> IEnumerable<Blob>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System; namespace System.Reflection.Metadata { public partial class BlobBuilder { // internal for testing internal struct Chunks : IEnumerable<BlobBuilder>, IEnumerator<BlobBuilder>, IEnumerator { private readonly BlobBuilder _head; private BlobBuilder _next; private BlobBuilder? _currentOpt; internal Chunks(BlobBuilder builder) { Debug.Assert(builder.IsHead); _head = builder; _next = builder.FirstChunk; _currentOpt = null; } object IEnumerator.Current => Current; public BlobBuilder Current => _currentOpt!; public bool MoveNext() { if (_currentOpt == _head) { return false; } if (_currentOpt == _head._nextOrPrevious) { _currentOpt = _head; return true; } _currentOpt = _next; _next = _next._nextOrPrevious; return true; } public void Reset() { _currentOpt = null; _next = _head.FirstChunk; } void IDisposable.Dispose() { } // IEnumerable: public Chunks GetEnumerator() => this; IEnumerator<BlobBuilder> IEnumerable<BlobBuilder>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public struct Blobs : IEnumerable<Blob>, IEnumerator<Blob>, IEnumerator { private Chunks _chunks; internal Blobs(BlobBuilder builder) { _chunks = new Chunks(builder); } object IEnumerator.Current => Current; public Blob Current { get { var current = _chunks.Current; if (current != null) { return new Blob(current._buffer, 0, current.Length); } else { return default(Blob); } } } public bool MoveNext() => _chunks.MoveNext(); public void Reset() => _chunks.Reset(); void IDisposable.Dispose() { } // IEnumerable: public Blobs GetEnumerator() => this; IEnumerator<Blob> IEnumerable<Blob>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/shims/src/System.Drawing.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AssemblyVersion>4.0.0.0</AssemblyVersion> <StrongNameKeyId>Microsoft</StrongNameKeyId> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AssemblyVersion>4.0.0.0</AssemblyVersion> <StrongNameKeyId>Microsoft</StrongNameKeyId> </PropertyGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/Loader/classloader/regressions/dev11_95728/dev11_95728.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /* Regression Test for Dev11 bug #95728: LINQ/CLR :: Accessing a static generic field <String> causes CLR to crash with FatalExecutionEngineError * * Comments from bug: FatalExecutionEngineError: The runtime has encountered a fatal error. The address of the error was at 0x71ff5dcd, * on thread 0x7f4. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user * code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack. */ using System; using System.Linq.Expressions; namespace StaticFieldBug { public class StubClass<T> { public StubClass(T value) { StubClass<T>.StaticField = value; } public static T StaticField = default(T); public static T StaticProperty { get { return StaticField; } } } class Program { static int Main(string[] args) { Foo<string>("Run me to crash LINQ..."); Console.WriteLine("PASS (we didn't crash)!"); return 100; } public static void Foo<T>(T value) { Expression<Func<int, T>> lambda; StubClass<T> foo = new StubClass<T>((T)value); lambda = i => StubClass<T>.StaticField; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /* Regression Test for Dev11 bug #95728: LINQ/CLR :: Accessing a static generic field <String> causes CLR to crash with FatalExecutionEngineError * * Comments from bug: FatalExecutionEngineError: The runtime has encountered a fatal error. The address of the error was at 0x71ff5dcd, * on thread 0x7f4. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user * code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack. */ using System; using System.Linq.Expressions; namespace StaticFieldBug { public class StubClass<T> { public StubClass(T value) { StubClass<T>.StaticField = value; } public static T StaticField = default(T); public static T StaticProperty { get { return StaticField; } } } class Program { static int Main(string[] args) { Foo<string>("Run me to crash LINQ..."); Console.WriteLine("PASS (we didn't crash)!"); return 100; } public static void Foo<T>(T value) { Expression<Func<int, T>> lambda; StubClass<T> foo = new StubClass<T>((T)value); lambda = i => StubClass<T>.StaticField; } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/SIMD/Mul_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="Mul.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="Mul.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/Interop/COM/NETClients/Aggregation/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace NetClient { using System; using System.Runtime.InteropServices; using TestLibrary; using Xunit; using Server.Contract; using Server.Contract.Servers; class Program { class ManagedInner : AggregationTestingClass { } static void ValidateNativeOuter() { var managedInner = new ManagedInner(); var nativeOuter = (AggregationTesting)managedInner; Assert.True(typeof(ManagedInner).IsCOMObject); Assert.True(typeof(AggregationTestingClass).IsCOMObject); Assert.False(typeof(AggregationTesting).IsCOMObject); Assert.True(Marshal.IsComObject(managedInner)); Assert.True(Marshal.IsComObject(nativeOuter)); Assert.True(nativeOuter.IsAggregated()); Assert.True(nativeOuter.AreAggregated(managedInner, nativeOuter)); Assert.False(nativeOuter.AreAggregated(nativeOuter, new object())); } static int Main(string[] doNotUse) { // RegFree COM is not supported on Windows Nano if (Utilities.IsWindowsNanoServer) { return 100; } try { ValidateNativeOuter(); } catch (Exception e) { Console.WriteLine($"Test Failure: {e}"); return 101; } return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace NetClient { using System; using System.Runtime.InteropServices; using TestLibrary; using Xunit; using Server.Contract; using Server.Contract.Servers; class Program { class ManagedInner : AggregationTestingClass { } static void ValidateNativeOuter() { var managedInner = new ManagedInner(); var nativeOuter = (AggregationTesting)managedInner; Assert.True(typeof(ManagedInner).IsCOMObject); Assert.True(typeof(AggregationTestingClass).IsCOMObject); Assert.False(typeof(AggregationTesting).IsCOMObject); Assert.True(Marshal.IsComObject(managedInner)); Assert.True(Marshal.IsComObject(nativeOuter)); Assert.True(nativeOuter.IsAggregated()); Assert.True(nativeOuter.AreAggregated(managedInner, nativeOuter)); Assert.False(nativeOuter.AreAggregated(nativeOuter, new object())); } static int Main(string[] doNotUse) { // RegFree COM is not supported on Windows Nano if (Utilities.IsWindowsNanoServer) { return 100; } try { ValidateNativeOuter(); } catch (Exception e) { Console.WriteLine($"Test Failure: {e}"); return 101; } return 100; } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Resources.Designer.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.Interop { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Interop.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Marshalling an array from unmanaged to managed requires either the &apos;SizeParamIndex&apos; or &apos;SizeConst&apos; fields to be set on a &apos;MarshalAsAttribute&apos; or the &apos;ConstantElementCount&apos; or &apos;CountElementName&apos; properties to be set on a &apos;MarshalUsingAttribute&apos;.. /// </summary> internal static string ArraySizeMustBeSpecified { get { return ResourceManager.GetString("ArraySizeMustBeSpecified", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;SizeParamIndex&apos; value in the &apos;MarshalAsAttribute&apos; is out of range.. /// </summary> internal static string ArraySizeParamIndexOutOfRange { get { return ResourceManager.GetString("ArraySizeParamIndexOutOfRange", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;BlittableTypeAttribute&apos; and &apos;NativeMarshallingAttribute&apos; attributes are mutually exclusive.. /// </summary> internal static string CannotHaveMultipleMarshallingAttributesDescription { get { return ResourceManager.GetString("CannotHaveMultipleMarshallingAttributesDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Type &apos;{0}&apos; is marked with &apos;BlittableTypeAttribute&apos; and &apos;NativeMarshallingAttribute&apos;. A type can only have one of these two attributes.. /// </summary> internal static string CannotHaveMultipleMarshallingAttributesMessage { get { return ResourceManager.GetString("CannotHaveMultipleMarshallingAttributesMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A native type with the &apos;GenericContiguousCollectionMarshallerAttribute&apos; must have at least one of the two marshalling methods as well as a &apos;ManagedValues&apos; property of type &apos;Span&lt;T&gt;&apos; for some &apos;T&apos; and a &apos;NativeValueStorage&apos; property of type &apos;Span&lt;byte&gt;&apos; to enable marshalling the managed type.. /// </summary> internal static string CollectionNativeTypeMustHaveRequiredShapeDescription { get { return ResourceManager.GetString("CollectionNativeTypeMustHaveRequiredShapeDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type &apos;{0}&apos; must be a value type and have a constructor that takes two parameters, one of type &apos;{1}&apos; and an &apos;int&apos;, or have a parameterless instance method named &apos;ToManaged&apos; that returns &apos;{1}&apos; as well as a &apos;ManagedValues&apos; property of type &apos;Span&lt;T&gt;&apos; for some &apos;T&apos; and a &apos;NativeValueStorage&apos; property of type &apos;Span&lt;byte&gt;&apos;. /// </summary> internal static string CollectionNativeTypeMustHaveRequiredShapeMessage { get { return ResourceManager.GetString("CollectionNativeTypeMustHaveRequiredShapeMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified collection size parameter for an collection must be an integer type. If the size information is applied to a nested collection, the size parameter must be a collection of one less level of nesting with an integral element.. /// </summary> internal static string CollectionSizeParamTypeMustBeIntegral { get { return ResourceManager.GetString("CollectionSizeParamTypeMustBeIntegral", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Only one of &apos;ConstantElementCount&apos; or &apos;ElementCountInfo&apos; may be used in a &apos;MarshalUsingAttribute&apos; for a given &apos;ElementIndirectionLevel&apos;. /// </summary> internal static string ConstantAndElementCountInfoDisallowed { get { return ResourceManager.GetString("ConstantAndElementCountInfoDisallowed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified parameter needs to be marshalled from managed to native, but the native type &apos;{0}&apos; does not support it.. /// </summary> internal static string CustomTypeMarshallingManagedToNativeUnsupported { get { return ResourceManager.GetString("CustomTypeMarshallingManagedToNativeUnsupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified parameter needs to be marshalled from native to managed, but the native type &apos;{0}&apos; does not support it.. /// </summary> internal static string CustomTypeMarshallingNativeToManagedUnsupported { get { return ResourceManager.GetString("CustomTypeMarshallingNativeToManagedUnsupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This element cannot depend on &apos;{0}&apos; for collection size information without creating a dependency cycle. /// </summary> internal static string CyclicalCountInfo { get { return ResourceManager.GetString("CyclicalCountInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Count information for a given element at a given indirection level can only be specified once. /// </summary> internal static string DuplicateCountInfo { get { return ResourceManager.GetString("DuplicateCountInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Multiple marshalling attributes per element per indirection level is unsupported, but duplicate information was provided for indirection level {0}. /// </summary> internal static string DuplicateMarshallingInfo { get { return ResourceManager.GetString("DuplicateMarshallingInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling info was specified for &apos;ElementIndirectionLevel&apos; {0}, but marshalling info was only needed for {1} level(s) of indirection. /// </summary> internal static string ExtraneousMarshallingInfo { get { return ResourceManager.GetString("ExtraneousMarshallingInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The provided graph has cycles and cannot be topologically sorted.. /// </summary> internal static string GraphHasCycles { get { return ResourceManager.GetString("GraphHasCycles", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[In]&apos; attribute is not supported unless the &apos;[Out]&apos; attribute is also used. The behavior of the &apos;[In]&apos; attribute without the &apos;[Out]&apos; attribute is the same as the default behavior.. /// </summary> internal static string InAttributeNotSupportedWithoutOut { get { return ResourceManager.GetString("InAttributeNotSupportedWithoutOut", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[In]&apos; and &apos;[Out]&apos; attributes are unsupported on parameters passed by reference. Use the &apos;in&apos;, &apos;ref&apos;, or &apos;out&apos; keywords instead.. /// </summary> internal static string InOutAttributeByRefNotSupported { get { return ResourceManager.GetString("InOutAttributeByRefNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The provided &apos;[In]&apos; and &apos;[Out]&apos; attributes on this parameter are unsupported on this parameter.. /// </summary> internal static string InOutAttributeMarshalerNotSupported { get { return ResourceManager.GetString("InOutAttributeMarshalerNotSupported", resourceCulture); } } /// <summary> /// Marshalling bool without explicit marshalling information is not supported. Specify either &apos;MarshalUsingAttribute&apos; or &apos;MarshalAsAttribute&apos;.. /// </summary> internal static string MarshallingBoolAsUndefinedNotSupported { get { return ResourceManager.GetString("MarshallingBoolAsUndefinedNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling char with &apos;CharSet.{0}&apos; is not supported. Instead, manually convert the char type to the desired byte representation and pass to the source-generated P/Invoke.. /// </summary> internal static string MarshallingCharAsSpecifiedCharSetNotSupported { get { return ResourceManager.GetString("MarshallingCharAsSpecifiedCharSetNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling string or char without explicit marshalling information is not supported. Specify either &apos;GeneratedDllImportAttribute.CharSet&apos; or &apos;MarshalAsAttribute&apos;.. /// </summary> internal static string MarshallingStringOrCharAsUndefinedNotSupported { get { return ResourceManager.GetString("MarshallingStringOrCharAsUndefinedNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type &apos;{0}&apos; for managed type &apos;{1}&apos; must be a closed generic type or have the same arity as the managed type.. /// </summary> internal static string NativeGenericTypeMustBeClosedOrMatchArityMessage { get { return ResourceManager.GetString("NativeGenericTypeMustBeClosedOrMatchArityMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type must have at least one of the two marshalling methods to enable marshalling the managed type.. /// </summary> internal static string NativeTypeMustHaveRequiredShapeDescription { get { return ResourceManager.GetString("NativeTypeMustHaveRequiredShapeDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type &apos;{0}&apos; must be a value type and have a constructor that takes one parameter of type &apos;{1}&apos; or a parameterless instance method named &apos;ToManaged&apos; that returns &apos;{1}&apos;. /// </summary> internal static string NativeTypeMustHaveRequiredShapeMessage { get { return ResourceManager.GetString("NativeTypeMustHaveRequiredShapeMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[Out]&apos; attribute is only supported on array parameters.. /// </summary> internal static string OutByValueNotSupportedDescription { get { return ResourceManager.GetString("OutByValueNotSupportedDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[Out]&apos; attribute is not supported on the &apos;{0}&apos; parameter.. /// </summary> internal static string OutByValueNotSupportedMessage { get { return ResourceManager.GetString("OutByValueNotSupportedMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property must not be a &apos;ref&apos; or &apos;readonly ref&apos; property.. /// </summary> internal static string RefValuePropertyUnsupportedDescription { get { return ResourceManager.GetString("RefValuePropertyUnsupportedDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property on the native type &apos;{0}&apos; must not be a &apos;ref&apos; or &apos;readonly ref&apos; property.. /// </summary> internal static string RefValuePropertyUnsupportedMessage { get { return ResourceManager.GetString("RefValuePropertyUnsupportedMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Runtime marshalling must be disabled in this project by applying the &apos;System.Runtime.InteropServices.DisableRuntimeMarshallingAttribute&apos; to the assembly to enable marshalling this type.. /// </summary> internal static string RuntimeMarshallingMustBeDisabled { get { return ResourceManager.GetString("RuntimeMarshallingMustBeDisabled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to An abstract type derived from &apos;SafeHandle&apos; cannot be marshalled by reference. The provided type must be concrete.. /// </summary> internal static string SafeHandleByRefMustBeConcrete { get { return ResourceManager.GetString("SafeHandleByRefMustBeConcrete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Specified type is not supported by source-generated P/Invokes. /// </summary> internal static string TypeNotSupportedTitle { get { return ResourceManager.GetString("TypeNotSupportedTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling a value between managed and native with a native type with a &apos;Value&apos; property requires extra state, which is not supported in this context.. /// </summary> internal static string ValuePropertyMarshallingRequiresAdditionalState { get { return ResourceManager.GetString("ValuePropertyMarshallingRequiresAdditionalState", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type&apos;s &apos;Value&apos; property must have a getter to support marshalling from managed to native.. /// </summary> internal static string ValuePropertyMustHaveGetterDescription { get { return ResourceManager.GetString("ValuePropertyMustHaveGetterDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property on the native type &apos;{0}&apos; must have a getter. /// </summary> internal static string ValuePropertyMustHaveGetterMessage { get { return ResourceManager.GetString("ValuePropertyMustHaveGetterMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type&apos;s &apos;Value&apos; property must have a setter to support marshalling from native to managed.. /// </summary> internal static string ValuePropertyMustHaveSetterDescription { get { return ResourceManager.GetString("ValuePropertyMustHaveSetterDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property on the native type &apos;{0}&apos; must have a setter. /// </summary> internal static string ValuePropertyMustHaveSetterMessage { get { return ResourceManager.GetString("ValuePropertyMustHaveSetterMessage", resourceCulture); } } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.Interop { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Interop.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Marshalling an array from unmanaged to managed requires either the &apos;SizeParamIndex&apos; or &apos;SizeConst&apos; fields to be set on a &apos;MarshalAsAttribute&apos; or the &apos;ConstantElementCount&apos; or &apos;CountElementName&apos; properties to be set on a &apos;MarshalUsingAttribute&apos;.. /// </summary> internal static string ArraySizeMustBeSpecified { get { return ResourceManager.GetString("ArraySizeMustBeSpecified", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;SizeParamIndex&apos; value in the &apos;MarshalAsAttribute&apos; is out of range.. /// </summary> internal static string ArraySizeParamIndexOutOfRange { get { return ResourceManager.GetString("ArraySizeParamIndexOutOfRange", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;BlittableTypeAttribute&apos; and &apos;NativeMarshallingAttribute&apos; attributes are mutually exclusive.. /// </summary> internal static string CannotHaveMultipleMarshallingAttributesDescription { get { return ResourceManager.GetString("CannotHaveMultipleMarshallingAttributesDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Type &apos;{0}&apos; is marked with &apos;BlittableTypeAttribute&apos; and &apos;NativeMarshallingAttribute&apos;. A type can only have one of these two attributes.. /// </summary> internal static string CannotHaveMultipleMarshallingAttributesMessage { get { return ResourceManager.GetString("CannotHaveMultipleMarshallingAttributesMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A native type with the &apos;GenericContiguousCollectionMarshallerAttribute&apos; must have at least one of the two marshalling methods as well as a &apos;ManagedValues&apos; property of type &apos;Span&lt;T&gt;&apos; for some &apos;T&apos; and a &apos;NativeValueStorage&apos; property of type &apos;Span&lt;byte&gt;&apos; to enable marshalling the managed type.. /// </summary> internal static string CollectionNativeTypeMustHaveRequiredShapeDescription { get { return ResourceManager.GetString("CollectionNativeTypeMustHaveRequiredShapeDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type &apos;{0}&apos; must be a value type and have a constructor that takes two parameters, one of type &apos;{1}&apos; and an &apos;int&apos;, or have a parameterless instance method named &apos;ToManaged&apos; that returns &apos;{1}&apos; as well as a &apos;ManagedValues&apos; property of type &apos;Span&lt;T&gt;&apos; for some &apos;T&apos; and a &apos;NativeValueStorage&apos; property of type &apos;Span&lt;byte&gt;&apos;. /// </summary> internal static string CollectionNativeTypeMustHaveRequiredShapeMessage { get { return ResourceManager.GetString("CollectionNativeTypeMustHaveRequiredShapeMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified collection size parameter for an collection must be an integer type. If the size information is applied to a nested collection, the size parameter must be a collection of one less level of nesting with an integral element.. /// </summary> internal static string CollectionSizeParamTypeMustBeIntegral { get { return ResourceManager.GetString("CollectionSizeParamTypeMustBeIntegral", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Only one of &apos;ConstantElementCount&apos; or &apos;ElementCountInfo&apos; may be used in a &apos;MarshalUsingAttribute&apos; for a given &apos;ElementIndirectionLevel&apos;. /// </summary> internal static string ConstantAndElementCountInfoDisallowed { get { return ResourceManager.GetString("ConstantAndElementCountInfoDisallowed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified parameter needs to be marshalled from managed to native, but the native type &apos;{0}&apos; does not support it.. /// </summary> internal static string CustomTypeMarshallingManagedToNativeUnsupported { get { return ResourceManager.GetString("CustomTypeMarshallingManagedToNativeUnsupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified parameter needs to be marshalled from native to managed, but the native type &apos;{0}&apos; does not support it.. /// </summary> internal static string CustomTypeMarshallingNativeToManagedUnsupported { get { return ResourceManager.GetString("CustomTypeMarshallingNativeToManagedUnsupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This element cannot depend on &apos;{0}&apos; for collection size information without creating a dependency cycle. /// </summary> internal static string CyclicalCountInfo { get { return ResourceManager.GetString("CyclicalCountInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Count information for a given element at a given indirection level can only be specified once. /// </summary> internal static string DuplicateCountInfo { get { return ResourceManager.GetString("DuplicateCountInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Multiple marshalling attributes per element per indirection level is unsupported, but duplicate information was provided for indirection level {0}. /// </summary> internal static string DuplicateMarshallingInfo { get { return ResourceManager.GetString("DuplicateMarshallingInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling info was specified for &apos;ElementIndirectionLevel&apos; {0}, but marshalling info was only needed for {1} level(s) of indirection. /// </summary> internal static string ExtraneousMarshallingInfo { get { return ResourceManager.GetString("ExtraneousMarshallingInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The provided graph has cycles and cannot be topologically sorted.. /// </summary> internal static string GraphHasCycles { get { return ResourceManager.GetString("GraphHasCycles", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[In]&apos; attribute is not supported unless the &apos;[Out]&apos; attribute is also used. The behavior of the &apos;[In]&apos; attribute without the &apos;[Out]&apos; attribute is the same as the default behavior.. /// </summary> internal static string InAttributeNotSupportedWithoutOut { get { return ResourceManager.GetString("InAttributeNotSupportedWithoutOut", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[In]&apos; and &apos;[Out]&apos; attributes are unsupported on parameters passed by reference. Use the &apos;in&apos;, &apos;ref&apos;, or &apos;out&apos; keywords instead.. /// </summary> internal static string InOutAttributeByRefNotSupported { get { return ResourceManager.GetString("InOutAttributeByRefNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The provided &apos;[In]&apos; and &apos;[Out]&apos; attributes on this parameter are unsupported on this parameter.. /// </summary> internal static string InOutAttributeMarshalerNotSupported { get { return ResourceManager.GetString("InOutAttributeMarshalerNotSupported", resourceCulture); } } /// <summary> /// Marshalling bool without explicit marshalling information is not supported. Specify either &apos;MarshalUsingAttribute&apos; or &apos;MarshalAsAttribute&apos;.. /// </summary> internal static string MarshallingBoolAsUndefinedNotSupported { get { return ResourceManager.GetString("MarshallingBoolAsUndefinedNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling char with &apos;CharSet.{0}&apos; is not supported. Instead, manually convert the char type to the desired byte representation and pass to the source-generated P/Invoke.. /// </summary> internal static string MarshallingCharAsSpecifiedCharSetNotSupported { get { return ResourceManager.GetString("MarshallingCharAsSpecifiedCharSetNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling string or char without explicit marshalling information is not supported. Specify either &apos;GeneratedDllImportAttribute.CharSet&apos; or &apos;MarshalAsAttribute&apos;.. /// </summary> internal static string MarshallingStringOrCharAsUndefinedNotSupported { get { return ResourceManager.GetString("MarshallingStringOrCharAsUndefinedNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type &apos;{0}&apos; for managed type &apos;{1}&apos; must be a closed generic type or have the same arity as the managed type.. /// </summary> internal static string NativeGenericTypeMustBeClosedOrMatchArityMessage { get { return ResourceManager.GetString("NativeGenericTypeMustBeClosedOrMatchArityMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type must have at least one of the two marshalling methods to enable marshalling the managed type.. /// </summary> internal static string NativeTypeMustHaveRequiredShapeDescription { get { return ResourceManager.GetString("NativeTypeMustHaveRequiredShapeDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type &apos;{0}&apos; must be a value type and have a constructor that takes one parameter of type &apos;{1}&apos; or a parameterless instance method named &apos;ToManaged&apos; that returns &apos;{1}&apos;. /// </summary> internal static string NativeTypeMustHaveRequiredShapeMessage { get { return ResourceManager.GetString("NativeTypeMustHaveRequiredShapeMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[Out]&apos; attribute is only supported on array parameters.. /// </summary> internal static string OutByValueNotSupportedDescription { get { return ResourceManager.GetString("OutByValueNotSupportedDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;[Out]&apos; attribute is not supported on the &apos;{0}&apos; parameter.. /// </summary> internal static string OutByValueNotSupportedMessage { get { return ResourceManager.GetString("OutByValueNotSupportedMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property must not be a &apos;ref&apos; or &apos;readonly ref&apos; property.. /// </summary> internal static string RefValuePropertyUnsupportedDescription { get { return ResourceManager.GetString("RefValuePropertyUnsupportedDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property on the native type &apos;{0}&apos; must not be a &apos;ref&apos; or &apos;readonly ref&apos; property.. /// </summary> internal static string RefValuePropertyUnsupportedMessage { get { return ResourceManager.GetString("RefValuePropertyUnsupportedMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Runtime marshalling must be disabled in this project by applying the &apos;System.Runtime.InteropServices.DisableRuntimeMarshallingAttribute&apos; to the assembly to enable marshalling this type.. /// </summary> internal static string RuntimeMarshallingMustBeDisabled { get { return ResourceManager.GetString("RuntimeMarshallingMustBeDisabled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to An abstract type derived from &apos;SafeHandle&apos; cannot be marshalled by reference. The provided type must be concrete.. /// </summary> internal static string SafeHandleByRefMustBeConcrete { get { return ResourceManager.GetString("SafeHandleByRefMustBeConcrete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Specified type is not supported by source-generated P/Invokes. /// </summary> internal static string TypeNotSupportedTitle { get { return ResourceManager.GetString("TypeNotSupportedTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Marshalling a value between managed and native with a native type with a &apos;Value&apos; property requires extra state, which is not supported in this context.. /// </summary> internal static string ValuePropertyMarshallingRequiresAdditionalState { get { return ResourceManager.GetString("ValuePropertyMarshallingRequiresAdditionalState", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type&apos;s &apos;Value&apos; property must have a getter to support marshalling from managed to native.. /// </summary> internal static string ValuePropertyMustHaveGetterDescription { get { return ResourceManager.GetString("ValuePropertyMustHaveGetterDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property on the native type &apos;{0}&apos; must have a getter. /// </summary> internal static string ValuePropertyMustHaveGetterMessage { get { return ResourceManager.GetString("ValuePropertyMustHaveGetterMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The native type&apos;s &apos;Value&apos; property must have a setter to support marshalling from native to managed.. /// </summary> internal static string ValuePropertyMustHaveSetterDescription { get { return ResourceManager.GetString("ValuePropertyMustHaveSetterDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;Value&apos; property on the native type &apos;{0}&apos; must have a setter. /// </summary> internal static string ValuePropertyMustHaveSetterMessage { get { return ResourceManager.GetString("ValuePropertyMustHaveSetterMessage", resourceCulture); } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/X86/Avx1/LoadVector256.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\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 LoadVector256UInt32() { var test = new SimpleUnaryOpTest__LoadVector256UInt32(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_Load(); // Validates calling via reflection works test.RunReflectionScenario_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 SimpleUnaryOpTest__LoadVector256UInt32 { private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; public SimpleUnaryOpTest__LoadVector256UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.LoadVector256( (UInt32*)(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.LoadVector256), new Type[] { typeof(UInt32*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArrayPtr, typeof(UInt32*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_Load(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<UInt32> firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.LoadVector256)}<UInt32>(Vector256<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.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 LoadVector256UInt32() { var test = new SimpleUnaryOpTest__LoadVector256UInt32(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_Load(); // Validates calling via reflection works test.RunReflectionScenario_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 SimpleUnaryOpTest__LoadVector256UInt32 { private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; public SimpleUnaryOpTest__LoadVector256UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.LoadVector256( (UInt32*)(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.LoadVector256), new Type[] { typeof(UInt32*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArrayPtr, typeof(UInt32*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_Load(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<UInt32> firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.LoadVector256)}<UInt32>(Vector256<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHashtable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Threading; using Debug = System.Diagnostics.Debug; using Interlocked = System.Threading.Interlocked; namespace System.Xml.Linq { /// <summary> /// This is a thread-safe hash table which maps string keys to values of type TValue. It is assumed that the string key is embedded in the hashed value /// and can be extracted via a call to ExtractKeyDelegate (in order to save space and allow cleanup of key if value is released due to a WeakReference /// TValue releasing its target). /// </summary> /// <remarks> /// All methods on this class are thread-safe. /// /// When the hash table fills up, it is necessary to resize it and rehash all contents. Because this can be expensive, /// a lock is taken, and one thread is responsible for the resize. Other threads which need to add values must wait /// for the resize to be complete. /// /// Thread-Safety Notes /// =================== /// /// 1. Because performance and scalability are such a concern with the global name table, I have avoided the use of /// BIFALOs (Big Fat Locks). Instead, I use CompareExchange, Interlocked.Increment, memory barriers, atomic state objects, /// etc. to avoid locks. Any changes to code which accesses these variables should be carefully reviewed and tested, /// as it can be *very* tricky. In particular, if you don't understand the CLR memory model or if you don't know /// what a memory barrier is, DON'T attempt to modify this code. A good discussion of these topics can be found at /// <![CDATA[http://discuss.develop.com/archives/wa.exe?A2=ind0203B&L=DOTNET&P=R375]]>. /// /// 2. Because I am not sure if the CLR spec has changed since versions 1.0/1.1, I am assuming the weak memory model that /// is described in the ECMA spec, in which normal writes can be reordered. This means I must introduce more memory /// barriers than otherwise would be necessary. /// /// 3. There are several thread-safety concepts and patterns I utilize in this code: /// a. Publishing -- There are a small number of places where state is exposed, or published, to multiple threads. /// These places are marked with the comment "PUBLISH", and are key locations to consider when /// reviewing the code for thread-safety. /// /// b. Immutable objects -- Immutable objects initialize their fields once in their constructor and then never modify /// them again. As long as care is taken to ensure that initial field values are visible to /// other threads before publishing the immutable object itself, immutable objects are /// completely thread-safe. /// /// c. Atomic state objects -- Locks typically are taken when several pieces of state must be updated atomically. In /// other words, there is a window in which state is inconsistent, and that window must /// be protected from view by locking. However, if a new object is created each time state /// changes (or state changes substantially), then during creation the new object is only /// visible to a single thread. Once construction is complete, an assignment (guaranteed /// atomic) can replace the old state object with the new state object, thus publishing a /// consistent view to all threads. /// /// d. Retry -- When several threads contend over shared state which only one is allowed to possess, it is possible /// to avoid locking by repeatedly attempting to acquire the shared state. The CompareExchange method /// is useful for atomically ensuring that only one thread succeeds, and other threads are notified that /// they must retry. /// /// 4. All variables which can be written by multiple threads are marked "SHARED STATE". /// </remarks> internal sealed class XHashtable<TValue> { private XHashtableState _state; // SHARED STATE: Contains all XHashtable state, so it can be atomically swapped when resizes occur /// <summary> /// Prototype of function which is called to extract a string key value from a hashed value. /// Returns null if the hashed value is invalid (e.g. value has been released due to a WeakReference TValue being cleaned up). /// </summary> public delegate string? ExtractKeyDelegate(TValue value); /// <summary> /// Construct a new XHashtable with the specified starting capacity. /// </summary> public XHashtable(ExtractKeyDelegate extractKey, int capacity) { _state = new XHashtableState(extractKey, capacity); } /// <summary> /// Get an existing value from the hash table. Return false if no such value exists. /// </summary> public bool TryGetValue(string key, int index, int count, [MaybeNullWhen(false)] out TValue value) { return _state.TryGetValue(key, index, count, out value); } /// <summary> /// Add a value to the hash table, hashed based on a string key embedded in it. Return the added value (may be a different object than "value"). /// </summary> public TValue Add(TValue value) { TValue newValue; // Loop until value is in hash table while (true) { // Add new value // XHashtableState.TryAdd returns false if hash table is not big enough if (_state.TryAdd(value, out newValue)) return newValue; // PUBLISH (state) // Hash table was not big enough, so resize it. // We only want one thread to perform a resize, as it is an expensive operation // First thread will perform resize; waiting threads will call Resize(), but should immediately // return since there will almost always be space in the hash table resized by the first thread. lock (this) { XHashtableState newState = _state.Resize(); // Use memory barrier to ensure that the resized XHashtableState object is fully constructed before it is assigned Thread.MemoryBarrier(); _state = newState; } } } /// <summary> /// This class contains all the hash table state. Rather than creating a bucket object, buckets are structs /// packed into an array. Buckets with the same truncated hash code are linked into lists, so that collisions /// can be disambiguated. /// </summary> /// <remarks> /// Note that the "buckets" and "entries" arrays are never themselves written by multiple threads. Instead, the /// *contents* of the array are written by multiple threads. Resizing the hash table does not modify these variables, /// or even modify the contents of these variables. Instead, resizing makes an entirely new XHashtableState object /// in which all entries are rehashed. This strategy allows reader threads to continue finding values in the "old" /// XHashtableState, while writer threads (those that need to add a new value to the table) are blocked waiting for /// the resize to complete. /// </remarks> private sealed class XHashtableState { private readonly int[] _buckets; // Buckets contain indexes into entries array (bucket values are SHARED STATE) private readonly Entry[] _entries; // Entries contain linked lists of buckets (next pointers are SHARED STATE) private int _numEntries; // SHARED STATE: Current number of entries (including orphaned entries) private readonly ExtractKeyDelegate _extractKey; // Delegate called in order to extract string key embedded in hashed TValue private const int EndOfList = 0; // End of linked list marker private const int FullList = -1; // Indicates entries should not be added to end of linked list /// <summary> /// Construct a new XHashtableState object with the specified capacity. /// </summary> public XHashtableState(ExtractKeyDelegate extractKey, int capacity) { Debug.Assert((capacity & (capacity - 1)) == 0, "capacity must be a power of 2"); Debug.Assert(extractKey != null, "extractKey may not be null"); // Initialize hash table data structures, with specified maximum capacity _buckets = new int[capacity]; _entries = new Entry[capacity]; // Save delegate _extractKey = extractKey; } /// <summary> /// If this table is not full, then just return "this". Otherwise, create and return a new table with /// additional capacity, and rehash all values in the table. /// </summary> public XHashtableState Resize() { // No need to resize if there are open entries if (_numEntries < _buckets.Length) return this; int newSize = 0; // Determine capacity of resized hash table by first counting number of valid, non-orphaned entries // As this count proceeds, close all linked lists so that no additional entries can be added to them for (int bucketIdx = 0; bucketIdx < _buckets.Length; bucketIdx++) { int entryIdx = _buckets[bucketIdx]; if (entryIdx == EndOfList) { // Replace EndOfList with FullList, so that any threads still attempting to add will be forced to resize entryIdx = Interlocked.CompareExchange(ref _buckets[bucketIdx], FullList, EndOfList); } // Loop until we've guaranteed that the list has been counted and closed to further adds while (entryIdx > EndOfList) { // Count each valid entry if (_extractKey(_entries[entryIdx].Value) != null) newSize++; if (_entries[entryIdx].Next == EndOfList) { // Replace EndOfList with FullList, so that any threads still attempting to add will be forced to resize entryIdx = Interlocked.CompareExchange(ref _entries[entryIdx].Next, FullList, EndOfList); } else { // Move to next entry in the list entryIdx = _entries[entryIdx].Next; } } Debug.Assert(entryIdx == EndOfList, "Resize() should only be called by one thread"); } // Double number of valid entries; if result is less than current capacity, then use current capacity if (newSize < _buckets.Length / 2) { newSize = _buckets.Length; } else { newSize = _buckets.Length * 2; if (newSize < 0) throw new OverflowException(); } // Create new hash table with additional capacity XHashtableState newHashtable = new XHashtableState(_extractKey, newSize); // Rehash names (TryAdd will always succeed, since we won't fill the new table) // Do not simply walk over entries and add them to table, as that would add orphaned // entries. Instead, walk the linked lists and add each name. for (int bucketIdx = 0; bucketIdx < _buckets.Length; bucketIdx++) { int entryIdx = _buckets[bucketIdx]; while (entryIdx > EndOfList) { newHashtable.TryAdd(_entries[entryIdx].Value, out _); entryIdx = _entries[entryIdx].Next; } Debug.Assert(entryIdx == FullList, "Linked list should have been closed when it was counted"); } return newHashtable; } /// <summary> /// Attempt to find "key" in the table. If the key exists, return the associated value in "value" and /// return true. Otherwise return false. /// </summary> public bool TryGetValue(string key, int index, int count, [MaybeNullWhen(false)] out TValue value) { int hashCode = ComputeHashCode(key, index, count); int entryIndex = 0; // If a matching entry is found, return its value if (FindEntry(hashCode, key, index, count, ref entryIndex)) { value = _entries[entryIndex].Value; return true; } // No matching entry found, so return false value = default(TValue); return false; } /// <summary> /// Attempt to add "value" to the table, hashed by an embedded string key. If a value having the same key already exists, /// then return the existing value in "newValue". Otherwise, return the newly added value in "newValue". /// /// If the hash table is full, return false. Otherwise, return true. /// </summary> public bool TryAdd(TValue value, out TValue newValue) { int newEntry, entryIndex; string? key; int hashCode; // Assume "value" will be added and returned as "newValue" newValue = value; // Extract the key from the value. If it's null, then value is invalid and does not need to be added to table. key = _extractKey(value); if (key == null) return true; // Compute hash code over entire length of key hashCode = ComputeHashCode(key, 0, key.Length); // Assume value is not yet in the hash table, and prepare to add it (if table is full, return false). // Use the entry index returned from Increment, which will never be zero, as zero conflicts with EndOfList. // Although this means that the first entry will never be used, it avoids the need to initialize all // starting buckets to the EndOfList value. newEntry = Interlocked.Increment(ref _numEntries); if (newEntry < 0 || newEntry >= _buckets.Length) return false; _entries[newEntry].Value = value; _entries[newEntry].HashCode = hashCode; // Ensure that all writes to the entry can't be reordered past this barrier (or other threads might see new entry // in list before entry has been initialized!). Thread.MemoryBarrier(); // Loop until a matching entry is found, a new entry is added, or linked list is found to be full entryIndex = 0; while (!FindEntry(hashCode, key, 0, key.Length, ref entryIndex)) { // PUBLISH (buckets slot) // No matching entry found, so add the new entry to the end of the list ("entryIndex" is index of last entry) if (entryIndex == 0) entryIndex = Interlocked.CompareExchange(ref _buckets[hashCode & (_buckets.Length - 1)], newEntry, EndOfList); else entryIndex = Interlocked.CompareExchange(ref _entries[entryIndex].Next, newEntry, EndOfList); // Return true only if the CompareExchange succeeded (happens when replaced value is EndOfList). // Return false if the linked list turned out to be full because another thread is currently resizing // the hash table. In this case, entries[newEntry] is orphaned (not part of any linked list) and the // Add needs to be performed on the new hash table. Otherwise, keep looping, looking for new end of list. if (entryIndex <= EndOfList) return entryIndex == EndOfList; } // Another thread already added the value while this thread was trying to add, so return that instance instead. // Note that entries[newEntry] will be orphaned (not part of any linked list) in this case newValue = _entries[entryIndex].Value; return true; } /// <summary> /// Searches a linked list of entries, beginning at "entryIndex". If "entryIndex" is 0, then search starts at a hash bucket instead. /// Each entry in the list is matched against the (hashCode, key, index, count) key. If a matching entry is found, then its /// entry index is returned in "entryIndex" and true is returned. If no matching entry is found, then the index of the last entry /// in the list (or 0 if list is empty) is returned in "entryIndex" and false is returned. /// </summary> /// <remarks> /// This method has the side effect of removing invalid entries from the list as it is traversed. /// </remarks> private bool FindEntry(int hashCode, string key, int index, int count, ref int entryIndex) { int previousIndex = entryIndex; int currentIndex; // Set initial value of currentIndex to index of the next entry following entryIndex if (previousIndex == 0) currentIndex = _buckets[hashCode & (_buckets.Length - 1)]; else currentIndex = previousIndex; // Loop while not at end of list while (currentIndex > EndOfList) { // Check for matching hash code, then matching key if (_entries[currentIndex].HashCode == hashCode) { string? keyCompare = _extractKey(_entries[currentIndex].Value); // If the key is invalid, then attempt to remove the current entry from the linked list. // This is thread-safe in the case where the Next field points to another entry, since once a Next field points // to another entry, it will never be modified to be EndOfList or FullList. if (keyCompare == null) { if (_entries[currentIndex].Next > EndOfList) { // PUBLISH (buckets slot or entries slot) // Entry is invalid, so modify previous entry to point to its next entry _entries[currentIndex].Value = default(TValue)!; currentIndex = _entries[currentIndex].Next; if (previousIndex == 0) _buckets[hashCode & (_buckets.Length - 1)] = currentIndex; else _entries[previousIndex].Next = currentIndex; continue; } } else { // Valid key, so compare keys if (count == keyCompare.Length && string.CompareOrdinal(key, index, keyCompare, 0, count) == 0) { // Found match, so return true and matching entry in list entryIndex = currentIndex; return true; } } } // Move to next entry previousIndex = currentIndex; currentIndex = _entries[currentIndex].Next; } // Return false and last entry in list entryIndex = previousIndex; return false; } /// <summary> /// Compute hash code for a string key (index, count substring of "key"). The algorithm used is the same on used in NameTable.cs in System.Xml. /// </summary> private static int ComputeHashCode(string key, int index, int count) { Debug.Assert(key != null, "key should have been checked previously for null"); return string.GetHashCode(key.AsSpan(index, count)); } /// <summary> /// Hash table entry. The "Value" and "HashCode" fields are filled during initialization, and are never changed. The "Next" /// field is updated when a new entry is chained to this one, and therefore care must be taken to ensure that updates to /// this field are thread-safe. /// </summary> private struct Entry { public TValue Value; // Hashed value public int HashCode; // Hash code of string key (equal to extractKey(Value).GetHashCode()) public int Next; // SHARED STATE: Points to next entry in linked list } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Threading; using Debug = System.Diagnostics.Debug; using Interlocked = System.Threading.Interlocked; namespace System.Xml.Linq { /// <summary> /// This is a thread-safe hash table which maps string keys to values of type TValue. It is assumed that the string key is embedded in the hashed value /// and can be extracted via a call to ExtractKeyDelegate (in order to save space and allow cleanup of key if value is released due to a WeakReference /// TValue releasing its target). /// </summary> /// <remarks> /// All methods on this class are thread-safe. /// /// When the hash table fills up, it is necessary to resize it and rehash all contents. Because this can be expensive, /// a lock is taken, and one thread is responsible for the resize. Other threads which need to add values must wait /// for the resize to be complete. /// /// Thread-Safety Notes /// =================== /// /// 1. Because performance and scalability are such a concern with the global name table, I have avoided the use of /// BIFALOs (Big Fat Locks). Instead, I use CompareExchange, Interlocked.Increment, memory barriers, atomic state objects, /// etc. to avoid locks. Any changes to code which accesses these variables should be carefully reviewed and tested, /// as it can be *very* tricky. In particular, if you don't understand the CLR memory model or if you don't know /// what a memory barrier is, DON'T attempt to modify this code. A good discussion of these topics can be found at /// <![CDATA[http://discuss.develop.com/archives/wa.exe?A2=ind0203B&L=DOTNET&P=R375]]>. /// /// 2. Because I am not sure if the CLR spec has changed since versions 1.0/1.1, I am assuming the weak memory model that /// is described in the ECMA spec, in which normal writes can be reordered. This means I must introduce more memory /// barriers than otherwise would be necessary. /// /// 3. There are several thread-safety concepts and patterns I utilize in this code: /// a. Publishing -- There are a small number of places where state is exposed, or published, to multiple threads. /// These places are marked with the comment "PUBLISH", and are key locations to consider when /// reviewing the code for thread-safety. /// /// b. Immutable objects -- Immutable objects initialize their fields once in their constructor and then never modify /// them again. As long as care is taken to ensure that initial field values are visible to /// other threads before publishing the immutable object itself, immutable objects are /// completely thread-safe. /// /// c. Atomic state objects -- Locks typically are taken when several pieces of state must be updated atomically. In /// other words, there is a window in which state is inconsistent, and that window must /// be protected from view by locking. However, if a new object is created each time state /// changes (or state changes substantially), then during creation the new object is only /// visible to a single thread. Once construction is complete, an assignment (guaranteed /// atomic) can replace the old state object with the new state object, thus publishing a /// consistent view to all threads. /// /// d. Retry -- When several threads contend over shared state which only one is allowed to possess, it is possible /// to avoid locking by repeatedly attempting to acquire the shared state. The CompareExchange method /// is useful for atomically ensuring that only one thread succeeds, and other threads are notified that /// they must retry. /// /// 4. All variables which can be written by multiple threads are marked "SHARED STATE". /// </remarks> internal sealed class XHashtable<TValue> { private XHashtableState _state; // SHARED STATE: Contains all XHashtable state, so it can be atomically swapped when resizes occur /// <summary> /// Prototype of function which is called to extract a string key value from a hashed value. /// Returns null if the hashed value is invalid (e.g. value has been released due to a WeakReference TValue being cleaned up). /// </summary> public delegate string? ExtractKeyDelegate(TValue value); /// <summary> /// Construct a new XHashtable with the specified starting capacity. /// </summary> public XHashtable(ExtractKeyDelegate extractKey, int capacity) { _state = new XHashtableState(extractKey, capacity); } /// <summary> /// Get an existing value from the hash table. Return false if no such value exists. /// </summary> public bool TryGetValue(string key, int index, int count, [MaybeNullWhen(false)] out TValue value) { return _state.TryGetValue(key, index, count, out value); } /// <summary> /// Add a value to the hash table, hashed based on a string key embedded in it. Return the added value (may be a different object than "value"). /// </summary> public TValue Add(TValue value) { TValue newValue; // Loop until value is in hash table while (true) { // Add new value // XHashtableState.TryAdd returns false if hash table is not big enough if (_state.TryAdd(value, out newValue)) return newValue; // PUBLISH (state) // Hash table was not big enough, so resize it. // We only want one thread to perform a resize, as it is an expensive operation // First thread will perform resize; waiting threads will call Resize(), but should immediately // return since there will almost always be space in the hash table resized by the first thread. lock (this) { XHashtableState newState = _state.Resize(); // Use memory barrier to ensure that the resized XHashtableState object is fully constructed before it is assigned Thread.MemoryBarrier(); _state = newState; } } } /// <summary> /// This class contains all the hash table state. Rather than creating a bucket object, buckets are structs /// packed into an array. Buckets with the same truncated hash code are linked into lists, so that collisions /// can be disambiguated. /// </summary> /// <remarks> /// Note that the "buckets" and "entries" arrays are never themselves written by multiple threads. Instead, the /// *contents* of the array are written by multiple threads. Resizing the hash table does not modify these variables, /// or even modify the contents of these variables. Instead, resizing makes an entirely new XHashtableState object /// in which all entries are rehashed. This strategy allows reader threads to continue finding values in the "old" /// XHashtableState, while writer threads (those that need to add a new value to the table) are blocked waiting for /// the resize to complete. /// </remarks> private sealed class XHashtableState { private readonly int[] _buckets; // Buckets contain indexes into entries array (bucket values are SHARED STATE) private readonly Entry[] _entries; // Entries contain linked lists of buckets (next pointers are SHARED STATE) private int _numEntries; // SHARED STATE: Current number of entries (including orphaned entries) private readonly ExtractKeyDelegate _extractKey; // Delegate called in order to extract string key embedded in hashed TValue private const int EndOfList = 0; // End of linked list marker private const int FullList = -1; // Indicates entries should not be added to end of linked list /// <summary> /// Construct a new XHashtableState object with the specified capacity. /// </summary> public XHashtableState(ExtractKeyDelegate extractKey, int capacity) { Debug.Assert((capacity & (capacity - 1)) == 0, "capacity must be a power of 2"); Debug.Assert(extractKey != null, "extractKey may not be null"); // Initialize hash table data structures, with specified maximum capacity _buckets = new int[capacity]; _entries = new Entry[capacity]; // Save delegate _extractKey = extractKey; } /// <summary> /// If this table is not full, then just return "this". Otherwise, create and return a new table with /// additional capacity, and rehash all values in the table. /// </summary> public XHashtableState Resize() { // No need to resize if there are open entries if (_numEntries < _buckets.Length) return this; int newSize = 0; // Determine capacity of resized hash table by first counting number of valid, non-orphaned entries // As this count proceeds, close all linked lists so that no additional entries can be added to them for (int bucketIdx = 0; bucketIdx < _buckets.Length; bucketIdx++) { int entryIdx = _buckets[bucketIdx]; if (entryIdx == EndOfList) { // Replace EndOfList with FullList, so that any threads still attempting to add will be forced to resize entryIdx = Interlocked.CompareExchange(ref _buckets[bucketIdx], FullList, EndOfList); } // Loop until we've guaranteed that the list has been counted and closed to further adds while (entryIdx > EndOfList) { // Count each valid entry if (_extractKey(_entries[entryIdx].Value) != null) newSize++; if (_entries[entryIdx].Next == EndOfList) { // Replace EndOfList with FullList, so that any threads still attempting to add will be forced to resize entryIdx = Interlocked.CompareExchange(ref _entries[entryIdx].Next, FullList, EndOfList); } else { // Move to next entry in the list entryIdx = _entries[entryIdx].Next; } } Debug.Assert(entryIdx == EndOfList, "Resize() should only be called by one thread"); } // Double number of valid entries; if result is less than current capacity, then use current capacity if (newSize < _buckets.Length / 2) { newSize = _buckets.Length; } else { newSize = _buckets.Length * 2; if (newSize < 0) throw new OverflowException(); } // Create new hash table with additional capacity XHashtableState newHashtable = new XHashtableState(_extractKey, newSize); // Rehash names (TryAdd will always succeed, since we won't fill the new table) // Do not simply walk over entries and add them to table, as that would add orphaned // entries. Instead, walk the linked lists and add each name. for (int bucketIdx = 0; bucketIdx < _buckets.Length; bucketIdx++) { int entryIdx = _buckets[bucketIdx]; while (entryIdx > EndOfList) { newHashtable.TryAdd(_entries[entryIdx].Value, out _); entryIdx = _entries[entryIdx].Next; } Debug.Assert(entryIdx == FullList, "Linked list should have been closed when it was counted"); } return newHashtable; } /// <summary> /// Attempt to find "key" in the table. If the key exists, return the associated value in "value" and /// return true. Otherwise return false. /// </summary> public bool TryGetValue(string key, int index, int count, [MaybeNullWhen(false)] out TValue value) { int hashCode = ComputeHashCode(key, index, count); int entryIndex = 0; // If a matching entry is found, return its value if (FindEntry(hashCode, key, index, count, ref entryIndex)) { value = _entries[entryIndex].Value; return true; } // No matching entry found, so return false value = default(TValue); return false; } /// <summary> /// Attempt to add "value" to the table, hashed by an embedded string key. If a value having the same key already exists, /// then return the existing value in "newValue". Otherwise, return the newly added value in "newValue". /// /// If the hash table is full, return false. Otherwise, return true. /// </summary> public bool TryAdd(TValue value, out TValue newValue) { int newEntry, entryIndex; string? key; int hashCode; // Assume "value" will be added and returned as "newValue" newValue = value; // Extract the key from the value. If it's null, then value is invalid and does not need to be added to table. key = _extractKey(value); if (key == null) return true; // Compute hash code over entire length of key hashCode = ComputeHashCode(key, 0, key.Length); // Assume value is not yet in the hash table, and prepare to add it (if table is full, return false). // Use the entry index returned from Increment, which will never be zero, as zero conflicts with EndOfList. // Although this means that the first entry will never be used, it avoids the need to initialize all // starting buckets to the EndOfList value. newEntry = Interlocked.Increment(ref _numEntries); if (newEntry < 0 || newEntry >= _buckets.Length) return false; _entries[newEntry].Value = value; _entries[newEntry].HashCode = hashCode; // Ensure that all writes to the entry can't be reordered past this barrier (or other threads might see new entry // in list before entry has been initialized!). Thread.MemoryBarrier(); // Loop until a matching entry is found, a new entry is added, or linked list is found to be full entryIndex = 0; while (!FindEntry(hashCode, key, 0, key.Length, ref entryIndex)) { // PUBLISH (buckets slot) // No matching entry found, so add the new entry to the end of the list ("entryIndex" is index of last entry) if (entryIndex == 0) entryIndex = Interlocked.CompareExchange(ref _buckets[hashCode & (_buckets.Length - 1)], newEntry, EndOfList); else entryIndex = Interlocked.CompareExchange(ref _entries[entryIndex].Next, newEntry, EndOfList); // Return true only if the CompareExchange succeeded (happens when replaced value is EndOfList). // Return false if the linked list turned out to be full because another thread is currently resizing // the hash table. In this case, entries[newEntry] is orphaned (not part of any linked list) and the // Add needs to be performed on the new hash table. Otherwise, keep looping, looking for new end of list. if (entryIndex <= EndOfList) return entryIndex == EndOfList; } // Another thread already added the value while this thread was trying to add, so return that instance instead. // Note that entries[newEntry] will be orphaned (not part of any linked list) in this case newValue = _entries[entryIndex].Value; return true; } /// <summary> /// Searches a linked list of entries, beginning at "entryIndex". If "entryIndex" is 0, then search starts at a hash bucket instead. /// Each entry in the list is matched against the (hashCode, key, index, count) key. If a matching entry is found, then its /// entry index is returned in "entryIndex" and true is returned. If no matching entry is found, then the index of the last entry /// in the list (or 0 if list is empty) is returned in "entryIndex" and false is returned. /// </summary> /// <remarks> /// This method has the side effect of removing invalid entries from the list as it is traversed. /// </remarks> private bool FindEntry(int hashCode, string key, int index, int count, ref int entryIndex) { int previousIndex = entryIndex; int currentIndex; // Set initial value of currentIndex to index of the next entry following entryIndex if (previousIndex == 0) currentIndex = _buckets[hashCode & (_buckets.Length - 1)]; else currentIndex = previousIndex; // Loop while not at end of list while (currentIndex > EndOfList) { // Check for matching hash code, then matching key if (_entries[currentIndex].HashCode == hashCode) { string? keyCompare = _extractKey(_entries[currentIndex].Value); // If the key is invalid, then attempt to remove the current entry from the linked list. // This is thread-safe in the case where the Next field points to another entry, since once a Next field points // to another entry, it will never be modified to be EndOfList or FullList. if (keyCompare == null) { if (_entries[currentIndex].Next > EndOfList) { // PUBLISH (buckets slot or entries slot) // Entry is invalid, so modify previous entry to point to its next entry _entries[currentIndex].Value = default(TValue)!; currentIndex = _entries[currentIndex].Next; if (previousIndex == 0) _buckets[hashCode & (_buckets.Length - 1)] = currentIndex; else _entries[previousIndex].Next = currentIndex; continue; } } else { // Valid key, so compare keys if (count == keyCompare.Length && string.CompareOrdinal(key, index, keyCompare, 0, count) == 0) { // Found match, so return true and matching entry in list entryIndex = currentIndex; return true; } } } // Move to next entry previousIndex = currentIndex; currentIndex = _entries[currentIndex].Next; } // Return false and last entry in list entryIndex = previousIndex; return false; } /// <summary> /// Compute hash code for a string key (index, count substring of "key"). The algorithm used is the same on used in NameTable.cs in System.Xml. /// </summary> private static int ComputeHashCode(string key, int index, int count) { Debug.Assert(key != null, "key should have been checked previously for null"); return string.GetHashCode(key.AsSpan(index, count)); } /// <summary> /// Hash table entry. The "Value" and "HashCode" fields are filled during initialization, and are never changed. The "Next" /// field is updated when a new entry is chained to this one, and therefore care must be taken to ensure that updates to /// this field are thread-safe. /// </summary> private struct Entry { public TValue Value; // Hashed value public int HashCode; // Hash code of string key (equal to extractKey(Value).GetHashCode()) public int Next; // SHARED STATE: Points to next entry in linked list } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReaderOptions.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.Metadata { [Flags] public enum MetadataReaderOptions { /// <summary> /// All options are disabled. /// </summary> None = 0x0, /// <summary> /// The options that are used when a <see cref="MetadataReader"/> is obtained /// via an overload that does not take a <see cref="MetadataReaderOptions"/> /// argument. /// </summary> Default = ApplyWindowsRuntimeProjections, /// <summary> /// Windows Runtime projections are enabled (on by default). /// </summary> ApplyWindowsRuntimeProjections = 0x1 } }
// 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.Metadata { [Flags] public enum MetadataReaderOptions { /// <summary> /// All options are disabled. /// </summary> None = 0x0, /// <summary> /// The options that are used when a <see cref="MetadataReader"/> is obtained /// via an overload that does not take a <see cref="MetadataReaderOptions"/> /// argument. /// </summary> Default = ApplyWindowsRuntimeProjections, /// <summary> /// Windows Runtime projections are enabled (on by default). /// </summary> ApplyWindowsRuntimeProjections = 0x1 } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadataCachedInformation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.Collections.Generic; using Microsoft.Win32; namespace System.Diagnostics.Eventing.Reader { /// <summary> /// This class does not expose underlying Provider metadata objects. Instead it /// exposes a limited set of Provider metadata information from the cache. The reason /// for this is so the cache can easily Dispose the metadata object without worrying /// about who is using it. /// </summary> internal sealed class ProviderMetadataCachedInformation { private readonly Dictionary<ProviderMetadataId, CacheItem> _cache; private readonly int _maximumCacheSize; private readonly EventLogSession _session; private readonly string _logfile; private sealed class ProviderMetadataId { public ProviderMetadataId(string providerName, CultureInfo cultureInfo) { ProviderName = providerName; TheCultureInfo = cultureInfo; } public override bool Equals(object obj) { ProviderMetadataId rhs = obj as ProviderMetadataId; if (rhs == null) return false; if (ProviderName.Equals(rhs.ProviderName) && (TheCultureInfo == rhs.TheCultureInfo)) return true; return false; } public override int GetHashCode() { return ProviderName.GetHashCode() ^ TheCultureInfo.GetHashCode(); } public string ProviderName { get; } public CultureInfo TheCultureInfo { get; } } private sealed class CacheItem { public CacheItem(ProviderMetadata pm) { ProviderMetadata = pm; TheTime = DateTime.Now; } public DateTime TheTime { get; set; } public ProviderMetadata ProviderMetadata { get; } } public ProviderMetadataCachedInformation(EventLogSession session, string logfile, int maximumCacheSize) { Debug.Assert(session != null); _session = session; _logfile = logfile; _cache = new Dictionary<ProviderMetadataId, CacheItem>(); _maximumCacheSize = maximumCacheSize; } private bool IsCacheFull() { return _cache.Count == _maximumCacheSize; } private bool IsProviderinCache(ProviderMetadataId key) { return _cache.ContainsKey(key); } private void DeleteCacheEntry(ProviderMetadataId key) { if (!IsProviderinCache(key)) return; CacheItem value = _cache[key]; _cache.Remove(key); value.ProviderMetadata.Dispose(); } private void AddCacheEntry(ProviderMetadataId key, ProviderMetadata pm) { if (IsCacheFull()) FlushOldestEntry(); CacheItem value = new CacheItem(pm); _cache.Add(key, value); return; } private void FlushOldestEntry() { double maxPassedTime = -10; DateTime timeNow = DateTime.Now; ProviderMetadataId keyToDelete = null; // Get the entry in the cache which was not accessed for the longest time. foreach (KeyValuePair<ProviderMetadataId, CacheItem> kvp in _cache) { // The time difference (in ms) between the timeNow and the last used time of each entry TimeSpan timeDifference = timeNow.Subtract(kvp.Value.TheTime); // For the "unused" items (with ReferenceCount == 0) -> can possible be deleted. if (timeDifference.TotalMilliseconds >= maxPassedTime) { maxPassedTime = timeDifference.TotalMilliseconds; keyToDelete = kvp.Key; } } if (keyToDelete != null) DeleteCacheEntry(keyToDelete); } private static void UpdateCacheValueInfoForHit(CacheItem cacheItem) { cacheItem.TheTime = DateTime.Now; } private ProviderMetadata GetProviderMetadata(ProviderMetadataId key) { if (!IsProviderinCache(key)) { ProviderMetadata pm; try { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo, _logfile); } catch (EventLogNotFoundException) { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo); } AddCacheEntry(key, pm); return pm; } else { CacheItem cacheItem = _cache[key]; ProviderMetadata pm = cacheItem.ProviderMetadata; // check Provider metadata to be sure it's hasn't been // uninstalled since last time it was used. try { UpdateCacheValueInfoForHit(cacheItem); } catch (EventLogException) { DeleteCacheEntry(key); try { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo, _logfile); } catch (EventLogNotFoundException) { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo); } AddCacheEntry(key, pm); } return pm; } } public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); try { ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent); } catch (EventLogNotFoundException) { return null; } } } public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle, string[] values) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); try { return NativeWrapper.EvtFormatMessageFormatDescription(pm.Handle, eventHandle, values); } catch (EventLogNotFoundException) { return null; } } } public string GetLevelDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageLevel); } } public string GetOpcodeDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageOpcode); } } public string GetTaskDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageTask); } } public IEnumerable<string> GetKeywordDisplayNames(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderKeywords(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageKeyword); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.Collections.Generic; using Microsoft.Win32; namespace System.Diagnostics.Eventing.Reader { /// <summary> /// This class does not expose underlying Provider metadata objects. Instead it /// exposes a limited set of Provider metadata information from the cache. The reason /// for this is so the cache can easily Dispose the metadata object without worrying /// about who is using it. /// </summary> internal sealed class ProviderMetadataCachedInformation { private readonly Dictionary<ProviderMetadataId, CacheItem> _cache; private readonly int _maximumCacheSize; private readonly EventLogSession _session; private readonly string _logfile; private sealed class ProviderMetadataId { public ProviderMetadataId(string providerName, CultureInfo cultureInfo) { ProviderName = providerName; TheCultureInfo = cultureInfo; } public override bool Equals(object obj) { ProviderMetadataId rhs = obj as ProviderMetadataId; if (rhs == null) return false; if (ProviderName.Equals(rhs.ProviderName) && (TheCultureInfo == rhs.TheCultureInfo)) return true; return false; } public override int GetHashCode() { return ProviderName.GetHashCode() ^ TheCultureInfo.GetHashCode(); } public string ProviderName { get; } public CultureInfo TheCultureInfo { get; } } private sealed class CacheItem { public CacheItem(ProviderMetadata pm) { ProviderMetadata = pm; TheTime = DateTime.Now; } public DateTime TheTime { get; set; } public ProviderMetadata ProviderMetadata { get; } } public ProviderMetadataCachedInformation(EventLogSession session, string logfile, int maximumCacheSize) { Debug.Assert(session != null); _session = session; _logfile = logfile; _cache = new Dictionary<ProviderMetadataId, CacheItem>(); _maximumCacheSize = maximumCacheSize; } private bool IsCacheFull() { return _cache.Count == _maximumCacheSize; } private bool IsProviderinCache(ProviderMetadataId key) { return _cache.ContainsKey(key); } private void DeleteCacheEntry(ProviderMetadataId key) { if (!IsProviderinCache(key)) return; CacheItem value = _cache[key]; _cache.Remove(key); value.ProviderMetadata.Dispose(); } private void AddCacheEntry(ProviderMetadataId key, ProviderMetadata pm) { if (IsCacheFull()) FlushOldestEntry(); CacheItem value = new CacheItem(pm); _cache.Add(key, value); return; } private void FlushOldestEntry() { double maxPassedTime = -10; DateTime timeNow = DateTime.Now; ProviderMetadataId keyToDelete = null; // Get the entry in the cache which was not accessed for the longest time. foreach (KeyValuePair<ProviderMetadataId, CacheItem> kvp in _cache) { // The time difference (in ms) between the timeNow and the last used time of each entry TimeSpan timeDifference = timeNow.Subtract(kvp.Value.TheTime); // For the "unused" items (with ReferenceCount == 0) -> can possible be deleted. if (timeDifference.TotalMilliseconds >= maxPassedTime) { maxPassedTime = timeDifference.TotalMilliseconds; keyToDelete = kvp.Key; } } if (keyToDelete != null) DeleteCacheEntry(keyToDelete); } private static void UpdateCacheValueInfoForHit(CacheItem cacheItem) { cacheItem.TheTime = DateTime.Now; } private ProviderMetadata GetProviderMetadata(ProviderMetadataId key) { if (!IsProviderinCache(key)) { ProviderMetadata pm; try { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo, _logfile); } catch (EventLogNotFoundException) { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo); } AddCacheEntry(key, pm); return pm; } else { CacheItem cacheItem = _cache[key]; ProviderMetadata pm = cacheItem.ProviderMetadata; // check Provider metadata to be sure it's hasn't been // uninstalled since last time it was used. try { UpdateCacheValueInfoForHit(cacheItem); } catch (EventLogException) { DeleteCacheEntry(key); try { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo, _logfile); } catch (EventLogNotFoundException) { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo); } AddCacheEntry(key, pm); } return pm; } } public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); try { ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent); } catch (EventLogNotFoundException) { return null; } } } public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle, string[] values) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); try { return NativeWrapper.EvtFormatMessageFormatDescription(pm.Handle, eventHandle, values); } catch (EventLogNotFoundException) { return null; } } } public string GetLevelDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageLevel); } } public string GetOpcodeDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageOpcode); } } public string GetTaskDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageTask); } } public IEnumerable<string> GetKeywordDisplayNames(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderKeywords(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageKeyword); } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Generics/Typeof/Struct02.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; public struct ValX0 { } public struct ValY0 { } public struct ValX1<T> { } public struct ValY1<T> { } public struct ValX2<T, U> { } public struct ValY2<T, U> { } public struct ValX3<T, U, V> { } public struct ValY3<T, U, V> { } public class RefX0 { } public class RefY0 { } public class RefX1<T> { } public class RefY1<T> { } public class RefX2<T, U> { } public class RefY2<T, U> { } public class RefX3<T, U, V> { } public class RefY3<T, U, V> { } public struct Gen<T, U> { public T Fld1; public U Fld2; public Gen(T fld1, U fld2) { Fld1 = fld1; Fld2 = fld2; } public bool InstVerify(System.Type t1, System.Type t2) { bool result = true; if (!(typeof(T).Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Gen<T, U>)); } if (!(typeof(U).Equals(t2))) { result = false; Console.WriteLine("Failed to verify type of Fld2 in: " + typeof(Gen<T, U>)); } return result; } } public class Test_Struct02 { 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 Gen<int, int>(new int(), new int())).InstVerify(typeof(int), typeof(int))); Eval((new Gen<int, double>(new int(), new double())).InstVerify(typeof(int), typeof(double))); Eval((new Gen<int, string>(new int(), "string")).InstVerify(typeof(int), typeof(string))); Eval((new Gen<int, object>(new int(), new object())).InstVerify(typeof(int), typeof(object))); Eval((new Gen<int, Guid>(new int(), new Guid())).InstVerify(typeof(int), typeof(Guid))); Eval((new Gen<int, RefX1<int>>(new int(), new RefX1<int>())).InstVerify(typeof(int), typeof(RefX1<int>))); Eval((new Gen<int, RefX1<string>>(new int(), new RefX1<string>())).InstVerify(typeof(int), typeof(RefX1<string>))); Eval((new Gen<int, RefX1<int[][, , ,][]>>(new int(), new RefX1<int[][, , ,][]>())).InstVerify(typeof(int), typeof(RefX1<int[][, , ,][]>))); Eval((new Gen<int, ValX1<int>>(new int(), new ValX1<int>())).InstVerify(typeof(int), typeof(ValX1<int>))); Eval((new Gen<int, ValX1<string>>(new int(), new ValX1<string>())).InstVerify(typeof(int), typeof(ValX1<string>))); Eval((new Gen<int, ValX1<int[][, , ,][]>>(new int(), new ValX1<int[][, , ,][]>())).InstVerify(typeof(int), typeof(ValX1<int[][, , ,][]>))); Eval((new Gen<double, int>(new double(), new int())).InstVerify(typeof(double), typeof(int))); Eval((new Gen<double, double>(new double(), new double())).InstVerify(typeof(double), typeof(double))); Eval((new Gen<double, string>(new double(), "string")).InstVerify(typeof(double), typeof(string))); Eval((new Gen<double, object>(new double(), new object())).InstVerify(typeof(double), typeof(object))); Eval((new Gen<double, Guid>(new double(), new Guid())).InstVerify(typeof(double), typeof(Guid))); Eval((new Gen<double, RefX1<double>>(new double(), new RefX1<double>())).InstVerify(typeof(double), typeof(RefX1<double>))); Eval((new Gen<double, RefX1<string>>(new double(), new RefX1<string>())).InstVerify(typeof(double), typeof(RefX1<string>))); Eval((new Gen<double, RefX1<double[][, , ,][]>>(new double(), new RefX1<double[][, , ,][]>())).InstVerify(typeof(double), typeof(RefX1<double[][, , ,][]>))); Eval((new Gen<double, ValX1<double>>(new double(), new ValX1<double>())).InstVerify(typeof(double), typeof(ValX1<double>))); Eval((new Gen<double, ValX1<string>>(new double(), new ValX1<string>())).InstVerify(typeof(double), typeof(ValX1<string>))); Eval((new Gen<double, ValX1<double[][, , ,][]>>(new double(), new ValX1<double[][, , ,][]>())).InstVerify(typeof(double), typeof(ValX1<double[][, , ,][]>))); Eval((new Gen<string, int>("string", new int())).InstVerify(typeof(string), typeof(int))); Eval((new Gen<string, double>("string", new double())).InstVerify(typeof(string), typeof(double))); Eval((new Gen<string, string>("string", "string")).InstVerify(typeof(string), typeof(string))); Eval((new Gen<string, object>("string", new object())).InstVerify(typeof(string), typeof(object))); Eval((new Gen<string, Guid>("string", new Guid())).InstVerify(typeof(string), typeof(Guid))); Eval((new Gen<string, RefX1<string>>("string", new RefX1<string>())).InstVerify(typeof(string), typeof(RefX1<string>))); Eval((new Gen<string, RefX1<string>>("string", new RefX1<string>())).InstVerify(typeof(string), typeof(RefX1<string>))); Eval((new Gen<string, RefX1<string[][, , ,][]>>("string", new RefX1<string[][, , ,][]>())).InstVerify(typeof(string), typeof(RefX1<string[][, , ,][]>))); Eval((new Gen<string, ValX1<string>>("string", new ValX1<string>())).InstVerify(typeof(string), typeof(ValX1<string>))); Eval((new Gen<string, ValX1<string>>("string", new ValX1<string>())).InstVerify(typeof(string), typeof(ValX1<string>))); Eval((new Gen<string, ValX1<string[][, , ,][]>>("string", new ValX1<string[][, , ,][]>())).InstVerify(typeof(string), typeof(ValX1<string[][, , ,][]>))); Eval((new Gen<object, int>(new object(), new int())).InstVerify(typeof(object), typeof(int))); Eval((new Gen<object, double>(new object(), new double())).InstVerify(typeof(object), typeof(double))); Eval((new Gen<object, string>(new object(), "string")).InstVerify(typeof(object), typeof(string))); Eval((new Gen<object, object>(new object(), new object())).InstVerify(typeof(object), typeof(object))); Eval((new Gen<object, Guid>(new object(), new Guid())).InstVerify(typeof(object), typeof(Guid))); Eval((new Gen<object, RefX1<object>>(new object(), new RefX1<object>())).InstVerify(typeof(object), typeof(RefX1<object>))); Eval((new Gen<object, RefX1<string>>(new object(), new RefX1<string>())).InstVerify(typeof(object), typeof(RefX1<string>))); Eval((new Gen<object, RefX1<object[][, , ,][]>>(new object(), new RefX1<object[][, , ,][]>())).InstVerify(typeof(object), typeof(RefX1<object[][, , ,][]>))); Eval((new Gen<object, ValX1<object>>(new object(), new ValX1<object>())).InstVerify(typeof(object), typeof(ValX1<object>))); Eval((new Gen<object, ValX1<string>>(new object(), new ValX1<string>())).InstVerify(typeof(object), typeof(ValX1<string>))); Eval((new Gen<object, ValX1<object[][, , ,][]>>(new object(), new ValX1<object[][, , ,][]>())).InstVerify(typeof(object), typeof(ValX1<object[][, , ,][]>))); Eval((new Gen<Guid, int>(new Guid(), new int())).InstVerify(typeof(Guid), typeof(int))); Eval((new Gen<Guid, double>(new Guid(), new double())).InstVerify(typeof(Guid), typeof(double))); Eval((new Gen<Guid, string>(new Guid(), "string")).InstVerify(typeof(Guid), typeof(string))); Eval((new Gen<Guid, object>(new Guid(), new object())).InstVerify(typeof(Guid), typeof(object))); Eval((new Gen<Guid, Guid>(new Guid(), new Guid())).InstVerify(typeof(Guid), typeof(Guid))); Eval((new Gen<Guid, RefX1<Guid>>(new Guid(), new RefX1<Guid>())).InstVerify(typeof(Guid), typeof(RefX1<Guid>))); Eval((new Gen<Guid, RefX1<string>>(new Guid(), new RefX1<string>())).InstVerify(typeof(Guid), typeof(RefX1<string>))); Eval((new Gen<Guid, RefX1<Guid[][, , ,][]>>(new Guid(), new RefX1<Guid[][, , ,][]>())).InstVerify(typeof(Guid), typeof(RefX1<Guid[][, , ,][]>))); Eval((new Gen<Guid, ValX1<Guid>>(new Guid(), new ValX1<Guid>())).InstVerify(typeof(Guid), typeof(ValX1<Guid>))); Eval((new Gen<Guid, ValX1<string>>(new Guid(), new ValX1<string>())).InstVerify(typeof(Guid), typeof(ValX1<string>))); Eval((new Gen<Guid, ValX1<Guid[][, , ,][]>>(new Guid(), new ValX1<Guid[][, , ,][]>())).InstVerify(typeof(Guid), typeof(ValX1<Guid[][, , ,][]>))); Eval((new Gen<RefX1<int>, int>(new RefX1<int>(), new int())).InstVerify(typeof(RefX1<int>), typeof(int))); Eval((new Gen<RefX1<long>, double>(new RefX1<long>(), new double())).InstVerify(typeof(RefX1<long>), typeof(double))); Eval((new Gen<RefX1<long>, string>(new RefX1<long>(), "string")).InstVerify(typeof(RefX1<long>), typeof(string))); Eval((new Gen<RefX1<long>, object>(new RefX1<long>(), new object())).InstVerify(typeof(RefX1<long>), typeof(object))); Eval((new Gen<RefX1<long>, Guid>(new RefX1<long>(), new Guid())).InstVerify(typeof(RefX1<long>), typeof(Guid))); Eval((new Gen<RefX1<long>, RefX1<RefX1<long>>>(new RefX1<long>(), new RefX1<RefX1<long>>())).InstVerify(typeof(RefX1<long>), typeof(RefX1<RefX1<long>>))); Eval((new Gen<RefX1<long>, RefX1<string>>(new RefX1<long>(), new RefX1<string>())).InstVerify(typeof(RefX1<long>), typeof(RefX1<string>))); Eval((new Gen<RefX1<long>, RefX1<RefX1<long[][, , ,][]>>>(new RefX1<long>(), new RefX1<RefX1<long[][, , ,][]>>())).InstVerify(typeof(RefX1<long>), typeof(RefX1<RefX1<long[][, , ,][]>>))); Eval((new Gen<RefX1<long>, ValX1<RefX1<long>>>(new RefX1<long>(), new ValX1<RefX1<long>>())).InstVerify(typeof(RefX1<long>), typeof(ValX1<RefX1<long>>))); Eval((new Gen<RefX1<long>, ValX1<string>>(new RefX1<long>(), new ValX1<string>())).InstVerify(typeof(RefX1<long>), typeof(ValX1<string>))); Eval((new Gen<RefX1<long>, ValX1<RefX1<long>[][, , ,][]>>(new RefX1<long>(), new ValX1<RefX1<long>[][, , ,][]>())).InstVerify(typeof(RefX1<long>), typeof(ValX1<RefX1<long>[][, , ,][]>))); Eval((new Gen<ValX1<string>, int>(new ValX1<string>(), new int())).InstVerify(typeof(ValX1<string>), typeof(int))); Eval((new Gen<ValX1<string>, double>(new ValX1<string>(), new double())).InstVerify(typeof(ValX1<string>), typeof(double))); Eval((new Gen<ValX1<string>, string>(new ValX1<string>(), "string")).InstVerify(typeof(ValX1<string>), typeof(string))); Eval((new Gen<ValX1<string>, object>(new ValX1<string>(), new object())).InstVerify(typeof(ValX1<string>), typeof(object))); Eval((new Gen<ValX1<string>, Guid>(new ValX1<string>(), new Guid())).InstVerify(typeof(ValX1<string>), typeof(Guid))); Eval((new Gen<ValX1<string>, RefX1<ValX1<string>>>(new ValX1<string>(), new RefX1<ValX1<string>>())).InstVerify(typeof(ValX1<string>), typeof(RefX1<ValX1<string>>))); Eval((new Gen<ValX1<string>, RefX1<string>>(new ValX1<string>(), new RefX1<string>())).InstVerify(typeof(ValX1<string>), typeof(RefX1<string>))); Eval((new Gen<ValX1<string>, RefX1<ValX1<string>[][, , ,][]>>(new ValX1<string>(), new RefX1<ValX1<string>[][, , ,][]>())).InstVerify(typeof(ValX1<string>), typeof(RefX1<ValX1<string>[][, , ,][]>))); Eval((new Gen<ValX1<string>, ValX1<ValX1<string>>>(new ValX1<string>(), new ValX1<ValX1<string>>())).InstVerify(typeof(ValX1<string>), typeof(ValX1<ValX1<string>>))); Eval((new Gen<ValX1<string>, ValX1<string>>(new ValX1<string>(), new ValX1<string>())).InstVerify(typeof(ValX1<string>), typeof(ValX1<string>))); Eval((new Gen<ValX1<string>, ValX1<ValX1<string>[][, , ,][]>>(new ValX1<string>(), new ValX1<ValX1<string>[][, , ,][]>())).InstVerify(typeof(ValX1<string>), typeof(ValX1<ValX1<string>[][, , ,][]>))); 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; public struct ValX0 { } public struct ValY0 { } public struct ValX1<T> { } public struct ValY1<T> { } public struct ValX2<T, U> { } public struct ValY2<T, U> { } public struct ValX3<T, U, V> { } public struct ValY3<T, U, V> { } public class RefX0 { } public class RefY0 { } public class RefX1<T> { } public class RefY1<T> { } public class RefX2<T, U> { } public class RefY2<T, U> { } public class RefX3<T, U, V> { } public class RefY3<T, U, V> { } public struct Gen<T, U> { public T Fld1; public U Fld2; public Gen(T fld1, U fld2) { Fld1 = fld1; Fld2 = fld2; } public bool InstVerify(System.Type t1, System.Type t2) { bool result = true; if (!(typeof(T).Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Gen<T, U>)); } if (!(typeof(U).Equals(t2))) { result = false; Console.WriteLine("Failed to verify type of Fld2 in: " + typeof(Gen<T, U>)); } return result; } } public class Test_Struct02 { 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 Gen<int, int>(new int(), new int())).InstVerify(typeof(int), typeof(int))); Eval((new Gen<int, double>(new int(), new double())).InstVerify(typeof(int), typeof(double))); Eval((new Gen<int, string>(new int(), "string")).InstVerify(typeof(int), typeof(string))); Eval((new Gen<int, object>(new int(), new object())).InstVerify(typeof(int), typeof(object))); Eval((new Gen<int, Guid>(new int(), new Guid())).InstVerify(typeof(int), typeof(Guid))); Eval((new Gen<int, RefX1<int>>(new int(), new RefX1<int>())).InstVerify(typeof(int), typeof(RefX1<int>))); Eval((new Gen<int, RefX1<string>>(new int(), new RefX1<string>())).InstVerify(typeof(int), typeof(RefX1<string>))); Eval((new Gen<int, RefX1<int[][, , ,][]>>(new int(), new RefX1<int[][, , ,][]>())).InstVerify(typeof(int), typeof(RefX1<int[][, , ,][]>))); Eval((new Gen<int, ValX1<int>>(new int(), new ValX1<int>())).InstVerify(typeof(int), typeof(ValX1<int>))); Eval((new Gen<int, ValX1<string>>(new int(), new ValX1<string>())).InstVerify(typeof(int), typeof(ValX1<string>))); Eval((new Gen<int, ValX1<int[][, , ,][]>>(new int(), new ValX1<int[][, , ,][]>())).InstVerify(typeof(int), typeof(ValX1<int[][, , ,][]>))); Eval((new Gen<double, int>(new double(), new int())).InstVerify(typeof(double), typeof(int))); Eval((new Gen<double, double>(new double(), new double())).InstVerify(typeof(double), typeof(double))); Eval((new Gen<double, string>(new double(), "string")).InstVerify(typeof(double), typeof(string))); Eval((new Gen<double, object>(new double(), new object())).InstVerify(typeof(double), typeof(object))); Eval((new Gen<double, Guid>(new double(), new Guid())).InstVerify(typeof(double), typeof(Guid))); Eval((new Gen<double, RefX1<double>>(new double(), new RefX1<double>())).InstVerify(typeof(double), typeof(RefX1<double>))); Eval((new Gen<double, RefX1<string>>(new double(), new RefX1<string>())).InstVerify(typeof(double), typeof(RefX1<string>))); Eval((new Gen<double, RefX1<double[][, , ,][]>>(new double(), new RefX1<double[][, , ,][]>())).InstVerify(typeof(double), typeof(RefX1<double[][, , ,][]>))); Eval((new Gen<double, ValX1<double>>(new double(), new ValX1<double>())).InstVerify(typeof(double), typeof(ValX1<double>))); Eval((new Gen<double, ValX1<string>>(new double(), new ValX1<string>())).InstVerify(typeof(double), typeof(ValX1<string>))); Eval((new Gen<double, ValX1<double[][, , ,][]>>(new double(), new ValX1<double[][, , ,][]>())).InstVerify(typeof(double), typeof(ValX1<double[][, , ,][]>))); Eval((new Gen<string, int>("string", new int())).InstVerify(typeof(string), typeof(int))); Eval((new Gen<string, double>("string", new double())).InstVerify(typeof(string), typeof(double))); Eval((new Gen<string, string>("string", "string")).InstVerify(typeof(string), typeof(string))); Eval((new Gen<string, object>("string", new object())).InstVerify(typeof(string), typeof(object))); Eval((new Gen<string, Guid>("string", new Guid())).InstVerify(typeof(string), typeof(Guid))); Eval((new Gen<string, RefX1<string>>("string", new RefX1<string>())).InstVerify(typeof(string), typeof(RefX1<string>))); Eval((new Gen<string, RefX1<string>>("string", new RefX1<string>())).InstVerify(typeof(string), typeof(RefX1<string>))); Eval((new Gen<string, RefX1<string[][, , ,][]>>("string", new RefX1<string[][, , ,][]>())).InstVerify(typeof(string), typeof(RefX1<string[][, , ,][]>))); Eval((new Gen<string, ValX1<string>>("string", new ValX1<string>())).InstVerify(typeof(string), typeof(ValX1<string>))); Eval((new Gen<string, ValX1<string>>("string", new ValX1<string>())).InstVerify(typeof(string), typeof(ValX1<string>))); Eval((new Gen<string, ValX1<string[][, , ,][]>>("string", new ValX1<string[][, , ,][]>())).InstVerify(typeof(string), typeof(ValX1<string[][, , ,][]>))); Eval((new Gen<object, int>(new object(), new int())).InstVerify(typeof(object), typeof(int))); Eval((new Gen<object, double>(new object(), new double())).InstVerify(typeof(object), typeof(double))); Eval((new Gen<object, string>(new object(), "string")).InstVerify(typeof(object), typeof(string))); Eval((new Gen<object, object>(new object(), new object())).InstVerify(typeof(object), typeof(object))); Eval((new Gen<object, Guid>(new object(), new Guid())).InstVerify(typeof(object), typeof(Guid))); Eval((new Gen<object, RefX1<object>>(new object(), new RefX1<object>())).InstVerify(typeof(object), typeof(RefX1<object>))); Eval((new Gen<object, RefX1<string>>(new object(), new RefX1<string>())).InstVerify(typeof(object), typeof(RefX1<string>))); Eval((new Gen<object, RefX1<object[][, , ,][]>>(new object(), new RefX1<object[][, , ,][]>())).InstVerify(typeof(object), typeof(RefX1<object[][, , ,][]>))); Eval((new Gen<object, ValX1<object>>(new object(), new ValX1<object>())).InstVerify(typeof(object), typeof(ValX1<object>))); Eval((new Gen<object, ValX1<string>>(new object(), new ValX1<string>())).InstVerify(typeof(object), typeof(ValX1<string>))); Eval((new Gen<object, ValX1<object[][, , ,][]>>(new object(), new ValX1<object[][, , ,][]>())).InstVerify(typeof(object), typeof(ValX1<object[][, , ,][]>))); Eval((new Gen<Guid, int>(new Guid(), new int())).InstVerify(typeof(Guid), typeof(int))); Eval((new Gen<Guid, double>(new Guid(), new double())).InstVerify(typeof(Guid), typeof(double))); Eval((new Gen<Guid, string>(new Guid(), "string")).InstVerify(typeof(Guid), typeof(string))); Eval((new Gen<Guid, object>(new Guid(), new object())).InstVerify(typeof(Guid), typeof(object))); Eval((new Gen<Guid, Guid>(new Guid(), new Guid())).InstVerify(typeof(Guid), typeof(Guid))); Eval((new Gen<Guid, RefX1<Guid>>(new Guid(), new RefX1<Guid>())).InstVerify(typeof(Guid), typeof(RefX1<Guid>))); Eval((new Gen<Guid, RefX1<string>>(new Guid(), new RefX1<string>())).InstVerify(typeof(Guid), typeof(RefX1<string>))); Eval((new Gen<Guid, RefX1<Guid[][, , ,][]>>(new Guid(), new RefX1<Guid[][, , ,][]>())).InstVerify(typeof(Guid), typeof(RefX1<Guid[][, , ,][]>))); Eval((new Gen<Guid, ValX1<Guid>>(new Guid(), new ValX1<Guid>())).InstVerify(typeof(Guid), typeof(ValX1<Guid>))); Eval((new Gen<Guid, ValX1<string>>(new Guid(), new ValX1<string>())).InstVerify(typeof(Guid), typeof(ValX1<string>))); Eval((new Gen<Guid, ValX1<Guid[][, , ,][]>>(new Guid(), new ValX1<Guid[][, , ,][]>())).InstVerify(typeof(Guid), typeof(ValX1<Guid[][, , ,][]>))); Eval((new Gen<RefX1<int>, int>(new RefX1<int>(), new int())).InstVerify(typeof(RefX1<int>), typeof(int))); Eval((new Gen<RefX1<long>, double>(new RefX1<long>(), new double())).InstVerify(typeof(RefX1<long>), typeof(double))); Eval((new Gen<RefX1<long>, string>(new RefX1<long>(), "string")).InstVerify(typeof(RefX1<long>), typeof(string))); Eval((new Gen<RefX1<long>, object>(new RefX1<long>(), new object())).InstVerify(typeof(RefX1<long>), typeof(object))); Eval((new Gen<RefX1<long>, Guid>(new RefX1<long>(), new Guid())).InstVerify(typeof(RefX1<long>), typeof(Guid))); Eval((new Gen<RefX1<long>, RefX1<RefX1<long>>>(new RefX1<long>(), new RefX1<RefX1<long>>())).InstVerify(typeof(RefX1<long>), typeof(RefX1<RefX1<long>>))); Eval((new Gen<RefX1<long>, RefX1<string>>(new RefX1<long>(), new RefX1<string>())).InstVerify(typeof(RefX1<long>), typeof(RefX1<string>))); Eval((new Gen<RefX1<long>, RefX1<RefX1<long[][, , ,][]>>>(new RefX1<long>(), new RefX1<RefX1<long[][, , ,][]>>())).InstVerify(typeof(RefX1<long>), typeof(RefX1<RefX1<long[][, , ,][]>>))); Eval((new Gen<RefX1<long>, ValX1<RefX1<long>>>(new RefX1<long>(), new ValX1<RefX1<long>>())).InstVerify(typeof(RefX1<long>), typeof(ValX1<RefX1<long>>))); Eval((new Gen<RefX1<long>, ValX1<string>>(new RefX1<long>(), new ValX1<string>())).InstVerify(typeof(RefX1<long>), typeof(ValX1<string>))); Eval((new Gen<RefX1<long>, ValX1<RefX1<long>[][, , ,][]>>(new RefX1<long>(), new ValX1<RefX1<long>[][, , ,][]>())).InstVerify(typeof(RefX1<long>), typeof(ValX1<RefX1<long>[][, , ,][]>))); Eval((new Gen<ValX1<string>, int>(new ValX1<string>(), new int())).InstVerify(typeof(ValX1<string>), typeof(int))); Eval((new Gen<ValX1<string>, double>(new ValX1<string>(), new double())).InstVerify(typeof(ValX1<string>), typeof(double))); Eval((new Gen<ValX1<string>, string>(new ValX1<string>(), "string")).InstVerify(typeof(ValX1<string>), typeof(string))); Eval((new Gen<ValX1<string>, object>(new ValX1<string>(), new object())).InstVerify(typeof(ValX1<string>), typeof(object))); Eval((new Gen<ValX1<string>, Guid>(new ValX1<string>(), new Guid())).InstVerify(typeof(ValX1<string>), typeof(Guid))); Eval((new Gen<ValX1<string>, RefX1<ValX1<string>>>(new ValX1<string>(), new RefX1<ValX1<string>>())).InstVerify(typeof(ValX1<string>), typeof(RefX1<ValX1<string>>))); Eval((new Gen<ValX1<string>, RefX1<string>>(new ValX1<string>(), new RefX1<string>())).InstVerify(typeof(ValX1<string>), typeof(RefX1<string>))); Eval((new Gen<ValX1<string>, RefX1<ValX1<string>[][, , ,][]>>(new ValX1<string>(), new RefX1<ValX1<string>[][, , ,][]>())).InstVerify(typeof(ValX1<string>), typeof(RefX1<ValX1<string>[][, , ,][]>))); Eval((new Gen<ValX1<string>, ValX1<ValX1<string>>>(new ValX1<string>(), new ValX1<ValX1<string>>())).InstVerify(typeof(ValX1<string>), typeof(ValX1<ValX1<string>>))); Eval((new Gen<ValX1<string>, ValX1<string>>(new ValX1<string>(), new ValX1<string>())).InstVerify(typeof(ValX1<string>), typeof(ValX1<string>))); Eval((new Gen<ValX1<string>, ValX1<ValX1<string>[][, , ,][]>>(new ValX1<string>(), new ValX1<ValX1<string>[][, , ,][]>())).InstVerify(typeof(ValX1<string>), typeof(ValX1<ValX1<string>[][, , ,][]>))); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Specifies the contract for a collection of service descriptors. /// </summary> public interface IServiceCollection : IList<ServiceDescriptor> { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Specifies the contract for a collection of service descriptors. /// </summary> public interface IServiceCollection : IList<ServiceDescriptor> { } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_ExclusiveOr.Double.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_ExclusiveOrDouble() { var test = new VectorBinaryOpTest__op_ExclusiveOrDouble(); // 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_ExclusiveOrDouble { 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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); 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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Double> _fld1; public Vector256<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_ExclusiveOrDouble testClass) { var result = _fld1 ^ _fld2; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_ExclusiveOrDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public VectorBinaryOpTest__op_ExclusiveOrDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr) ^ Unsafe.Read<Vector256<Double>>(_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(Vector256<Double>).GetMethod("op_ExclusiveOr", new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(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<Vector256<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Double>>(_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_ExclusiveOrDouble(); 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(Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != (BitConverter.DoubleToInt64Bits(left[0]) ^ BitConverter.DoubleToInt64Bits(right[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != (BitConverter.DoubleToInt64Bits(left[i]) ^ BitConverter.DoubleToInt64Bits(right[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_ExclusiveOr<Double>(Vector256<Double>, Vector256<Double>): {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_ExclusiveOrDouble() { var test = new VectorBinaryOpTest__op_ExclusiveOrDouble(); // 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_ExclusiveOrDouble { 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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); 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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Double> _fld1; public Vector256<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_ExclusiveOrDouble testClass) { var result = _fld1 ^ _fld2; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_ExclusiveOrDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public VectorBinaryOpTest__op_ExclusiveOrDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr) ^ Unsafe.Read<Vector256<Double>>(_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(Vector256<Double>).GetMethod("op_ExclusiveOr", new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(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<Vector256<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Double>>(_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_ExclusiveOrDouble(); 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(Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != (BitConverter.DoubleToInt64Bits(left[0]) ^ BitConverter.DoubleToInt64Bits(right[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != (BitConverter.DoubleToInt64Bits(left[i]) ^ BitConverter.DoubleToInt64Bits(right[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_ExclusiveOr<Double>(Vector256<Double>, Vector256<Double>): {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,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.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.Globalization; using System.Linq; using System.Runtime.Versioning; namespace System.Collections.Immutable { public readonly partial struct ImmutableArray<T> : IReadOnlyList<T>, IList<T>, IEquatable<ImmutableArray<T>>, IList, IImmutableArray, IStructuralComparable, IStructuralEquatable, IImmutableList<T> { /// <summary> /// Gets or sets the element at the specified index in the read-only list. /// </summary> /// <param name="index">The zero-based index of the element to get.</param> /// <returns>The element at the specified index in the read-only list.</returns> /// <exception cref="NotSupportedException">Always thrown from the setter.</exception> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> T IList<T>.this[int index] { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self[index]; } set { throw new NotSupportedException(); } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value> /// <c>true</c> if this instance is read only; otherwise, <c>false</c>. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection<T>.IsReadOnly { get { return true; } } /// <summary> /// Gets the number of array in the collection. /// </summary> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] int ICollection<T>.Count { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Length; } } /// <summary> /// Gets the number of array in the collection. /// </summary> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] int IReadOnlyCollection<T>.Count { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Length; } } /// <summary> /// Gets the element at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns> /// The element. /// </returns> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> T IReadOnlyList<T>.this[int index] { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self[index]; } } public ReadOnlySpan<T> AsSpan() => new ReadOnlySpan<T>(array); public ReadOnlyMemory<T> AsMemory() => new ReadOnlyMemory<T>(array); /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int IndexOf(T item) { var self = this; return self.IndexOf(item, 0, self.Length, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int IndexOf(T item, int startIndex, IEqualityComparer<T>? equalityComparer) { var self = this; return self.IndexOf(item, startIndex, self.Length - startIndex, equalityComparer); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int IndexOf(T item, int startIndex) { var self = this; return self.IndexOf(item, startIndex, self.Length - startIndex, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int IndexOf(T item, int startIndex, int count) { return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used. /// </param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowNullRefIfNotInitialized(); if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < self.Length, nameof(startIndex)); Requires.Range(count >= 0 && startIndex + count <= self.Length, nameof(count)); equalityComparer = equalityComparer ?? EqualityComparer<T>.Default; if (equalityComparer == EqualityComparer<T>.Default) { return Array.IndexOf(self.array!, item, startIndex, count); } else { for (int i = startIndex; i < startIndex + count; i++) { if (equalityComparer.Equals(self.array![i], item)) { return i; } } return -1; } } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int LastIndexOf(T item) { var self = this; if (self.IsEmpty) { return -1; } return self.LastIndexOf(item, self.Length - 1, self.Length, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int LastIndexOf(T item, int startIndex) { var self = this; if (self.IsEmpty && startIndex == 0) { return -1; } return self.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int LastIndexOf(T item, int startIndex, int count) { return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowNullRefIfNotInitialized(); if (startIndex == 0 && count == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < self.Length, nameof(startIndex)); Requires.Range(count >= 0 && startIndex - count + 1 >= 0, nameof(count)); equalityComparer = equalityComparer ?? EqualityComparer<T>.Default; if (equalityComparer == EqualityComparer<T>.Default) { return Array.LastIndexOf(self.array!, item, startIndex, count); } else { for (int i = startIndex; i >= startIndex - count + 1; i--) { if (equalityComparer.Equals(item, self.array![i])) { return i; } } return -1; } } /// <summary> /// Determines whether the specified item exists in the array. /// </summary> /// <param name="item">The item to search for.</param> /// <returns><c>true</c> if an equal value was found in the array; <c>false</c> otherwise.</returns> public bool Contains(T item) { return this.IndexOf(item) >= 0; } /// <summary> /// Returns a new array with the specified value inserted at the specified position. /// </summary> /// <param name="index">The 0-based index into the array at which the new item should be added.</param> /// <param name="item">The item to insert at the start of the array.</param> /// <returns>A new array.</returns> public ImmutableArray<T> Insert(int index, T item) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); if (self.IsEmpty) { return ImmutableArray.Create(item); } T[] tmp = new T[self.Length + 1]; tmp[index] = item; if (index != 0) { Array.Copy(self.array!, tmp, index); } if (index != self.Length) { Array.Copy(self.array!, index, tmp, index + 1, self.Length - index); } return new ImmutableArray<T>(tmp); } /// <summary> /// Inserts the specified values at the specified index. /// </summary> /// <param name="index">The index at which to insert the value.</param> /// <param name="items">The elements to insert.</param> /// <returns>The new immutable collection.</returns> public ImmutableArray<T> InsertRange(int index, IEnumerable<T> items) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); Requires.NotNull(items, nameof(items)); if (self.IsEmpty) { return ImmutableArray.CreateRange(items); } int count = ImmutableExtensions.GetCount(ref items); if (count == 0) { return self; } T[] tmp = new T[self.Length + count]; if (index != 0) { Array.Copy(self.array!, tmp, index); } if (index != self.Length) { Array.Copy(self.array!, index, tmp, index + count, self.Length - index); } // We want to copy over the items we need to insert. // Check first to see if items is a well-known collection we can call CopyTo // on to the array, which is an order of magnitude faster than foreach. // Otherwise, go to the fallback route where we manually enumerate the sequence // and place the items in the array one-by-one. if (!items.TryCopyTo(tmp, index)) { int sequenceIndex = index; foreach (T item in items) { tmp[sequenceIndex++] = item; } } return new ImmutableArray<T>(tmp); } /// <summary> /// Inserts the specified values at the specified index. /// </summary> /// <param name="index">The index at which to insert the value.</param> /// <param name="items">The elements to insert.</param> /// <returns>The new immutable collection.</returns> public ImmutableArray<T> InsertRange(int index, ImmutableArray<T> items) { var self = this; self.ThrowNullRefIfNotInitialized(); items.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); if (self.IsEmpty) { return items; } if (items.IsEmpty) { return self; } return self.InsertSpanRangeInternal(index, items.AsSpan()); } /// <summary> /// Returns a new array with the specified value inserted at the end. /// </summary> /// <param name="item">The item to insert at the end of the array.</param> /// <returns>A new array.</returns> public ImmutableArray<T> Add(T item) { var self = this; if (self.IsEmpty) { return ImmutableArray.Create(item); } return self.Insert(self.Length, item); } /// <summary> /// Adds the specified values to this list. /// </summary> /// <param name="items">The values to add.</param> /// <returns>A new list with the elements added.</returns> public ImmutableArray<T> AddRange(IEnumerable<T> items) { var self = this; return self.InsertRange(self.Length, items); } /// <summary> /// Adds the specified values to this list. /// </summary> /// <param name="items">The values to add.</param> /// <returns>A new list with the elements added.</returns> public ImmutableArray<T> AddRange(ImmutableArray<T> items) { var self = this; return self.InsertRange(self.Length, items); } /// <summary> /// Returns an array with the item at the specified position replaced. /// </summary> /// <param name="index">The index of the item to replace.</param> /// <param name="item">The new item.</param> /// <returns>The new array.</returns> public ImmutableArray<T> SetItem(int index, T item) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index < self.Length, nameof(index)); T[] tmp = new T[self.Length]; Array.Copy(self.array!, tmp, self.Length); tmp[index] = item; return new ImmutableArray<T>(tmp); } /// <summary> /// Replaces the first equal element in the list with the specified element. /// </summary> /// <param name="oldValue">The element to replace.</param> /// <param name="newValue">The element to replace the old element with.</param> /// <returns>The new list -- even if the value being replaced is equal to the new value for that position.</returns> /// <exception cref="ArgumentException">Thrown when the old value does not exist in the list.</exception> public ImmutableArray<T> Replace(T oldValue, T newValue) { return this.Replace(oldValue, newValue, EqualityComparer<T>.Default); } /// <summary> /// Replaces the first equal element in the list with the specified element. /// </summary> /// <param name="oldValue">The element to replace.</param> /// <param name="newValue">The element to replace the old element with.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used. /// </param> /// <returns>The new list -- even if the value being replaced is equal to the new value for that position.</returns> /// <exception cref="ArgumentException">Thrown when the old value does not exist in the list.</exception> public ImmutableArray<T> Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) { var self = this; int index = self.IndexOf(oldValue, 0, self.Length, equalityComparer); if (index < 0) { throw new ArgumentException(SR.CannotFindOldValue, nameof(oldValue)); } return self.SetItem(index, newValue); } /// <summary> /// Returns an array with the first occurrence of the specified element removed from the array. /// If no match is found, the current array is returned. /// </summary> /// <param name="item">The item to remove.</param> /// <returns>The new array.</returns> public ImmutableArray<T> Remove(T item) { return this.Remove(item, EqualityComparer<T>.Default); } /// <summary> /// Returns an array with the first occurrence of the specified element removed from the array. /// If no match is found, the current array is returned. /// </summary> /// <param name="item">The item to remove.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used. /// </param> /// <returns>The new array.</returns> public ImmutableArray<T> Remove(T item, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowNullRefIfNotInitialized(); int index = self.IndexOf(item, 0, self.Length, equalityComparer); return index < 0 ? self : self.RemoveAt(index); } /// <summary> /// Returns an array with the element at the specified position removed. /// </summary> /// <param name="index">The 0-based index into the array for the element to omit from the returned array.</param> /// <returns>The new array.</returns> public ImmutableArray<T> RemoveAt(int index) { return this.RemoveRange(index, 1); } /// <summary> /// Returns an array with the elements at the specified position removed. /// </summary> /// <param name="index">The 0-based index into the array for the element to omit from the returned array.</param> /// <param name="length">The number of elements to remove.</param> /// <returns>The new array.</returns> public ImmutableArray<T> RemoveRange(int index, int length) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); Requires.Range(length >= 0 && index + length <= self.Length, nameof(length)); if (length == 0) { return self; } T[] tmp = new T[self.Length - length]; Array.Copy(self.array!, tmp, index); Array.Copy(self.array!, index + length, tmp, index, self.Length - index - length); return new ImmutableArray<T>(tmp); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(IEnumerable<T> items) { return this.RemoveRange(items, EqualityComparer<T>.Default); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used. /// </param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.NotNull(items, nameof(items)); var indicesToRemove = new SortedSet<int>(); foreach (T item in items) { int index = -1; do { index = self.IndexOf(item, index + 1, equalityComparer); } while (index >= 0 && !indicesToRemove.Add(index) && index < self.Length - 1); } return self.RemoveAtRange(indicesToRemove); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(ImmutableArray<T> items) { return this.RemoveRange(items, EqualityComparer<T>.Default); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// </param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(ImmutableArray<T> items, IEqualityComparer<T>? equalityComparer) { Requires.NotNull(items.array!, nameof(items)); return RemoveRange(items.AsSpan(), equalityComparer); } /// <summary> /// Removes all the elements that match the conditions defined by the specified /// predicate. /// </summary> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the elements /// to remove. /// </param> /// <returns> /// The new list. /// </returns> public ImmutableArray<T> RemoveAll(Predicate<T> match) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.NotNull(match, nameof(match)); if (self.IsEmpty) { return self; } List<int>? removeIndices = null; for (int i = 0; i < self.array!.Length; i++) { if (match(self.array[i])) { if (removeIndices == null) { removeIndices = new List<int>(); } removeIndices.Add(i); } } return removeIndices != null ? self.RemoveAtRange(removeIndices) : self; } /// <summary> /// Returns an empty array. /// </summary> public ImmutableArray<T> Clear() { return Empty; } /// <summary> /// Returns a sorted instance of this array. /// </summary> public ImmutableArray<T> Sort() { var self = this; return self.Sort(0, self.Length, Comparer<T>.Default); } /// <summary> /// Sorts the elements in the entire <see cref="ImmutableArray{T}"/> using /// the specified <see cref="Comparison{T}"/>. /// </summary> /// <param name="comparison"> /// The <see cref="Comparison{T}"/> to use when comparing elements. /// </param> /// <returns>The sorted list.</returns> /// <exception cref="ArgumentNullException"><paramref name="comparison"/> is null.</exception> public ImmutableArray<T> Sort(Comparison<T> comparison) { Requires.NotNull(comparison, nameof(comparison)); var self = this; return self.Sort(Comparer<T>.Create(comparison)); } /// <summary> /// Returns a sorted instance of this array. /// </summary> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public ImmutableArray<T> Sort(IComparer<T>? comparer) { var self = this; return self.Sort(0, self.Length, comparer); } /// <summary> /// Returns a sorted instance of this array. /// </summary> /// <param name="index">The index of the first element to consider in the sort.</param> /// <param name="count">The number of elements to include in the sort.</param> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public ImmutableArray<T> Sort(int index, int count, IComparer<T>? comparer) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0, nameof(index)); Requires.Range(count >= 0 && index + count <= self.Length, nameof(count)); // 0 and 1 element arrays don't need to be sorted. if (count > 1) { if (comparer == null) { comparer = Comparer<T>.Default; } // Avoid copying the entire array when the array is already sorted. bool outOfOrder = false; for (int i = index + 1; i < index + count; i++) { if (comparer.Compare(self.array![i - 1], self.array[i]) > 0) { outOfOrder = true; break; } } if (outOfOrder) { var tmp = new T[self.Length]; Array.Copy(self.array!, tmp, self.Length); Array.Sort(tmp, index, count, comparer); return new ImmutableArray<T>(tmp); } } return self; } /// <summary> /// Filters the elements of this array to those assignable to the specified type. /// </summary> /// <typeparam name="TResult">The type to filter the elements of the sequence on.</typeparam> /// <returns> /// An <see cref="IEnumerable{T}"/> that contains elements from /// the input sequence of type <typeparamref name="TResult"/>. /// </returns> public IEnumerable<TResult> OfType<TResult>() { var self = this; if (self.array == null || self.array.Length == 0) { return Enumerable.Empty<TResult>(); } return self.array.OfType<TResult>(); } /// <summary> /// Adds the specified values to this list. /// </summary> /// <param name="items">The values to add.</param> /// <returns>A new list with the elements added.</returns> public ImmutableArray<T> AddRange(ReadOnlySpan<T> items) { var self = this; return self.InsertRange(self.Length, items); } /// <summary> /// Adds the specified values to this list. /// </summary> /// <param name="items">The values to add.</param> /// <returns>A new list with the elements added.</returns> public ImmutableArray<T> AddRange(params T[] items) { var self = this; return self.InsertRange(self.Length, items); } /// <summary> /// Creates a <see cref="ReadOnlySpan{T}"/> over the portion of current <see cref="ImmutableArray{T}"/> beginning at a specified position for a specified length. /// </summary> /// <param name="start">The index at which to begin the span.</param> /// <param name="length">The number of items in the span.</param> /// <returns>The <see cref="ReadOnlySpan{T}"/> representation of the <see cref="ImmutableArray{T}"/></returns> public ReadOnlySpan<T> AsSpan(int start, int length) => new ReadOnlySpan<T>(array, start, length); /// <summary> /// Copies the elements of current <see cref="ImmutableArray{T}"/> to an <see cref="Span{T}"/>. /// </summary> /// <param name="destination">The <see cref="Span{T}"/> that is the destination of the elements copied from current <see cref="ImmutableArray{T}"/>.</param> public void CopyTo(Span<T> destination) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(self.Length <= destination.Length, nameof(destination)); self.AsSpan().CopyTo(destination); } /// <summary> /// Inserts the specified values at the specified index. /// </summary> /// <param name="index">The index at which to insert the value.</param> /// <param name="items">The elements to insert.</param> /// <returns>The new immutable collection.</returns> public ImmutableArray<T> InsertRange(int index, T[] items) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); Requires.NotNull(items, nameof(items)); if (items.Length == 0) { return self; } if (self.IsEmpty) { return new ImmutableArray<T>(items); } return self.InsertSpanRangeInternal(index, items); } /// <summary> /// Inserts the specified values at the specified index. /// </summary> /// <param name="index">The index at which to insert the value.</param> /// <param name="items">The elements to insert.</param> /// <returns>The new immutable collection.</returns> public ImmutableArray<T> InsertRange(int index, ReadOnlySpan<T> items) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); if (items.IsEmpty) { return self; } if (self.IsEmpty) { return items.ToImmutableArray(); } return self.InsertSpanRangeInternal(index, items); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// </param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(ReadOnlySpan<T> items, IEqualityComparer<T>? equalityComparer = null) { var self = this; self.ThrowNullRefIfNotInitialized(); if (items.IsEmpty || self.IsEmpty) { return self; } if (items.Length == 1) { return self.Remove(items[0], equalityComparer); } var indicesToRemove = new SortedSet<int>(); foreach (T item in items) { int index = -1; do { index = self.IndexOf(item, index + 1, equalityComparer); } while (index >= 0 && !indicesToRemove.Add(index) && index < self.Length - 1); } return self.RemoveAtRange(indicesToRemove); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// </param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(T[] items, IEqualityComparer<T>? equalityComparer = null) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.NotNull(items, nameof(items)); return self.RemoveRange(new ReadOnlySpan<T>(items), equalityComparer); } /// <summary> /// Forms a slice out of the current <see cref="ImmutableArray{T}"/> starting at a specified index for a specified length. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice.</param> /// <returns>A <see cref="ImmutableArray{T}"/> that consists of length elements from the current <see cref="ImmutableArray{T}"/> starting at start.</returns> public ImmutableArray<T> Slice(int start, int length) { var self = this; self.ThrowNullRefIfNotInitialized(); return ImmutableArray.Create(self, start, length); } #region Explicit interface methods void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.Clear() { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Clear(); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.Add(T value) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Add(value); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.AddRange(IEnumerable<T> items) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.AddRange(items); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.Insert(int index, T element) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Insert(index, element); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.InsertRange(int index, IEnumerable<T> items) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.InsertRange(index, items); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.Remove(T value, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Remove(value, equalityComparer); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.RemoveAll(Predicate<T> match) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.RemoveAll(match); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.RemoveRange(items, equalityComparer); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.RemoveRange(int index, int count) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.RemoveRange(index, count); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.RemoveAt(int index) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.RemoveAt(index); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.SetItem(int index, T value) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.SetItem(index, value); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Replace(oldValue, newValue, equalityComparer); } /// <summary> /// Adds an item to the <see cref="IList"/>. /// </summary> /// <param name="value">The object to add to the <see cref="IList"/>.</param> /// <returns> /// The position into which the new element was inserted, or -1 to indicate that the item was not inserted into the collection, /// </returns> /// <exception cref="System.NotSupportedException"></exception> int IList.Add(object? value) { throw new NotSupportedException(); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. /// </summary> /// <exception cref="System.NotSupportedException"></exception> void IList.Clear() { throw new NotSupportedException(); } /// <summary> /// Determines whether the <see cref="IList"/> contains a specific value. /// </summary> /// <param name="value">The object to locate in the <see cref="IList"/>.</param> /// <returns> /// true if the <see cref="object"/> is found in the <see cref="IList"/>; otherwise, false. /// </returns> bool IList.Contains(object? value) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Contains((T)value!); } /// <summary> /// Determines the index of a specific item in the <see cref="IList"/>. /// </summary> /// <param name="value">The object to locate in the <see cref="IList"/>.</param> /// <returns> /// The index of <paramref name="value"/> if found in the list; otherwise, -1. /// </returns> int IList.IndexOf(object? value) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.IndexOf((T)value!); } /// <summary> /// Inserts an item to the <see cref="IList"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param> /// <param name="value">The object to insert into the <see cref="IList"/>.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.Insert(int index, object? value) { throw new NotSupportedException(); } /// <summary> /// Gets a value indicating whether this instance is fixed size. /// </summary> /// <value> /// <c>true</c> if this instance is fixed size; otherwise, <c>false</c>. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool IList.IsFixedSize { get { return true; } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value> /// <c>true</c> if this instance is read only; otherwise, <c>false</c>. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool IList.IsReadOnly { get { return true; } } /// <summary> /// Gets the size of the array. /// </summary> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] int ICollection.Count { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Length; } } /// <summary> /// See the <see cref="ICollection"/> interface. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { // This is immutable, so it is always thread-safe. return true; } } /// <summary> /// Gets the sync root. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { throw new NotSupportedException(); } } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="IList"/>. /// </summary> /// <param name="value">The object to remove from the <see cref="IList"/>.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.Remove(object? value) { throw new NotSupportedException(); } /// <summary> /// Removes the <see cref="IList{T}"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.RemoveAt(int index) { throw new NotSupportedException(); } /// <summary> /// Gets or sets the <see cref="object"/> at the specified index. /// </summary> /// <value> /// The <see cref="object"/>. /// </value> /// <param name="index">The index.</param> /// <returns></returns> /// <exception cref="NotSupportedException">Always thrown from the setter.</exception> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> object? IList.this[int index] { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self[index]; } set { throw new NotSupportedException(); } } /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int index) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); Array.Copy(self.array!, 0, array, index, self.Length); } /// <summary> /// Determines whether an object is structurally equal to the current instance. /// </summary> /// <param name="other">The object to compare with the current instance.</param> /// <param name="comparer">An object that determines whether the current instance and other are equal.</param> /// <returns>true if the two objects are equal; otherwise, false.</returns> bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { var self = this; Array? otherArray = other as Array; if (otherArray == null) { if (other is IImmutableArray theirs) { otherArray = theirs.Array; if (self.array == null && otherArray == null) { return true; } else if (self.array == null) { return false; } } } IStructuralEquatable ours = self.array!; return ours.Equals(otherArray, comparer); } /// <summary> /// Returns a hash code for the current instance. /// </summary> /// <param name="comparer">An object that computes the hash code of the current object.</param> /// <returns>The hash code for the current instance.</returns> int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { var self = this; IStructuralEquatable? ours = self.array; return ours != null ? ours.GetHashCode(comparer) : self.GetHashCode(); } /// <summary> /// Determines whether the current collection object precedes, occurs in the /// same position as, or follows another object in the sort order. /// </summary> /// <param name="other">The object to compare with the current instance.</param> /// <param name="comparer"> /// An object that compares members of the current collection object with the /// corresponding members of other. /// </param> /// <returns> /// An integer that indicates the relationship of the current collection object /// to other. /// </returns> int IStructuralComparable.CompareTo(object? other, IComparer comparer) { var self = this; Array? otherArray = other as Array; if (otherArray == null) { if (other is IImmutableArray theirs) { otherArray = theirs.Array; if (self.array == null && otherArray == null) { return 0; } else if (self.array == null ^ otherArray == null) { throw new ArgumentException(SR.ArrayInitializedStateNotEqual, nameof(other)); } } } if (otherArray != null) { IStructuralComparable? ours = self.array; if (ours == null) { throw new ArgumentException(SR.ArrayInitializedStateNotEqual, nameof(other)); } return ours.CompareTo(otherArray, comparer); } throw new ArgumentException(SR.ArrayLengthsNotEqual, nameof(other)); } #endregion /// <summary> /// Returns an array with items at the specified indices removed. /// </summary> /// <param name="indicesToRemove">A **sorted set** of indices to elements that should be omitted from the returned array.</param> /// <returns>The new array.</returns> private ImmutableArray<T> RemoveAtRange(ICollection<int> indicesToRemove) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.NotNull(indicesToRemove, nameof(indicesToRemove)); if (indicesToRemove.Count == 0) { // Be sure to return a !IsDefault instance. return self; } var newArray = new T[self.Length - indicesToRemove.Count]; int copied = 0; int removed = 0; int lastIndexRemoved = -1; foreach (int indexToRemove in indicesToRemove) { int copyLength = lastIndexRemoved == -1 ? indexToRemove : (indexToRemove - lastIndexRemoved - 1); Debug.Assert(indexToRemove > lastIndexRemoved); // We require that the input be a sorted set. Array.Copy(self.array!, copied + removed, newArray, copied, copyLength); removed++; copied += copyLength; lastIndexRemoved = indexToRemove; } Array.Copy(self.array!, copied + removed, newArray, copied, self.Length - (copied + removed)); return new ImmutableArray<T>(newArray); } private ImmutableArray<T> InsertSpanRangeInternal(int index, ReadOnlySpan<T> items) { Debug.Assert(array != null); Debug.Assert(!IsEmpty); Debug.Assert(!items.IsEmpty); var tmp = new T[Length + items.Length]; if (index != 0) { Array.Copy(array!, tmp, index); } items.CopyTo(new Span<T>(tmp, index, items.Length)); if (index != Length) { Array.Copy(array!, index, tmp, index + items.Length, Length - index); } return new ImmutableArray<T>(tmp); } } }
// 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.Globalization; using System.Linq; using System.Runtime.Versioning; namespace System.Collections.Immutable { public readonly partial struct ImmutableArray<T> : IReadOnlyList<T>, IList<T>, IEquatable<ImmutableArray<T>>, IList, IImmutableArray, IStructuralComparable, IStructuralEquatable, IImmutableList<T> { /// <summary> /// Gets or sets the element at the specified index in the read-only list. /// </summary> /// <param name="index">The zero-based index of the element to get.</param> /// <returns>The element at the specified index in the read-only list.</returns> /// <exception cref="NotSupportedException">Always thrown from the setter.</exception> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> T IList<T>.this[int index] { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self[index]; } set { throw new NotSupportedException(); } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value> /// <c>true</c> if this instance is read only; otherwise, <c>false</c>. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection<T>.IsReadOnly { get { return true; } } /// <summary> /// Gets the number of array in the collection. /// </summary> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] int ICollection<T>.Count { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Length; } } /// <summary> /// Gets the number of array in the collection. /// </summary> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] int IReadOnlyCollection<T>.Count { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Length; } } /// <summary> /// Gets the element at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns> /// The element. /// </returns> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> T IReadOnlyList<T>.this[int index] { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self[index]; } } public ReadOnlySpan<T> AsSpan() => new ReadOnlySpan<T>(array); public ReadOnlyMemory<T> AsMemory() => new ReadOnlyMemory<T>(array); /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int IndexOf(T item) { var self = this; return self.IndexOf(item, 0, self.Length, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int IndexOf(T item, int startIndex, IEqualityComparer<T>? equalityComparer) { var self = this; return self.IndexOf(item, startIndex, self.Length - startIndex, equalityComparer); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int IndexOf(T item, int startIndex) { var self = this; return self.IndexOf(item, startIndex, self.Length - startIndex, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int IndexOf(T item, int startIndex, int count) { return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used. /// </param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowNullRefIfNotInitialized(); if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < self.Length, nameof(startIndex)); Requires.Range(count >= 0 && startIndex + count <= self.Length, nameof(count)); equalityComparer = equalityComparer ?? EqualityComparer<T>.Default; if (equalityComparer == EqualityComparer<T>.Default) { return Array.IndexOf(self.array!, item, startIndex, count); } else { for (int i = startIndex; i < startIndex + count; i++) { if (equalityComparer.Equals(self.array![i], item)) { return i; } } return -1; } } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int LastIndexOf(T item) { var self = this; if (self.IsEmpty) { return -1; } return self.LastIndexOf(item, self.Length - 1, self.Length, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int LastIndexOf(T item, int startIndex) { var self = this; if (self.IsEmpty && startIndex == 0) { return -1; } return self.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int LastIndexOf(T item, int startIndex, int count) { return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowNullRefIfNotInitialized(); if (startIndex == 0 && count == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < self.Length, nameof(startIndex)); Requires.Range(count >= 0 && startIndex - count + 1 >= 0, nameof(count)); equalityComparer = equalityComparer ?? EqualityComparer<T>.Default; if (equalityComparer == EqualityComparer<T>.Default) { return Array.LastIndexOf(self.array!, item, startIndex, count); } else { for (int i = startIndex; i >= startIndex - count + 1; i--) { if (equalityComparer.Equals(item, self.array![i])) { return i; } } return -1; } } /// <summary> /// Determines whether the specified item exists in the array. /// </summary> /// <param name="item">The item to search for.</param> /// <returns><c>true</c> if an equal value was found in the array; <c>false</c> otherwise.</returns> public bool Contains(T item) { return this.IndexOf(item) >= 0; } /// <summary> /// Returns a new array with the specified value inserted at the specified position. /// </summary> /// <param name="index">The 0-based index into the array at which the new item should be added.</param> /// <param name="item">The item to insert at the start of the array.</param> /// <returns>A new array.</returns> public ImmutableArray<T> Insert(int index, T item) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); if (self.IsEmpty) { return ImmutableArray.Create(item); } T[] tmp = new T[self.Length + 1]; tmp[index] = item; if (index != 0) { Array.Copy(self.array!, tmp, index); } if (index != self.Length) { Array.Copy(self.array!, index, tmp, index + 1, self.Length - index); } return new ImmutableArray<T>(tmp); } /// <summary> /// Inserts the specified values at the specified index. /// </summary> /// <param name="index">The index at which to insert the value.</param> /// <param name="items">The elements to insert.</param> /// <returns>The new immutable collection.</returns> public ImmutableArray<T> InsertRange(int index, IEnumerable<T> items) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); Requires.NotNull(items, nameof(items)); if (self.IsEmpty) { return ImmutableArray.CreateRange(items); } int count = ImmutableExtensions.GetCount(ref items); if (count == 0) { return self; } T[] tmp = new T[self.Length + count]; if (index != 0) { Array.Copy(self.array!, tmp, index); } if (index != self.Length) { Array.Copy(self.array!, index, tmp, index + count, self.Length - index); } // We want to copy over the items we need to insert. // Check first to see if items is a well-known collection we can call CopyTo // on to the array, which is an order of magnitude faster than foreach. // Otherwise, go to the fallback route where we manually enumerate the sequence // and place the items in the array one-by-one. if (!items.TryCopyTo(tmp, index)) { int sequenceIndex = index; foreach (T item in items) { tmp[sequenceIndex++] = item; } } return new ImmutableArray<T>(tmp); } /// <summary> /// Inserts the specified values at the specified index. /// </summary> /// <param name="index">The index at which to insert the value.</param> /// <param name="items">The elements to insert.</param> /// <returns>The new immutable collection.</returns> public ImmutableArray<T> InsertRange(int index, ImmutableArray<T> items) { var self = this; self.ThrowNullRefIfNotInitialized(); items.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); if (self.IsEmpty) { return items; } if (items.IsEmpty) { return self; } return self.InsertSpanRangeInternal(index, items.AsSpan()); } /// <summary> /// Returns a new array with the specified value inserted at the end. /// </summary> /// <param name="item">The item to insert at the end of the array.</param> /// <returns>A new array.</returns> public ImmutableArray<T> Add(T item) { var self = this; if (self.IsEmpty) { return ImmutableArray.Create(item); } return self.Insert(self.Length, item); } /// <summary> /// Adds the specified values to this list. /// </summary> /// <param name="items">The values to add.</param> /// <returns>A new list with the elements added.</returns> public ImmutableArray<T> AddRange(IEnumerable<T> items) { var self = this; return self.InsertRange(self.Length, items); } /// <summary> /// Adds the specified values to this list. /// </summary> /// <param name="items">The values to add.</param> /// <returns>A new list with the elements added.</returns> public ImmutableArray<T> AddRange(ImmutableArray<T> items) { var self = this; return self.InsertRange(self.Length, items); } /// <summary> /// Returns an array with the item at the specified position replaced. /// </summary> /// <param name="index">The index of the item to replace.</param> /// <param name="item">The new item.</param> /// <returns>The new array.</returns> public ImmutableArray<T> SetItem(int index, T item) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index < self.Length, nameof(index)); T[] tmp = new T[self.Length]; Array.Copy(self.array!, tmp, self.Length); tmp[index] = item; return new ImmutableArray<T>(tmp); } /// <summary> /// Replaces the first equal element in the list with the specified element. /// </summary> /// <param name="oldValue">The element to replace.</param> /// <param name="newValue">The element to replace the old element with.</param> /// <returns>The new list -- even if the value being replaced is equal to the new value for that position.</returns> /// <exception cref="ArgumentException">Thrown when the old value does not exist in the list.</exception> public ImmutableArray<T> Replace(T oldValue, T newValue) { return this.Replace(oldValue, newValue, EqualityComparer<T>.Default); } /// <summary> /// Replaces the first equal element in the list with the specified element. /// </summary> /// <param name="oldValue">The element to replace.</param> /// <param name="newValue">The element to replace the old element with.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used. /// </param> /// <returns>The new list -- even if the value being replaced is equal to the new value for that position.</returns> /// <exception cref="ArgumentException">Thrown when the old value does not exist in the list.</exception> public ImmutableArray<T> Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) { var self = this; int index = self.IndexOf(oldValue, 0, self.Length, equalityComparer); if (index < 0) { throw new ArgumentException(SR.CannotFindOldValue, nameof(oldValue)); } return self.SetItem(index, newValue); } /// <summary> /// Returns an array with the first occurrence of the specified element removed from the array. /// If no match is found, the current array is returned. /// </summary> /// <param name="item">The item to remove.</param> /// <returns>The new array.</returns> public ImmutableArray<T> Remove(T item) { return this.Remove(item, EqualityComparer<T>.Default); } /// <summary> /// Returns an array with the first occurrence of the specified element removed from the array. /// If no match is found, the current array is returned. /// </summary> /// <param name="item">The item to remove.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used. /// </param> /// <returns>The new array.</returns> public ImmutableArray<T> Remove(T item, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowNullRefIfNotInitialized(); int index = self.IndexOf(item, 0, self.Length, equalityComparer); return index < 0 ? self : self.RemoveAt(index); } /// <summary> /// Returns an array with the element at the specified position removed. /// </summary> /// <param name="index">The 0-based index into the array for the element to omit from the returned array.</param> /// <returns>The new array.</returns> public ImmutableArray<T> RemoveAt(int index) { return this.RemoveRange(index, 1); } /// <summary> /// Returns an array with the elements at the specified position removed. /// </summary> /// <param name="index">The 0-based index into the array for the element to omit from the returned array.</param> /// <param name="length">The number of elements to remove.</param> /// <returns>The new array.</returns> public ImmutableArray<T> RemoveRange(int index, int length) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); Requires.Range(length >= 0 && index + length <= self.Length, nameof(length)); if (length == 0) { return self; } T[] tmp = new T[self.Length - length]; Array.Copy(self.array!, tmp, index); Array.Copy(self.array!, index + length, tmp, index, self.Length - index - length); return new ImmutableArray<T>(tmp); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(IEnumerable<T> items) { return this.RemoveRange(items, EqualityComparer<T>.Default); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used. /// </param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.NotNull(items, nameof(items)); var indicesToRemove = new SortedSet<int>(); foreach (T item in items) { int index = -1; do { index = self.IndexOf(item, index + 1, equalityComparer); } while (index >= 0 && !indicesToRemove.Add(index) && index < self.Length - 1); } return self.RemoveAtRange(indicesToRemove); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(ImmutableArray<T> items) { return this.RemoveRange(items, EqualityComparer<T>.Default); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// </param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(ImmutableArray<T> items, IEqualityComparer<T>? equalityComparer) { Requires.NotNull(items.array!, nameof(items)); return RemoveRange(items.AsSpan(), equalityComparer); } /// <summary> /// Removes all the elements that match the conditions defined by the specified /// predicate. /// </summary> /// <param name="match"> /// The <see cref="Predicate{T}"/> delegate that defines the conditions of the elements /// to remove. /// </param> /// <returns> /// The new list. /// </returns> public ImmutableArray<T> RemoveAll(Predicate<T> match) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.NotNull(match, nameof(match)); if (self.IsEmpty) { return self; } List<int>? removeIndices = null; for (int i = 0; i < self.array!.Length; i++) { if (match(self.array[i])) { if (removeIndices == null) { removeIndices = new List<int>(); } removeIndices.Add(i); } } return removeIndices != null ? self.RemoveAtRange(removeIndices) : self; } /// <summary> /// Returns an empty array. /// </summary> public ImmutableArray<T> Clear() { return Empty; } /// <summary> /// Returns a sorted instance of this array. /// </summary> public ImmutableArray<T> Sort() { var self = this; return self.Sort(0, self.Length, Comparer<T>.Default); } /// <summary> /// Sorts the elements in the entire <see cref="ImmutableArray{T}"/> using /// the specified <see cref="Comparison{T}"/>. /// </summary> /// <param name="comparison"> /// The <see cref="Comparison{T}"/> to use when comparing elements. /// </param> /// <returns>The sorted list.</returns> /// <exception cref="ArgumentNullException"><paramref name="comparison"/> is null.</exception> public ImmutableArray<T> Sort(Comparison<T> comparison) { Requires.NotNull(comparison, nameof(comparison)); var self = this; return self.Sort(Comparer<T>.Create(comparison)); } /// <summary> /// Returns a sorted instance of this array. /// </summary> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public ImmutableArray<T> Sort(IComparer<T>? comparer) { var self = this; return self.Sort(0, self.Length, comparer); } /// <summary> /// Returns a sorted instance of this array. /// </summary> /// <param name="index">The index of the first element to consider in the sort.</param> /// <param name="count">The number of elements to include in the sort.</param> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public ImmutableArray<T> Sort(int index, int count, IComparer<T>? comparer) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0, nameof(index)); Requires.Range(count >= 0 && index + count <= self.Length, nameof(count)); // 0 and 1 element arrays don't need to be sorted. if (count > 1) { if (comparer == null) { comparer = Comparer<T>.Default; } // Avoid copying the entire array when the array is already sorted. bool outOfOrder = false; for (int i = index + 1; i < index + count; i++) { if (comparer.Compare(self.array![i - 1], self.array[i]) > 0) { outOfOrder = true; break; } } if (outOfOrder) { var tmp = new T[self.Length]; Array.Copy(self.array!, tmp, self.Length); Array.Sort(tmp, index, count, comparer); return new ImmutableArray<T>(tmp); } } return self; } /// <summary> /// Filters the elements of this array to those assignable to the specified type. /// </summary> /// <typeparam name="TResult">The type to filter the elements of the sequence on.</typeparam> /// <returns> /// An <see cref="IEnumerable{T}"/> that contains elements from /// the input sequence of type <typeparamref name="TResult"/>. /// </returns> public IEnumerable<TResult> OfType<TResult>() { var self = this; if (self.array == null || self.array.Length == 0) { return Enumerable.Empty<TResult>(); } return self.array.OfType<TResult>(); } /// <summary> /// Adds the specified values to this list. /// </summary> /// <param name="items">The values to add.</param> /// <returns>A new list with the elements added.</returns> public ImmutableArray<T> AddRange(ReadOnlySpan<T> items) { var self = this; return self.InsertRange(self.Length, items); } /// <summary> /// Adds the specified values to this list. /// </summary> /// <param name="items">The values to add.</param> /// <returns>A new list with the elements added.</returns> public ImmutableArray<T> AddRange(params T[] items) { var self = this; return self.InsertRange(self.Length, items); } /// <summary> /// Creates a <see cref="ReadOnlySpan{T}"/> over the portion of current <see cref="ImmutableArray{T}"/> beginning at a specified position for a specified length. /// </summary> /// <param name="start">The index at which to begin the span.</param> /// <param name="length">The number of items in the span.</param> /// <returns>The <see cref="ReadOnlySpan{T}"/> representation of the <see cref="ImmutableArray{T}"/></returns> public ReadOnlySpan<T> AsSpan(int start, int length) => new ReadOnlySpan<T>(array, start, length); /// <summary> /// Copies the elements of current <see cref="ImmutableArray{T}"/> to an <see cref="Span{T}"/>. /// </summary> /// <param name="destination">The <see cref="Span{T}"/> that is the destination of the elements copied from current <see cref="ImmutableArray{T}"/>.</param> public void CopyTo(Span<T> destination) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(self.Length <= destination.Length, nameof(destination)); self.AsSpan().CopyTo(destination); } /// <summary> /// Inserts the specified values at the specified index. /// </summary> /// <param name="index">The index at which to insert the value.</param> /// <param name="items">The elements to insert.</param> /// <returns>The new immutable collection.</returns> public ImmutableArray<T> InsertRange(int index, T[] items) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); Requires.NotNull(items, nameof(items)); if (items.Length == 0) { return self; } if (self.IsEmpty) { return new ImmutableArray<T>(items); } return self.InsertSpanRangeInternal(index, items); } /// <summary> /// Inserts the specified values at the specified index. /// </summary> /// <param name="index">The index at which to insert the value.</param> /// <param name="items">The elements to insert.</param> /// <returns>The new immutable collection.</returns> public ImmutableArray<T> InsertRange(int index, ReadOnlySpan<T> items) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.Range(index >= 0 && index <= self.Length, nameof(index)); if (items.IsEmpty) { return self; } if (self.IsEmpty) { return items.ToImmutableArray(); } return self.InsertSpanRangeInternal(index, items); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// </param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(ReadOnlySpan<T> items, IEqualityComparer<T>? equalityComparer = null) { var self = this; self.ThrowNullRefIfNotInitialized(); if (items.IsEmpty || self.IsEmpty) { return self; } if (items.Length == 1) { return self.Remove(items[0], equalityComparer); } var indicesToRemove = new SortedSet<int>(); foreach (T item in items) { int index = -1; do { index = self.IndexOf(item, index + 1, equalityComparer); } while (index >= 0 && !indicesToRemove.Add(index) && index < self.Length - 1); } return self.RemoveAtRange(indicesToRemove); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="items">The items to remove if matches are found in this list.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// </param> /// <returns> /// A new list with the elements removed. /// </returns> public ImmutableArray<T> RemoveRange(T[] items, IEqualityComparer<T>? equalityComparer = null) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.NotNull(items, nameof(items)); return self.RemoveRange(new ReadOnlySpan<T>(items), equalityComparer); } /// <summary> /// Forms a slice out of the current <see cref="ImmutableArray{T}"/> starting at a specified index for a specified length. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice.</param> /// <returns>A <see cref="ImmutableArray{T}"/> that consists of length elements from the current <see cref="ImmutableArray{T}"/> starting at start.</returns> public ImmutableArray<T> Slice(int start, int length) { var self = this; self.ThrowNullRefIfNotInitialized(); return ImmutableArray.Create(self, start, length); } #region Explicit interface methods void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.Clear() { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Clear(); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.Add(T value) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Add(value); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.AddRange(IEnumerable<T> items) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.AddRange(items); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.Insert(int index, T element) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Insert(index, element); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.InsertRange(int index, IEnumerable<T> items) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.InsertRange(index, items); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.Remove(T value, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Remove(value, equalityComparer); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.RemoveAll(Predicate<T> match) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.RemoveAll(match); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.RemoveRange(items, equalityComparer); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.RemoveRange(int index, int count) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.RemoveRange(index, count); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.RemoveAt(int index) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.RemoveAt(index); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.SetItem(int index, T value) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.SetItem(index, value); } /// <summary> /// See <see cref="IImmutableList{T}"/> /// </summary> IImmutableList<T> IImmutableList<T>.Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Replace(oldValue, newValue, equalityComparer); } /// <summary> /// Adds an item to the <see cref="IList"/>. /// </summary> /// <param name="value">The object to add to the <see cref="IList"/>.</param> /// <returns> /// The position into which the new element was inserted, or -1 to indicate that the item was not inserted into the collection, /// </returns> /// <exception cref="System.NotSupportedException"></exception> int IList.Add(object? value) { throw new NotSupportedException(); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. /// </summary> /// <exception cref="System.NotSupportedException"></exception> void IList.Clear() { throw new NotSupportedException(); } /// <summary> /// Determines whether the <see cref="IList"/> contains a specific value. /// </summary> /// <param name="value">The object to locate in the <see cref="IList"/>.</param> /// <returns> /// true if the <see cref="object"/> is found in the <see cref="IList"/>; otherwise, false. /// </returns> bool IList.Contains(object? value) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Contains((T)value!); } /// <summary> /// Determines the index of a specific item in the <see cref="IList"/>. /// </summary> /// <param name="value">The object to locate in the <see cref="IList"/>.</param> /// <returns> /// The index of <paramref name="value"/> if found in the list; otherwise, -1. /// </returns> int IList.IndexOf(object? value) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.IndexOf((T)value!); } /// <summary> /// Inserts an item to the <see cref="IList"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param> /// <param name="value">The object to insert into the <see cref="IList"/>.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.Insert(int index, object? value) { throw new NotSupportedException(); } /// <summary> /// Gets a value indicating whether this instance is fixed size. /// </summary> /// <value> /// <c>true</c> if this instance is fixed size; otherwise, <c>false</c>. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool IList.IsFixedSize { get { return true; } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value> /// <c>true</c> if this instance is read only; otherwise, <c>false</c>. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool IList.IsReadOnly { get { return true; } } /// <summary> /// Gets the size of the array. /// </summary> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] int ICollection.Count { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self.Length; } } /// <summary> /// See the <see cref="ICollection"/> interface. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { // This is immutable, so it is always thread-safe. return true; } } /// <summary> /// Gets the sync root. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { throw new NotSupportedException(); } } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="IList"/>. /// </summary> /// <param name="value">The object to remove from the <see cref="IList"/>.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.Remove(object? value) { throw new NotSupportedException(); } /// <summary> /// Removes the <see cref="IList{T}"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.RemoveAt(int index) { throw new NotSupportedException(); } /// <summary> /// Gets or sets the <see cref="object"/> at the specified index. /// </summary> /// <value> /// The <see cref="object"/>. /// </value> /// <param name="index">The index.</param> /// <returns></returns> /// <exception cref="NotSupportedException">Always thrown from the setter.</exception> /// <exception cref="InvalidOperationException">Thrown if the <see cref="IsDefault"/> property returns true.</exception> object? IList.this[int index] { get { var self = this; self.ThrowInvalidOperationIfNotInitialized(); return self[index]; } set { throw new NotSupportedException(); } } /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int index) { var self = this; self.ThrowInvalidOperationIfNotInitialized(); Array.Copy(self.array!, 0, array, index, self.Length); } /// <summary> /// Determines whether an object is structurally equal to the current instance. /// </summary> /// <param name="other">The object to compare with the current instance.</param> /// <param name="comparer">An object that determines whether the current instance and other are equal.</param> /// <returns>true if the two objects are equal; otherwise, false.</returns> bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { var self = this; Array? otherArray = other as Array; if (otherArray == null) { if (other is IImmutableArray theirs) { otherArray = theirs.Array; if (self.array == null && otherArray == null) { return true; } else if (self.array == null) { return false; } } } IStructuralEquatable ours = self.array!; return ours.Equals(otherArray, comparer); } /// <summary> /// Returns a hash code for the current instance. /// </summary> /// <param name="comparer">An object that computes the hash code of the current object.</param> /// <returns>The hash code for the current instance.</returns> int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { var self = this; IStructuralEquatable? ours = self.array; return ours != null ? ours.GetHashCode(comparer) : self.GetHashCode(); } /// <summary> /// Determines whether the current collection object precedes, occurs in the /// same position as, or follows another object in the sort order. /// </summary> /// <param name="other">The object to compare with the current instance.</param> /// <param name="comparer"> /// An object that compares members of the current collection object with the /// corresponding members of other. /// </param> /// <returns> /// An integer that indicates the relationship of the current collection object /// to other. /// </returns> int IStructuralComparable.CompareTo(object? other, IComparer comparer) { var self = this; Array? otherArray = other as Array; if (otherArray == null) { if (other is IImmutableArray theirs) { otherArray = theirs.Array; if (self.array == null && otherArray == null) { return 0; } else if (self.array == null ^ otherArray == null) { throw new ArgumentException(SR.ArrayInitializedStateNotEqual, nameof(other)); } } } if (otherArray != null) { IStructuralComparable? ours = self.array; if (ours == null) { throw new ArgumentException(SR.ArrayInitializedStateNotEqual, nameof(other)); } return ours.CompareTo(otherArray, comparer); } throw new ArgumentException(SR.ArrayLengthsNotEqual, nameof(other)); } #endregion /// <summary> /// Returns an array with items at the specified indices removed. /// </summary> /// <param name="indicesToRemove">A **sorted set** of indices to elements that should be omitted from the returned array.</param> /// <returns>The new array.</returns> private ImmutableArray<T> RemoveAtRange(ICollection<int> indicesToRemove) { var self = this; self.ThrowNullRefIfNotInitialized(); Requires.NotNull(indicesToRemove, nameof(indicesToRemove)); if (indicesToRemove.Count == 0) { // Be sure to return a !IsDefault instance. return self; } var newArray = new T[self.Length - indicesToRemove.Count]; int copied = 0; int removed = 0; int lastIndexRemoved = -1; foreach (int indexToRemove in indicesToRemove) { int copyLength = lastIndexRemoved == -1 ? indexToRemove : (indexToRemove - lastIndexRemoved - 1); Debug.Assert(indexToRemove > lastIndexRemoved); // We require that the input be a sorted set. Array.Copy(self.array!, copied + removed, newArray, copied, copyLength); removed++; copied += copyLength; lastIndexRemoved = indexToRemove; } Array.Copy(self.array!, copied + removed, newArray, copied, self.Length - (copied + removed)); return new ImmutableArray<T>(newArray); } private ImmutableArray<T> InsertSpanRangeInternal(int index, ReadOnlySpan<T> items) { Debug.Assert(array != null); Debug.Assert(!IsEmpty); Debug.Assert(!items.IsEmpty); var tmp = new T[Length + items.Length]; if (index != 0) { Array.Copy(array!, tmp, index); } items.CopyTo(new Span<T>(tmp, index, items.Length)); if (index != Length) { Array.Copy(array!, index, tmp, index + items.Length, Length - index); } return new ImmutableArray<T>(tmp); } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/Common/helixpublishwitharcade.proj
<Project DefaultTargets="RunInParallelForEachScenario"> <!-- This project uses the helix SDK, documented at https://github.com/dotnet/arcade/tree/master/src/Microsoft.DotNet.Helix/Sdk, to send test jobs to helix. --> <Import Sdk="Microsoft.DotNet.Helix.Sdk" Project="Sdk.props" Condition=" '$(UsesHelixSdk)' == 'true' " /> <Import Sdk="Microsoft.Build.NoTargets" Project="Sdk.props" Condition=" '$(UsesHelixSdk)' != 'true' " /> <PropertyGroup> <CoreRootDirectory>$(TestBinDir)Tests\Core_Root\</CoreRootDirectory> <LegacyPayloadsRootDirectory>$(TestBinDir)LegacyPayloads\</LegacyPayloadsRootDirectory> <LegacyPayloadsRootDirectory>$([MSBuild]::NormalizeDirectory($(LegacyPayloadsRootDirectory)))</LegacyPayloadsRootDirectory> <MergedPayloadsRootDirectory>$(TestBinDir)MergedPayloads\</MergedPayloadsRootDirectory> <MergedPayloadsRootDirectory>$([MSBuild]::NormalizeDirectory($(MergedPayloadsRootDirectory)))</MergedPayloadsRootDirectory> </PropertyGroup> <!-- This target runs once and creates several instances of this project (one for each scenario) that will run in parallel. --> <Target Name="RunInParallelForEachScenario"> <PropertyGroup> <!-- This specifies what properties are needed to be passed down as global properties to a child project. --> <_PropertiesToPass> TargetArchitecture=$(TargetArchitecture); TargetOS=$(TargetOS); Configuration=$(Configuration); Creator=$(_Creator); HelixAccessToken=$(_HelixAccessToken); HelixBuild=$(_HelixBuild); HelixSource=$(_HelixSource); HelixTargetQueues=$(_HelixTargetQueues); HelixType=$(_HelixType); PublishTestResults=$(_PublishTestResults); RunCrossGen=$(_RunCrossGen); RunCrossGen2=$(_RunCrossGen2); CompositeBuildMode=$(_CompositeBuildMode); LongRunningGCTests=$(_LongRunningGCTests); GcSimulatorTests=$(_GcSimulatorTests); RunInUnloadableContext=$(_RunInUnloadableContext); TieringTest=$(_TieringTest); TimeoutPerTestCollectionInMinutes=$(_TimeoutPerTestCollectionInMinutes); TimeoutPerTestInMinutes=$(_TimeoutPerTestInMinutes); RuntimeVariant=$(_RuntimeVariant); BundledNETCoreAppPackageVersion=$(BundledNETCoreAppPackageVersion); HelixRuntimeRid=$(HelixRuntimeRid); PALTestsDir=$(_PALTestsDir) </_PropertiesToPass> <_PropertiesToPass Condition="'$(TargetOS)' == 'Browser' Or '$(TargetsAndroid)' == 'true'"> $(_PropertiesToPass); IncludeDotNetCli=$(IncludeDotNetCli); DotNetCliRuntime=$(DotNetCliRuntime); DotNetCliPackageType=$(DotNetCliPackageType); DotNetCliVersion=$(DotNetCliVersion) </_PropertiesToPass> </PropertyGroup> <Message Text="DotNetCliVersion: $(DotNetCliVersion)" Importance="High" /> <Message Text="DotNetCliPackageType: $(DotNetCliPackageType)" Importance="High" /> <Message Text="HelixRuntimeRid: $(HelixRuntimeRid)" Importance="High" /> <Error Condition="'$(_Scenarios)' == ''" Text="_Scenarios not set" /> <ItemGroup> <CleanPreexistingPayloads Include="$(LegacyPayloadsRootDirectory)**" /> <CleanPreexistingPayloads Include="$(MergedPayloadsRootDirectory)**" /> </ItemGroup> <Delete Files="@(CleanPreexistingPayloads)" /> <MSBuild Projects="$(MSBuildProjectFile)" Targets="PrepareCorrelationPayloadDirectory" /> <MSBuild Projects="$(MSBuildProjectFile)" Targets="PreparePayloadDirectories" Properties="Scenarios=$(_Scenarios)" StopOnFirstFailure="true" /> <MSBuild Projects="$(MSBuildProjectFile)" Targets="PreparePALTestArchive" Properties="$(_PropertiesToPass)" StopOnFirstFailure="true" /> <ItemGroup> <_Scenarios Include="$(_Scenarios.Split(','))" /> <!-- MSBuild creates a new instance of the project for each %(_Scenarios.Identity) and can build them in parallel. --> <_ProjectsToBuild Include="$(MSBuildProjectFile)"> <AdditionalProperties>$(_PropertiesToPass);Scenario=%(_Scenarios.Identity)</AdditionalProperties> </_ProjectsToBuild> </ItemGroup> <PropertyGroup> <_BuildInParallel>false</_BuildInParallel> <_BuildInParallel Condition=" '@(_ProjectsToBuild->Count())' &gt; '1' ">true</_BuildInParallel> </PropertyGroup> <MSBuild Projects="@(_ProjectsToBuild)" Targets="Test" BuildInParallel="$(_BuildInParallel)" StopOnFirstFailure="false" Properties="UsesHelixSdk=true" /> </Target> <!-- Choose a suitable runtime RID for Helix to restore the dotnet cli --> <PropertyGroup Condition="'$(HelixRuntimeRid)' == ''"> <TargetOSSpec>$(TargetOS)$(TargetOSSubgroup)</TargetOSSpec> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'windows'">win-$(TargetArchitecture)</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'OSX'">osx-$(TargetArchitecture)</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'Linux'">linux-$(TargetArchitecture)</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'Linux_musl'">linux-musl-$(TargetArchitecture)</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'Browser'">browser-wasm</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'Android'">android-$(TargetArchitecture)</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'iOSSimulator'">iossimulator-$(TargetArchitecture)</HelixRuntimeRid> </PropertyGroup> <PropertyGroup> <TargetHasHelixXHarnessSdkSupport>false</TargetHasHelixXHarnessSdkSupport> <TargetHasHelixXHarnessSdkSupport Condition="'$(TargetsMobile)' == 'true' and '$(TargetsBrowser)' != 'true'">true</TargetHasHelixXHarnessSdkSupport> </PropertyGroup> <PropertyGroup> <TestEnvFileName Condition=" '$(TestWrapperTargetsWindows)' == 'true' ">SetStressModes_$(Scenario).cmd</TestEnvFileName> <TestEnvFileName Condition=" '$(TestWrapperTargetsWindows)' != 'true' ">SetStressModes_$(Scenario).sh</TestEnvFileName> <IncludeDotNetCli>true</IncludeDotNetCli> <DotNetCliPackageType>runtime</DotNetCliPackageType> <DotNetCliVersion>$(BundledNETCoreAppPackageVersion)</DotNetCliVersion> <DotNetCliRuntime>$(HelixRuntimeRid)</DotNetCliRuntime> </PropertyGroup> <PropertyGroup Condition="'$(TargetsBrowser)' == 'true' Or '$(TargetsAndroid)' == 'true'"> <DotNetCliPackageType>sdk</DotNetCliPackageType> <GlobalJsonContent>$([System.IO.File]::ReadAllText('$(RepoRoot)global.json'))</GlobalJsonContent> <DotNetCliVersion>$([System.Text.RegularExpressions.Regex]::Match($(GlobalJsonContent), '(%3F&lt;="dotnet": ").*(%3F=")'))</DotNetCliVersion> <!-- wasm and Android need to use the host OS DotnetCliRuntime --> <DotNetCliRuntime>linux-x64</DotNetCliRuntime> <DotNetCliRuntime Condition=" '$(TargetArchitecture)' == 'arm64' ">win-x64</DotNetCliRuntime> </PropertyGroup> <PropertyGroup Condition="'$(TargetsAppleMobile)' == 'true'"> <DotNetCliPackageType>sdk</DotNetCliPackageType> <GlobalJsonContent>$([System.IO.File]::ReadAllText('$(RepoRoot)global.json'))</GlobalJsonContent> <DotNetCliVersion>$([System.Text.RegularExpressions.Regex]::Match($(GlobalJsonContent), '(%3F&lt;="dotnet": ").*(%3F=")'))</DotNetCliVersion> <!-- Apple mobile test runs need to use the host OS DotnetCliRuntime --> <DotNetCliRuntime>osx-x64</DotNetCliRuntime> </PropertyGroup> <PropertyGroup Condition="'$(TargetsMobile)' == 'true'"> <IncludeXHarnessCli>true</IncludeXHarnessCli> <EnableXHarnessTelemetry>true</EnableXHarnessTelemetry> </PropertyGroup> <Import Project="testgrouping.proj" /> <Target Name="DiscoverLegacyXUnitWrappers"> <ItemGroup> <_XUnitWrapperDll Include="%(TestGrouping.XUnitWrapperDll)" Condition="Exists('%(XUnitWrapperDll)')"> <PayloadGroup>%(TestGroup)</PayloadGroup> </_XUnitWrapperDll> <_XUnitWrapperDll Include="@(XUnitWrapperGrouping)" /> <!-- This adds the remaining *.XUnitWrapper.dll files in TestBinDir unless 1) they are in LegacyPayloadsRootDirectory or 2) they are grouped by XUnitWrapperGrouping. --> <_XUnitWrapperDll Include="$(TestBinDir)**\*.XUnitWrapper.dll" Exclude="$(LegacyPayloadsRootDirectory)**\*.XUnitWrapper.dll;@(XUnitWrapperGrouping->Metadata('FullPath'))"> <!-- Set PayloadGroup to empty string, so we can update _XUnitWrapperDll items with no PayloadGroup to default value. Unfortunatelly, we can't do this right here. --> <PayloadGroup></PayloadGroup> </_XUnitWrapperDll> <!-- Assign "default" value of PayloadGroup metadata. --> <_XUnitWrapperDll Update="@(_XUnitWrapperDll)"> <PayloadGroup Condition="'%(PayloadGroup)' == ''">$([MSBuild]::ValueOrDefault(%(FileName),'').Replace('.XUnitWrapper',''))</PayloadGroup> </_XUnitWrapperDll> </ItemGroup> </Target> <Target Name="PrepareLegacyPayloadDirectory" Outputs="%(_XUnitWrapperDll.FileName)%(PayloadGroup)" DependsOnTargets="DiscoverLegacyXUnitWrappers"> <PropertyGroup> <_FileDirectory>%(_XUnitWrapperDll.RootDir)%(Directory)</_FileDirectory> <_PayloadGroup>%(_XUnitWrapperDll.PayloadGroup)</_PayloadGroup> <_XUnitWrapperDll>%(_XUnitWrapperDll.FullPath)</_XUnitWrapperDll> </PropertyGroup> <ItemGroup> <_TestGroupingRelevant Include="@(TestGrouping->WithMetadataValue('XUnitWrapperDll',$(_XUnitWrapperDll))->Metadata('FullPath'))" /> </ItemGroup> <PropertyGroup> <_TestGroupingExists>@(_TestGroupingRelevant->AnyHaveMetadataValue('TestGroup','$(_PayloadGroup)'))</_TestGroupingExists> </PropertyGroup> <ItemGroup Condition="'$(_FileDirectory)' != ''"> <!-- If no TestGrouping is defined, all the files under $(_FileDirectory) and its subdirectories goes to the PayloadDirectory. --> <_LegacyPayloadFiles Include="$(_FileDirectory)**" Exclude="@(_TestGroupingRelevant)" Condition="'$(_TestGroupingExists)' != 'true'" /> <!-- If there is a TestGrouping, then take only the files that belong to the TestGroup == $(_PayloadGroup). --> <_LegacyPayloadFiles Include="@(_TestGroupingRelevant->WithMetadataValue('TestGroup','$(_PayloadGroup)')->DistinctWithCase())" Condition="'$(_TestGroupingExists)' == 'true'" /> <_LegacyPayloadFiles Include="$(_FileDirectory)*" Condition="'$(_TestGroupingExists)' == 'true'" /> <_LegacyPayloadFiles Include="$(_FileDirectory)/*.app" Condition="'$(_TestGroupingExists)' == 'true'" /> <_LegacyPayloadFiles Include="$(_FileDirectory)/*.app/**" Condition="'$(_TestGroupingExists)' == 'true'" /> <_LegacyPayloadFiles Update="@(_LegacyPayloadFiles)"> <!-- Never use [MSBuild]::MakeRelative here! We have some files containing Unicode characters in their %(FullPath) and MakeRelative function calls Escape function internally that replaces all the Unicode characters with %<xx>. --> <FileRelativeToPayloadsRootDirectory>$(_PayloadGroup)\$([System.IO.Path]::GetRelativePath($(TestBinDir), %(FullPath)))</FileRelativeToPayloadsRootDirectory> </_LegacyPayloadFiles> </ItemGroup> <ItemGroup> <!-- Remove the managed pdbs from our payloads. This is for performance reasons to reduce our helix payload size --> <ReducedLegacyPayloadFiles Include="@(_LegacyPayloadFiles)" Condition=" '%(Extension)' != '.pdb' " /> <ReducedLegacyPayloadFilesFinal Include="@(ReducedLegacyPayloadFiles)" Condition=" '%(Extension)' != '.sh' and '$(TestWrapperTargetsWindows)' == 'true' "/> <ReducedLegacyPayloadFilesFinal Include="@(ReducedLegacyPayloadFiles)" Condition=" '%(Extension)' != '.cmd' and '$(TestWrapperTargetsWindows)' != 'true' "/> <!-- Don't include the new merged wrappers in the legacy builds --> <ReducedLegacyPayloadFilesFinal Remove="@(_MergedWrapperRunScript)" /> </ItemGroup> <PropertyGroup Condition="'$(TargetsMobile)' == 'true'"> <!-- When targeting mobile or browser runs, we publish self-contained builds and build mobile/wasm apps, so we want to exclude these files from the legacy payloads as well --> <PublishedMergedPayloadsToExclude>@(_MergedWrapperRunScript->'%(RootDir)%(Directory)publish/*')</PublishedMergedPayloadsToExclude> <PublishedMergedPayloadsToExclude>$(PublishedMergedPayloadsToExclude);@(_MergedWrapperRunScript->'%(RootDir)%(Directory)AppBundle/**')</PublishedMergedPayloadsToExclude> </PropertyGroup> <ItemGroup> <ReducedLegacyPayloadFilesFinal Remove="$(PublishedMergedPayloadsToExclude)" /> </ItemGroup> <Copy SourceFiles="@(ReducedLegacyPayloadFilesFinal)" DestinationFiles="@(ReducedLegacyPayloadFilesFinal->'$(LegacyPayloadsRootDirectory)%(FileRelativeToPayloadsRootDirectory)')" /> </Target> <Target Name="PrepareCorrelationPayloadDirectory"> <MSBuild Projects="$(RepoRoot)src\tests\Common\xunitconsolerunner.depproj" Targets="Restore" /> <ItemGroup> <_XUnitConsoleRunnerFiles Include="$(NuGetPackageRoot)Microsoft.DotNet.XUnitConsoleRunner\$(MicrosoftDotNetXUnitConsoleRunnerVersion)\**\xunit.console.*" /> </ItemGroup> <Copy SourceFiles="@(_XUnitConsoleRunnerFiles)" DestinationFolder="$(CoreRootDirectory)\xunit" /> <Copy SourceFiles="$(MSBuildThisFileDirectory)scripts\runincontext.cmd" DestinationFolder="$(CoreRootDirectory)" Condition=" '$(TestWrapperTargetsWindows)' == 'true' and '$(_RunInUnloadableContext)' == 'true'" /> <Copy SourceFiles="$(MSBuildThisFileDirectory)scripts/runincontext.sh" DestinationFolder="$(CoreRootDirectory)" Condition=" '$(TestWrapperTargetsWindows)' != 'true' and '$(_RunInUnloadableContext)' == 'true'" /> <Copy SourceFiles="$(MSBuildThisFileDirectory)scripts\tieringtest.cmd" DestinationFolder="$(CoreRootDirectory)" Condition=" '$(TestWrapperTargetsWindows)' == 'true' and '$(_TieringTest)' == 'true'" /> <Copy SourceFiles="$(MSBuildThisFileDirectory)scripts/tieringtest.sh" DestinationFolder="$(CoreRootDirectory)" Condition=" '$(TestWrapperTargetsWindows)' != 'true' and '$(_TieringTest)' == 'true'" /> </Target> <Target Name="CreateTestEnvFiles" Condition="'$(PayloadGroups)' != ''"> <!-- This target creates one __TestEnv file for each combination of %(_PayloadGroups.Identity) and $(Scenario). --> <ItemGroup> <_PayloadGroups Include="$(PayloadGroups)" /> <_ProjectsToBuild Include="testenvironment.proj" Condition="!$(IsMergedTestWrapper)"> <Properties>Scenario=$(Scenario);TestEnvFileName=$(LegacyPayloadsRootDirectory)%(_PayloadGroups.Identity)\$(TestEnvFileName);TargetsWindows=$(TestWrapperTargetsWindows);RuntimeVariant=$(_RuntimeVariant)</Properties> </_ProjectsToBuild> <_ProjectsToBuild Include="testenvironment.proj" Condition="$(IsMergedTestWrapper)"> <Properties>Scenario=$(Scenario);TestEnvFileName=$(MergedPayloadsRootDirectory)%(_PayloadGroups.Identity)\$(TestEnvFileName);TargetsWindows=$(TestWrapperTargetsWindows);RuntimeVariant=$(_RuntimeVariant)</Properties> </_ProjectsToBuild> </ItemGroup> <MSBuild Projects="@(_ProjectsToBuild)" Targets="CreateTestEnvFile" StopOnFirstFailure="true" /> </Target> <Target Name="PreparePALTestArchive"> <Exec Condition="'$(PALTestsDir)' != '' and '$(TestWrapperTargetsWindows)' != 'true'" WorkingDirectory="$(PALTestsDir)" Command="tar -czvf $(LegacyPayloadsRootDirectory)paltests.tar.gz `ls -A`"/> </Target> <Target Name="PreparePayloadDirectories" DependsOnTargets="PrepareMergedTestPayloadDirectories;PrepareLegacyPayloadDirectories" /> <Target Name="PrepareLegacyPayloadDirectories" DependsOnTargets="PrepareLegacyPayloadDirectory"> <ItemGroup> <_LegacyPayloadGroups Include="@(_XUnitWrapperDll->Metadata('PayloadGroup')->DistinctWithCase())" /> <_Scenario Include="$(_Scenarios.Split(','))" /> <_ProjectsToBuild Include="$(MSBuildProjectFile)"> <AdditionalProperties>Scenario=%(_Scenario.Identity);PayloadGroups=@(_LegacyPayloadGroups);IsMergedTestWrapper=false</AdditionalProperties> </_ProjectsToBuild> </ItemGroup> <MSBuild Projects="@(_ProjectsToBuild)" Targets="CreateTestEnvFiles" StopOnFirstFailure="true" /> </Target> <Target Name="PrepareMergedTestPayloadDirectories" DependsOnTargets="PrepareMergedTestPayloadDirectory"> <ItemGroup> <_Scenario Include="$(_Scenarios.Split(','))" /> <_ProjectsToBuild Include="$(MSBuildProjectFile)"> <AdditionalProperties>Scenario=%(_Scenario.Identity);PayloadGroups=@(_MergedPayloadGroups);IsMergedTestWrapper=true</AdditionalProperties> </_ProjectsToBuild> </ItemGroup> <MSBuild Projects="@(_ProjectsToBuild)" Targets="CreateTestEnvFiles" StopOnFirstFailure="true" /> </Target> <Target Name="DiscoverMergedTestWrappers"> <ItemGroup> <_MergedWrapperMarker Include="$(TestBinDir)**\*.MergedTestAssembly" /> </ItemGroup> </Target> <Target Name="PrepareMergedTestPayloadDirectoryForDesktop" Condition="'$(TargetsMobile)' != 'true'" Outputs="%(_MergedWrapperMarker.FileName)" DependsOnTargets="DiscoverMergedTestWrappers"> <ItemGroup> <_MergedWrapperRunScript Include="$([System.IO.Path]::ChangeExtension('%(_MergedWrapperMarker.Identity)', '.$(TestScriptExtension)'))" /> </ItemGroup> <PropertyGroup> <_MergedWrapperDirectory>%(_MergedWrapperRunScript.RootDir)%(Directory)</_MergedWrapperDirectory> <_MergedWrapperName>%(_MergedWrapperRunScript.FileName)</_MergedWrapperName> <_MergedWrapperRunScriptRelative Condition="'%(_MergedWrapperRunScript.Identity)' != ''">$([System.IO.Path]::GetRelativePath($(TestBinDir), %(_MergedWrapperRunScript.FullPath)))</_MergedWrapperRunScriptRelative> </PropertyGroup> <ItemGroup> <_MergedPayloadGroups Include="$(_MergedWrapperName)" /> <_MergedPayloadFiles Include="$(_MergedWrapperDirectory)**" /> <_MergedPayloadFiles Update="@(_MergedPayloadFiles)"> <!-- Never use [MSBuild]::MakeRelative here! We have some files containing Unicode characters in their %(FullPath) and MakeRelative function calls Escape function internally that replaces all the Unicode characters with %<xx>. --> <FileRelativeToPayloadsRootDirectory>$([System.IO.Path]::GetRelativePath($(TestBinDir), %(FullPath)))</FileRelativeToPayloadsRootDirectory> </_MergedPayloadFiles> </ItemGroup> <ItemGroup> <!-- Remove the managed pdbs from our payloads. This is for performance reasons to reduce our helix payload size --> <ReducedMergedPayloadFilesFinal Include="@(_MergedPayloadFiles)" Condition=" '%(Extension)' != '.pdb' " /> </ItemGroup> <Copy SourceFiles="@(ReducedMergedPayloadFilesFinal)" DestinationFiles="@(ReducedMergedPayloadFilesFinal->'$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\%(FileRelativeToPayloadsRootDirectory)')" /> <WriteLinesToFile File="$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\HelixCommand.txt" Lines="$(_MergedWrapperRunScriptRelative)" /> </Target> <Target Name="PrepareMergedTestPayloadDirectoryForAndroid" Condition="'$(TargetsAndroid)' == 'true'" Outputs="%(_MergedWrapperMarker.FileName)" DependsOnTargets="DiscoverMergedTestWrappers"> <PropertyGroup> <_MergedWrapperDirectory>%(_MergedWrapperMarker.RootDir)%(Directory)</_MergedWrapperDirectory> <_MergedWrapperName>%(_MergedWrapperMarker.FileName)</_MergedWrapperName> </PropertyGroup> <ItemGroup> <_MergedPayloadGroups Include="$(_MergedWrapperName)" /> <_MergedPayloadFiles Include="@(_MergedPayloadGroups->'$(_MergedWrapperDirectory)AppBundle/bin/%(Identity).apk')" /> </ItemGroup> <Copy SourceFiles="@(_MergedPayloadFiles)" DestinationFiles="@(_MergedPayloadFiles->'$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\%(FileName)%(Extension)')" /> </Target> <Target Name="PrepareMergedTestPayloadDirectoryForWasm" Condition="'$(TargetsBrowser)' == 'true'" Outputs="%(_MergedWrapperMarker.FileName)" DependsOnTargets="DiscoverMergedTestWrappers"> <ItemGroup> <_MergedWrapperRunScript Include="@(_MergedWrapperMarker->'%(RootDir)%(Directory)AppBundle/RunTests.$(TestScriptExtension)')" /> </ItemGroup> <PropertyGroup> <_MergedWrapperDirectory>%(_MergedWrapperMarker.RootDir)%(Directory)</_MergedWrapperDirectory> <_MergedWrapperName>%(_MergedWrapperMarker.FileName)</_MergedWrapperName> <_MergedWrapperRunScriptRelative Condition="'%(_MergedWrapperRunScript.Identity)' != ''">$([System.IO.Path]::GetRelativePath('$(_MergedWrapperDirectory)AppBundle', %(_MergedWrapperRunScript.FullPath)))</_MergedWrapperRunScriptRelative> <_MergedWrapperRunScriptRelative Condition="'$(TestWrapperTargetsWindows)' != 'true'">./$(_MergedWrapperRunScriptRelative)</_MergedWrapperRunScriptRelative> </PropertyGroup> <ItemGroup> <_MergedPayloadGroups Include="$(_MergedWrapperName)" /> <_MergedPayloadFiles Include="$(_MergedWrapperDirectory)AppBundle/**" /> <_MergedPayloadFiles Update="@(_MergedPayloadFiles)"> <!-- Never use [MSBuild]::MakeRelative here! We have some files containing Unicode characters in their %(FullPath) and MakeRelative function calls Escape function internally that replaces all the Unicode characters with %<xx>. --> <FileRelativeToPayloadsRootDirectory>$([System.IO.Path]::GetRelativePath('$(_MergedWrapperDirectory)AppBundle', %(FullPath)))</FileRelativeToPayloadsRootDirectory> </_MergedPayloadFiles> </ItemGroup> <Copy SourceFiles="@(_MergedPayloadFiles)" DestinationFiles="@(_MergedPayloadFiles->'$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\%(FileRelativeToPayloadsRootDirectory)')" /> <WriteLinesToFile File="$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\HelixCommand.txt" Lines="$(_MergedWrapperRunScriptRelative)" /> </Target> <Target Name="PrepareMergedTestPayloadDirectoryForAppleMobile" Condition="'$(TargetsAppleMobile)' == 'true'" Outputs="%(_MergedWrapperMarker.FileName)" DependsOnTargets="DiscoverMergedTestWrappers"> <PropertyGroup> <_MergedWrapperDirectory>%(_MergedWrapperMarker.RootDir)%(Directory)</_MergedWrapperDirectory> <_MergedWrapperName>%(_MergedWrapperMarker.FileName)</_MergedWrapperName> </PropertyGroup> <PropertyGroup> <XCodeSdk Condition="'$(TargetsiOS)' == 'true'">iphone</XCodeSdk> <XCodeSdk Condition="'$(TargetsiOSSimulator)' == 'true'">iphonesimulator</XCodeSdk> <XCodeSdk Condition="'$(TargetstvOS)' == 'true'">appletvos</XCodeSdk> <XCodeSdk Condition="'$(TargetstvOSSimulator)' == 'true'">appletvsimulator</XCodeSdk> <XCodeSdk Condition="'$(TargetsMacCatalyst)' == 'true'">maccatalyst</XCodeSdk> </PropertyGroup> <ItemGroup> <_MergedPayloadGroups Include="$(_MergedWrapperName)" /> </ItemGroup> <ItemGroup> <_MergedPayloadFiles Include="$(_MergedWrapperDirectory)AppBundle/$(_MergedWrapperName)/$(Configuration)-$(XCodeSdk)/$(_MergedWrapperName).app/**" /> <_MergedPayloadFiles Update="@(_MergedPayloadFiles)"> <!-- Never use [MSBuild]::MakeRelative here! We have some files containing Unicode characters in their %(FullPath) and MakeRelative function calls Escape function internally that replaces all the Unicode characters with %<xx>. --> <FileRelativeToPayloadsRootDirectory>$([System.IO.Path]::GetRelativePath('$(_MergedWrapperDirectory)AppBundle/$(_MergedWrapperName)/$(Configuration)-$(XCodeSdk)', %(FullPath)))</FileRelativeToPayloadsRootDirectory> </_MergedPayloadFiles> </ItemGroup> <Copy SourceFiles="@(_MergedPayloadFiles)" DestinationFiles="@(_MergedPayloadFiles->'$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\%(FileRelativeToPayloadsRootDirectory)')" /> </Target> <Target Name="PrepareMergedTestPayloadDirectory" DependsOnTargets="DiscoverMergedTestWrappers;PrepareMergedTestPayloadDirectoryForDesktop;PrepareMergedTestPayloadDirectoryForAndroid;PrepareMergedTestPayloadDirectoryForWasm;PrepareMergedTestPayloadDirectoryForAppleMobile" /> <Target Name="ZipLegacyPayloadDirectory" AfterTargets="PrepareLegacyPayloadDirectories" Condition="'$(TargetHasHelixXHarnessSdkSupport)' == 'true'"> <ItemGroup> <LegacyPayloads Include="$([System.IO.Directory]::GetDirectories($(LegacyPayloadsRootDirectory)))" Condition="Exists('$(LegacyPayloadsRootDirectory)')" /> <LegacyPayloads Update="@(LegacyPayloads)"> <PayloadGroup>$([MSBuild]::MakeRelative($(LegacyPayloadsRootDirectory), %(FullPath)))</PayloadGroup> <PayloadDirectory>%(FullPath)</PayloadDirectory> </LegacyPayloads> </ItemGroup> <ZipDirectory SourceDirectory="@(LegacyPayloads->Metadata('PayloadDirectory'))" DestinationFile="$(LegacyPayloadsRootDirectory)\%(LegacyPayloads.PayloadGroup).zip" /> </Target> <Target Name="ZipMergedPayloadDirectory" AfterTargets="PrepareMergedTestPayloadDirectories" Condition="'$(TargetsBrowser)' == 'true'"> <ItemGroup> <MergedPayloads Include="$([System.IO.Directory]::GetDirectories($(MergedPayloadsRootDirectory)))" Condition="Exists('$(MergedPayloadsRootDirectory)')" /> <MergedPayloads Update="@(MergedPayloads)"> <PayloadGroup>$([MSBuild]::MakeRelative($(MergedPayloadsRootDirectory), %(FullPath)))</PayloadGroup> <PayloadDirectory>%(FullPath)</PayloadDirectory> </MergedPayloads> </ItemGroup> <ZipDirectory SourceDirectory="@(MergedPayloads->Metadata('PayloadDirectory'))" DestinationFile="$(MergedPayloadsRootDirectory)\%(MergedPayloads.PayloadGroup).zip" /> </Target> <PropertyGroup> <EnableAzurePipelinesReporter>$(PublishTestResults)</EnableAzurePipelinesReporter> <EnableAzurePipelinesReporter Condition=" '$(EnableAzurePipelinesReporter)' == '' ">false</EnableAzurePipelinesReporter> <FailOnMissionControlTestFailure>true</FailOnMissionControlTestFailure> <FailOnWorkItemFailure>true</FailOnWorkItemFailure> <HelixArchitecture>$(TargetArchitecture)</HelixArchitecture> <HelixConfiguration Condition=" '$(Scenario)' == 'normal' ">$(Configuration)</HelixConfiguration> <HelixConfiguration Condition=" '$(Scenario)' != 'normal' ">$(Configuration)-$(Scenario)</HelixConfiguration> <RunCrossGen Condition=" '$(RunCrossGen)' != 'true' ">false</RunCrossGen> <RunCrossGen2 Condition=" '$(RunCrossGen2)' != 'true' ">false</RunCrossGen2> <LongRunningGCTests Condition=" '$(LongRunningGCTests)' != 'true' ">false</LongRunningGCTests> <GcSimulatorTests Condition=" '$(GcSimulatorTests)' != 'true' ">false</GcSimulatorTests> <TestRunNamePrefix Condition="'$(RuntimeFlavorDisplayName)' != ''">$(RuntimeFlavorDisplayName) </TestRunNamePrefix> <TestRunNamePrefix Condition=" '$(RunCrossGen)' == 'true' ">R2R </TestRunNamePrefix> <TestRunNamePrefix Condition=" '$(RunCrossGen2)' == 'true' ">R2R-CG2 </TestRunNamePrefix> <TestRunNamePrefix Condition=" '$(Scenario)' == 'normal' ">$(TestRunNamePrefix)$(TargetOS) $(TargetArchitecture) $(Configuration) @ </TestRunNamePrefix> <TestRunNamePrefix Condition=" '$(Scenario)' != 'normal' ">$(TestRunNamePrefix)$(TargetOS) $(TargetArchitecture) $(Configuration) $(Scenario) @ </TestRunNamePrefix> <TimeoutPerTestInMilliseconds Condition=" '$(TimeoutPerTestInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestInMinutes)).TotalMilliseconds)</TimeoutPerTestInMilliseconds> <WaitForWorkItemCompletion>true</WaitForWorkItemCompletion> <_XUnitParallelMode>collections</_XUnitParallelMode> <_XUnitParallelMode Condition=" '$(TargetsAndroid)' == 'true' or '$(TargetsiOSSimulator)' == 'true'">none</_XUnitParallelMode> <_XUnitParallelMode Condition=" '$(LongRunningGCTests)' == 'true' ">none</_XUnitParallelMode> <_XUnitParallelMode Condition=" '$(GcSimulatorTests)' == 'true' ">none</_XUnitParallelMode> <XUnitRunnerArgs>-parallel $(_XUnitParallelMode) -nocolor -noshadow -xml testResults.xml</XUnitRunnerArgs> </PropertyGroup> <!-- WARNING: HelixPreCommand ItemGroup is intentionally minimal and should be kept that way. --> <ItemGroup Condition=" '$(TestWrapperTargetsWindows)' == 'true' "> <HelixPreCommand Include="taskkill.exe /f /im corerun.exe"/> <HelixPreCommand Include="set CORE_ROOT=%HELIX_CORRELATION_PAYLOAD%" /> <!-- Set _NT_SYMBOL_PATH so VM _ASSERTE() asserts can find the symbol files when doing stack walks --> <HelixPreCommand Include="set _NT_SYMBOL_PATH=%HELIX_CORRELATION_PAYLOAD%\PDB" /> <HelixPreCommand Include="set RunCrossGen2=1" Condition=" '$(RunCrossGen)' == 'true' " /> <HelixPreCommand Include="set RunCrossGen2=1" Condition=" '$(RunCrossGen2)' == 'true' " /> <HelixPreCommand Include="set CompositeBuildMode=1" Condition=" '$(CompositeBuildMode)' == 'true' " /> <HelixPreCommand Include="set RunningLongGCTests=1" Condition=" '$(LongRunningGCTests)' == 'true' " /> <HelixPreCommand Include="set RunningGCSimulatorTests=1" Condition=" '$(GcSimulatorTests)' == 'true' " /> <HelixPreCommand Include="set RunInUnloadableContext=1" Condition=" '$(RunInUnloadableContext)' == 'true' " /> <HelixPreCommand Include="set RunTieringTest=1" Condition=" '$(TieringTest)' == 'true' " /> <HelixPreCommand Include="set CLRCustomTestLauncher=%HELIX_CORRELATION_PAYLOAD%\runincontext.cmd" Condition=" '$(RunInUnloadableContext)' == 'true' " /> <HelixPreCommand Include="set CLRCustomTestLauncher=%HELIX_CORRELATION_PAYLOAD%\tieringtest.cmd" Condition=" '$(TieringTest)' == 'true' " /> <HelixPreCommand Include="set __TestEnv=%HELIX_WORKITEM_PAYLOAD%\$(TestEnvFileName)" /> <HelixPreCommand Include="set __TestTimeout=$(TimeoutPerTestInMilliseconds)" Condition=" '$(TimeoutPerTestInMilliseconds)' != '' " /> <HelixPreCommand Include="set __CollectDumps=1" /> <HelixPreCommand Include="set __CrashDumpFolder=%HELIX_DUMP_FOLDER%" /> <HelixPreCommand Include="type %__TestEnv%" /> </ItemGroup> <ItemGroup Condition=" '$(TestWrapperTargetsWindows)' == 'true' "> <HelixPostCommand Include="taskkill.exe /f /im corerun.exe"/> </ItemGroup> <ItemGroup Condition=" '$(TestWrapperTargetsWindows)' != 'true' "> <HelixPreCommand Include="export CORE_ROOT=$HELIX_CORRELATION_PAYLOAD" /> <HelixPreCommand Include="export RunCrossGen2=1" Condition=" '$(RunCrossGen)' == 'true' " /> <HelixPreCommand Include="export RunCrossGen2=1" Condition=" '$(RunCrossGen2)' == 'true' " /> <HelixPreCommand Include="export CompositeBuildMode=1" Condition=" '$(CompositeBuildMode)' == 'true' " /> <HelixPreCommand Include="export RunningLongGCTests=1" Condition=" '$(LongRunningGCTests)' == 'true' " /> <HelixPreCommand Include="export RunningGCSimulatorTests=1" Condition=" '$(GcSimulatorTests)' == 'true' " /> <HelixPreCommand Include="export RunInUnloadableContext=1" Condition=" '$(RunInUnloadableContext)' == 'true' " /> <HelixPreCommand Include="export RunTieringTest=1" Condition=" '$(TieringTest)' == 'true' " /> <HelixPreCommand Include="export CLRCustomTestLauncher=$HELIX_CORRELATION_PAYLOAD/runincontext.sh" Condition=" '$(RunInUnloadableContext)' == 'true' " /> <HelixPreCommand Include="export CLRCustomTestLauncher=$HELIX_CORRELATION_PAYLOAD/tieringtest.sh" Condition=" '$(TieringTest)' == 'true' " /> <HelixPreCommand Include="export __TestEnv=$HELIX_WORKITEM_PAYLOAD/$(TestEnvFileName)" /> <HelixPreCommand Include="export __TestTimeout=$(TimeoutPerTestInMilliseconds)" Condition=" '$(TimeoutPerTestInMilliseconds)' != '' " /> <HelixPreCommand Include="export __CollectDumps=1" /> <HelixPreCommand Include="export __CrashDumpFolder=$HELIX_DUMP_FOLDER" /> <HelixPreCommand Include="cat $__TestEnv" /> </ItemGroup> <PropertyGroup> <HelixPreCommands>@(HelixPreCommand)</HelixPreCommands> <HelixPostCommands>@(HelixPostCommand)</HelixPostCommands> </PropertyGroup> <PropertyGroup Condition=" '$(TestWrapperTargetsWindows)' == 'true' "> <!-- When the target has XHarness support in the Helix SDK, the script runs in a powershell context. Otherwise it runs in a Batch context. --> <XUnitRunnerDll Condition="'$(TargetHasHelixXHarnessSdkSupport)' == 'true'">$Env:CORE_ROOT\xunit\xunit.console.dll</XUnitRunnerDll> <XUnitRunnerDll Condition="'$(TargetHasHelixXHarnessSdkSupport)' != 'true'">%CORE_ROOT%\xunit\xunit.console.dll</XUnitRunnerDll> </PropertyGroup> <PropertyGroup Condition=" '$(TestWrapperTargetsWindows)' != 'true' "> <XUnitRunnerDll>$CORE_ROOT/xunit/xunit.console.dll</XUnitRunnerDll> </PropertyGroup> <ItemGroup Condition=" '$(UsesHelixSdk)' == 'true' "> <HelixCorrelationPayload Include="$(CoreRootDirectory)" /> <LegacyPayloads Include="$([System.IO.Directory]::GetDirectories($(LegacyPayloadsRootDirectory)))" Condition="Exists('$(LegacyPayloadsRootDirectory)')" /> <LegacyPayloads Update="@(LegacyPayloads)"> <PayloadGroup>$([MSBuild]::MakeRelative($(LegacyPayloadsRootDirectory), %(FullPath)))</PayloadGroup> <PayloadDirectory>%(FullPath)</PayloadDirectory> <XUnitWrapperDlls>$([System.String]::Join(' ', $([System.IO.Directory]::GetFiles(%(FullPath), '*.XUnitWrapper.dll', SearchOption.AllDirectories))).Replace($([MSBuild]::EnsureTrailingSlash(%(FullPath))),''))</XUnitWrapperDlls> </LegacyPayloads> <LegacyPayloads Update="@(LegacyPayloads)"> <TestGroup>%(PayloadGroup)</TestGroup> <!-- When Payload contains more than one *.XUnitWrapper.dll TestGroup should not be specified. --> <TestGroup Condition=" $([MSBuild]::ValueOrDefault(%(XUnitWrapperDlls), '').IndexOf('.XUnitWrapper.dll')) != $([MSBuild]::ValueOrDefault(%(XUnitWrapperDlls), '').LastIndexOf('.XUnitWrapper.dll')) "></TestGroup> <PayloadZipFile>$(LegacyPayloadsRootDirectory)\%(PayloadGroup).zip</PayloadZipFile> </LegacyPayloads> </ItemGroup> <ItemGroup> <MergedPayloads Include="$([System.IO.Directory]::GetDirectories($(MergedPayloadsRootDirectory)))" Condition="Exists('$(MergedPayloadsRootDirectory)')" /> <MergedPayloads Update="@(MergedPayloads)"> <PayloadDirectory>%(FullPath)</PayloadDirectory> </MergedPayloads> </ItemGroup> <ItemGroup Condition="'$(TargetsMobile)' != 'true'"> <MergedPayloads Update="@(MergedPayloads)"> <PayloadHelixCommandFile>$(MergedPayloadsRootDirectory)%(FileName)%(Extension)\HelixCommand.txt</PayloadHelixCommandFile> <MergedTestHelixCommand>$([System.IO.File]::ReadAllText('%(PayloadHelixCommandFile)'))</MergedTestHelixCommand> <PayloadGroup>$([System.IO.Path]::GetDirectoryName('%(MergedTestHelixCommand)').Replace('/', '-').Replace('\', '-'))</PayloadGroup> <PayloadZipFile>$(MergedPayloadsRootDirectory)%(PayloadGroup).zip</PayloadZipFile> </MergedPayloads> </ItemGroup> <ItemGroup Condition="'$(TargetsBrowser)' == 'true'"> <MergedPayloads Update="@(MergedPayloads)"> <PayloadHelixCommandFile>$(MergedPayloadsRootDirectory)%(FileName)%(Extension)\HelixCommand.txt</PayloadHelixCommandFile> <MergedTestHelixCommand>$([System.IO.File]::ReadAllText('%(PayloadHelixCommandFile)'))</MergedTestHelixCommand> <PayloadGroup>%(FileName)%(Extension)</PayloadGroup> <PayloadZipFile>$(MergedPayloadsRootDirectory)%(PayloadGroup).zip</PayloadZipFile> </MergedPayloads> </ItemGroup> <ItemGroup Condition="'$(TargetHasHelixXHarnessSdkSupport)' != 'true'"> <MergedPayloads Update="@(MergedPayloads)" Condition="'$(TestWrapperTargetsWindows)' != 'true'"> <MergedTestHelixCommand>chmod +x %(MergedPayloads.MergedTestHelixCommand)%0A%(MergedPayloads.MergedTestHelixCommand)</MergedTestHelixCommand> </MergedPayloads> </ItemGroup> <ItemGroup Condition="'$(TargetHasHelixXHarnessSdkSupport)' == 'true'"> <MergedPayloads Update="@(MergedPayloads)"> <PayloadGroup>%(FileName)%(Extension)</PayloadGroup> <ApkPath>$(MergedPayloadsRootDirectory)%(FileName)%(Extension)/%(FileName)%(Extension).apk</ApkPath> <AppBundlePath>$(MergedPayloadsRootDirectory)%(FileName)%(Extension)/%(FileName)%(Extension).app</AppBundlePath> </MergedPayloads> </ItemGroup> <ItemGroup> <HelixWorkItem Include="@(LegacyPayloads->Metadata('PayloadGroup'))" Condition="'$(TargetHasHelixXHarnessSdkSupport)' != 'true'"> <PayloadDirectory>%(PayloadDirectory)</PayloadDirectory> <Command>dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs)</Command> <Command Condition=" '%(TestGroup)' != '' ">dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs) -trait TestGroup=%(TestGroup)</Command> <Timeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</Timeout> </HelixWorkItem> <HelixWorkItem Include="@(MergedPayloads->Metadata('PayloadGroup'))" Condition="'$(TargetHasHelixXHarnessSdkSupport)' != 'true'"> <PayloadDirectory>%(PayloadDirectory)</PayloadDirectory> <Command>%(MergedTestHelixCommand)</Command> <Timeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</Timeout> </HelixWorkItem> <XHarnessApkToTest Include="@(LegacyPayloads->Metadata('PayloadZipFile'))" Condition="'$(TargetsAndroid)' == 'true'"> <TestTimeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</TestTimeout> <CustomCommands>dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs)</CustomCommands> <CustomCommands Condition=" '%(TestGroup)' != '' ">dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs) -trait TestGroup=%(TestGroup)</CustomCommands> </XHarnessApkToTest> <XHarnessApkToTest Include="@(MergedPayloads->Metadata('PayloadGroup'))" Condition="'$(TargetsAndroid)' == 'true'"> <AndroidPackageName>net.dot.%(PayloadGroup)</AndroidPackageName> <AndroidInstrumentationName>net.dot.MonoRunner</AndroidInstrumentationName> <TestTimeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</TestTimeout> </XHarnessApkToTest> <XHarnessAppBundleToTest Include="@(LegacyPayloads->Metadata('PayloadZipFile'))" Condition="'$(TargetsAppleMobile)' == 'true'"> <TestTarget Condition="'$(TargetArchitecture)' == 'arm64'">ios-simulator-64</TestTarget> <TestTarget Condition="'$(TargetArchitecture)' == 'x64'">ios-simulator-64</TestTarget> <TestTimeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</TestTimeout> <CustomCommands>dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs)</CustomCommands> <CustomCommands Condition=" '%(TestGroup)' != '' ">dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs) -trait TestGroup=%(TestGroup)</CustomCommands> </XHarnessAppBundleToTest> <XHarnessAppBundleToTest Include="@(MergedPayloads->Metadata('PayloadGroup'))" Condition="'$(TargetsAppleMobile)' == 'true'"> <TestTarget Condition="'$(TargetArchitecture)' == 'arm64'">ios-simulator-64</TestTarget> <TestTarget Condition="'$(TargetArchitecture)' == 'x64'">ios-simulator-64</TestTarget> <TestTimeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</TestTimeout> </XHarnessAppBundleToTest> <HelixWorkItem Condition="'$(PALTestsDir)' != '' and '$(TestWrapperTargetsWindows)' != 'true'" Include="PALTests"> <PayloadArchive>$(LegacyPayloadsRootDirectory)paltests.tar.gz</PayloadArchive> <Command>./runpaltestshelix.sh</Command> <Timeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</Timeout> </HelixWorkItem> </ItemGroup> <Import Sdk="Microsoft.DotNet.Helix.Sdk" Project="Sdk.targets" Condition=" '$(UsesHelixSdk)' == 'true' " /> <Import Sdk="Microsoft.Build.NoTargets" Project="Sdk.targets" Condition=" '$(UsesHelixSdk)' != 'true' " /> </Project>
<Project DefaultTargets="RunInParallelForEachScenario"> <!-- This project uses the helix SDK, documented at https://github.com/dotnet/arcade/tree/master/src/Microsoft.DotNet.Helix/Sdk, to send test jobs to helix. --> <Import Sdk="Microsoft.DotNet.Helix.Sdk" Project="Sdk.props" Condition=" '$(UsesHelixSdk)' == 'true' " /> <Import Sdk="Microsoft.Build.NoTargets" Project="Sdk.props" Condition=" '$(UsesHelixSdk)' != 'true' " /> <PropertyGroup> <CoreRootDirectory>$(TestBinDir)Tests\Core_Root\</CoreRootDirectory> <LegacyPayloadsRootDirectory>$(TestBinDir)LegacyPayloads\</LegacyPayloadsRootDirectory> <LegacyPayloadsRootDirectory>$([MSBuild]::NormalizeDirectory($(LegacyPayloadsRootDirectory)))</LegacyPayloadsRootDirectory> <MergedPayloadsRootDirectory>$(TestBinDir)MergedPayloads\</MergedPayloadsRootDirectory> <MergedPayloadsRootDirectory>$([MSBuild]::NormalizeDirectory($(MergedPayloadsRootDirectory)))</MergedPayloadsRootDirectory> </PropertyGroup> <!-- This target runs once and creates several instances of this project (one for each scenario) that will run in parallel. --> <Target Name="RunInParallelForEachScenario"> <PropertyGroup> <!-- This specifies what properties are needed to be passed down as global properties to a child project. --> <_PropertiesToPass> TargetArchitecture=$(TargetArchitecture); TargetOS=$(TargetOS); Configuration=$(Configuration); Creator=$(_Creator); HelixAccessToken=$(_HelixAccessToken); HelixBuild=$(_HelixBuild); HelixSource=$(_HelixSource); HelixTargetQueues=$(_HelixTargetQueues); HelixType=$(_HelixType); PublishTestResults=$(_PublishTestResults); RunCrossGen=$(_RunCrossGen); RunCrossGen2=$(_RunCrossGen2); CompositeBuildMode=$(_CompositeBuildMode); LongRunningGCTests=$(_LongRunningGCTests); GcSimulatorTests=$(_GcSimulatorTests); RunInUnloadableContext=$(_RunInUnloadableContext); TieringTest=$(_TieringTest); TimeoutPerTestCollectionInMinutes=$(_TimeoutPerTestCollectionInMinutes); TimeoutPerTestInMinutes=$(_TimeoutPerTestInMinutes); RuntimeVariant=$(_RuntimeVariant); BundledNETCoreAppPackageVersion=$(BundledNETCoreAppPackageVersion); HelixRuntimeRid=$(HelixRuntimeRid); PALTestsDir=$(_PALTestsDir) </_PropertiesToPass> <_PropertiesToPass Condition="'$(TargetOS)' == 'Browser' Or '$(TargetsAndroid)' == 'true'"> $(_PropertiesToPass); IncludeDotNetCli=$(IncludeDotNetCli); DotNetCliRuntime=$(DotNetCliRuntime); DotNetCliPackageType=$(DotNetCliPackageType); DotNetCliVersion=$(DotNetCliVersion) </_PropertiesToPass> </PropertyGroup> <Message Text="DotNetCliVersion: $(DotNetCliVersion)" Importance="High" /> <Message Text="DotNetCliPackageType: $(DotNetCliPackageType)" Importance="High" /> <Message Text="HelixRuntimeRid: $(HelixRuntimeRid)" Importance="High" /> <Error Condition="'$(_Scenarios)' == ''" Text="_Scenarios not set" /> <ItemGroup> <CleanPreexistingPayloads Include="$(LegacyPayloadsRootDirectory)**" /> <CleanPreexistingPayloads Include="$(MergedPayloadsRootDirectory)**" /> </ItemGroup> <Delete Files="@(CleanPreexistingPayloads)" /> <MSBuild Projects="$(MSBuildProjectFile)" Targets="PrepareCorrelationPayloadDirectory" /> <MSBuild Projects="$(MSBuildProjectFile)" Targets="PreparePayloadDirectories" Properties="Scenarios=$(_Scenarios)" StopOnFirstFailure="true" /> <MSBuild Projects="$(MSBuildProjectFile)" Targets="PreparePALTestArchive" Properties="$(_PropertiesToPass)" StopOnFirstFailure="true" /> <ItemGroup> <_Scenarios Include="$(_Scenarios.Split(','))" /> <!-- MSBuild creates a new instance of the project for each %(_Scenarios.Identity) and can build them in parallel. --> <_ProjectsToBuild Include="$(MSBuildProjectFile)"> <AdditionalProperties>$(_PropertiesToPass);Scenario=%(_Scenarios.Identity)</AdditionalProperties> </_ProjectsToBuild> </ItemGroup> <PropertyGroup> <_BuildInParallel>false</_BuildInParallel> <_BuildInParallel Condition=" '@(_ProjectsToBuild->Count())' &gt; '1' ">true</_BuildInParallel> </PropertyGroup> <MSBuild Projects="@(_ProjectsToBuild)" Targets="Test" BuildInParallel="$(_BuildInParallel)" StopOnFirstFailure="false" Properties="UsesHelixSdk=true" /> </Target> <!-- Choose a suitable runtime RID for Helix to restore the dotnet cli --> <PropertyGroup Condition="'$(HelixRuntimeRid)' == ''"> <TargetOSSpec>$(TargetOS)$(TargetOSSubgroup)</TargetOSSpec> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'windows'">win-$(TargetArchitecture)</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'OSX'">osx-$(TargetArchitecture)</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'Linux'">linux-$(TargetArchitecture)</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'Linux_musl'">linux-musl-$(TargetArchitecture)</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'Browser'">browser-wasm</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'Android'">android-$(TargetArchitecture)</HelixRuntimeRid> <HelixRuntimeRid Condition="'$(TargetOSSpec)' == 'iOSSimulator'">iossimulator-$(TargetArchitecture)</HelixRuntimeRid> </PropertyGroup> <PropertyGroup> <TargetHasHelixXHarnessSdkSupport>false</TargetHasHelixXHarnessSdkSupport> <TargetHasHelixXHarnessSdkSupport Condition="'$(TargetsMobile)' == 'true' and '$(TargetsBrowser)' != 'true'">true</TargetHasHelixXHarnessSdkSupport> </PropertyGroup> <PropertyGroup> <TestEnvFileName Condition=" '$(TestWrapperTargetsWindows)' == 'true' ">SetStressModes_$(Scenario).cmd</TestEnvFileName> <TestEnvFileName Condition=" '$(TestWrapperTargetsWindows)' != 'true' ">SetStressModes_$(Scenario).sh</TestEnvFileName> <IncludeDotNetCli>true</IncludeDotNetCli> <DotNetCliPackageType>runtime</DotNetCliPackageType> <DotNetCliVersion>$(BundledNETCoreAppPackageVersion)</DotNetCliVersion> <DotNetCliRuntime>$(HelixRuntimeRid)</DotNetCliRuntime> </PropertyGroup> <PropertyGroup Condition="'$(TargetsBrowser)' == 'true' Or '$(TargetsAndroid)' == 'true'"> <DotNetCliPackageType>sdk</DotNetCliPackageType> <GlobalJsonContent>$([System.IO.File]::ReadAllText('$(RepoRoot)global.json'))</GlobalJsonContent> <DotNetCliVersion>$([System.Text.RegularExpressions.Regex]::Match($(GlobalJsonContent), '(%3F&lt;="dotnet": ").*(%3F=")'))</DotNetCliVersion> <!-- wasm and Android need to use the host OS DotnetCliRuntime --> <DotNetCliRuntime>linux-x64</DotNetCliRuntime> <DotNetCliRuntime Condition=" '$(TargetArchitecture)' == 'arm64' ">win-x64</DotNetCliRuntime> </PropertyGroup> <PropertyGroup Condition="'$(TargetsAppleMobile)' == 'true'"> <DotNetCliPackageType>sdk</DotNetCliPackageType> <GlobalJsonContent>$([System.IO.File]::ReadAllText('$(RepoRoot)global.json'))</GlobalJsonContent> <DotNetCliVersion>$([System.Text.RegularExpressions.Regex]::Match($(GlobalJsonContent), '(%3F&lt;="dotnet": ").*(%3F=")'))</DotNetCliVersion> <!-- Apple mobile test runs need to use the host OS DotnetCliRuntime --> <DotNetCliRuntime>osx-x64</DotNetCliRuntime> </PropertyGroup> <PropertyGroup Condition="'$(TargetsMobile)' == 'true'"> <IncludeXHarnessCli>true</IncludeXHarnessCli> <EnableXHarnessTelemetry>true</EnableXHarnessTelemetry> </PropertyGroup> <Import Project="testgrouping.proj" /> <Target Name="DiscoverLegacyXUnitWrappers"> <ItemGroup> <_XUnitWrapperDll Include="%(TestGrouping.XUnitWrapperDll)" Condition="Exists('%(XUnitWrapperDll)')"> <PayloadGroup>%(TestGroup)</PayloadGroup> </_XUnitWrapperDll> <_XUnitWrapperDll Include="@(XUnitWrapperGrouping)" /> <!-- This adds the remaining *.XUnitWrapper.dll files in TestBinDir unless 1) they are in LegacyPayloadsRootDirectory or 2) they are grouped by XUnitWrapperGrouping. --> <_XUnitWrapperDll Include="$(TestBinDir)**\*.XUnitWrapper.dll" Exclude="$(LegacyPayloadsRootDirectory)**\*.XUnitWrapper.dll;@(XUnitWrapperGrouping->Metadata('FullPath'))"> <!-- Set PayloadGroup to empty string, so we can update _XUnitWrapperDll items with no PayloadGroup to default value. Unfortunatelly, we can't do this right here. --> <PayloadGroup></PayloadGroup> </_XUnitWrapperDll> <!-- Assign "default" value of PayloadGroup metadata. --> <_XUnitWrapperDll Update="@(_XUnitWrapperDll)"> <PayloadGroup Condition="'%(PayloadGroup)' == ''">$([MSBuild]::ValueOrDefault(%(FileName),'').Replace('.XUnitWrapper',''))</PayloadGroup> </_XUnitWrapperDll> </ItemGroup> </Target> <Target Name="PrepareLegacyPayloadDirectory" Outputs="%(_XUnitWrapperDll.FileName)%(PayloadGroup)" DependsOnTargets="DiscoverLegacyXUnitWrappers"> <PropertyGroup> <_FileDirectory>%(_XUnitWrapperDll.RootDir)%(Directory)</_FileDirectory> <_PayloadGroup>%(_XUnitWrapperDll.PayloadGroup)</_PayloadGroup> <_XUnitWrapperDll>%(_XUnitWrapperDll.FullPath)</_XUnitWrapperDll> </PropertyGroup> <ItemGroup> <_TestGroupingRelevant Include="@(TestGrouping->WithMetadataValue('XUnitWrapperDll',$(_XUnitWrapperDll))->Metadata('FullPath'))" /> </ItemGroup> <PropertyGroup> <_TestGroupingExists>@(_TestGroupingRelevant->AnyHaveMetadataValue('TestGroup','$(_PayloadGroup)'))</_TestGroupingExists> </PropertyGroup> <ItemGroup Condition="'$(_FileDirectory)' != ''"> <!-- If no TestGrouping is defined, all the files under $(_FileDirectory) and its subdirectories goes to the PayloadDirectory. --> <_LegacyPayloadFiles Include="$(_FileDirectory)**" Exclude="@(_TestGroupingRelevant)" Condition="'$(_TestGroupingExists)' != 'true'" /> <!-- If there is a TestGrouping, then take only the files that belong to the TestGroup == $(_PayloadGroup). --> <_LegacyPayloadFiles Include="@(_TestGroupingRelevant->WithMetadataValue('TestGroup','$(_PayloadGroup)')->DistinctWithCase())" Condition="'$(_TestGroupingExists)' == 'true'" /> <_LegacyPayloadFiles Include="$(_FileDirectory)*" Condition="'$(_TestGroupingExists)' == 'true'" /> <_LegacyPayloadFiles Include="$(_FileDirectory)/*.app" Condition="'$(_TestGroupingExists)' == 'true'" /> <_LegacyPayloadFiles Include="$(_FileDirectory)/*.app/**" Condition="'$(_TestGroupingExists)' == 'true'" /> <_LegacyPayloadFiles Update="@(_LegacyPayloadFiles)"> <!-- Never use [MSBuild]::MakeRelative here! We have some files containing Unicode characters in their %(FullPath) and MakeRelative function calls Escape function internally that replaces all the Unicode characters with %<xx>. --> <FileRelativeToPayloadsRootDirectory>$(_PayloadGroup)\$([System.IO.Path]::GetRelativePath($(TestBinDir), %(FullPath)))</FileRelativeToPayloadsRootDirectory> </_LegacyPayloadFiles> </ItemGroup> <ItemGroup> <!-- Remove the managed pdbs from our payloads. This is for performance reasons to reduce our helix payload size --> <ReducedLegacyPayloadFiles Include="@(_LegacyPayloadFiles)" Condition=" '%(Extension)' != '.pdb' " /> <ReducedLegacyPayloadFilesFinal Include="@(ReducedLegacyPayloadFiles)" Condition=" '%(Extension)' != '.sh' and '$(TestWrapperTargetsWindows)' == 'true' "/> <ReducedLegacyPayloadFilesFinal Include="@(ReducedLegacyPayloadFiles)" Condition=" '%(Extension)' != '.cmd' and '$(TestWrapperTargetsWindows)' != 'true' "/> <!-- Don't include the new merged wrappers in the legacy builds --> <ReducedLegacyPayloadFilesFinal Remove="@(_MergedWrapperRunScript)" /> </ItemGroup> <PropertyGroup Condition="'$(TargetsMobile)' == 'true'"> <!-- When targeting mobile or browser runs, we publish self-contained builds and build mobile/wasm apps, so we want to exclude these files from the legacy payloads as well --> <PublishedMergedPayloadsToExclude>@(_MergedWrapperRunScript->'%(RootDir)%(Directory)publish/*')</PublishedMergedPayloadsToExclude> <PublishedMergedPayloadsToExclude>$(PublishedMergedPayloadsToExclude);@(_MergedWrapperRunScript->'%(RootDir)%(Directory)AppBundle/**')</PublishedMergedPayloadsToExclude> </PropertyGroup> <ItemGroup> <ReducedLegacyPayloadFilesFinal Remove="$(PublishedMergedPayloadsToExclude)" /> </ItemGroup> <Copy SourceFiles="@(ReducedLegacyPayloadFilesFinal)" DestinationFiles="@(ReducedLegacyPayloadFilesFinal->'$(LegacyPayloadsRootDirectory)%(FileRelativeToPayloadsRootDirectory)')" /> </Target> <Target Name="PrepareCorrelationPayloadDirectory"> <MSBuild Projects="$(RepoRoot)src\tests\Common\xunitconsolerunner.depproj" Targets="Restore" /> <ItemGroup> <_XUnitConsoleRunnerFiles Include="$(NuGetPackageRoot)Microsoft.DotNet.XUnitConsoleRunner\$(MicrosoftDotNetXUnitConsoleRunnerVersion)\**\xunit.console.*" /> </ItemGroup> <Copy SourceFiles="@(_XUnitConsoleRunnerFiles)" DestinationFolder="$(CoreRootDirectory)\xunit" /> <Copy SourceFiles="$(MSBuildThisFileDirectory)scripts\runincontext.cmd" DestinationFolder="$(CoreRootDirectory)" Condition=" '$(TestWrapperTargetsWindows)' == 'true' and '$(_RunInUnloadableContext)' == 'true'" /> <Copy SourceFiles="$(MSBuildThisFileDirectory)scripts/runincontext.sh" DestinationFolder="$(CoreRootDirectory)" Condition=" '$(TestWrapperTargetsWindows)' != 'true' and '$(_RunInUnloadableContext)' == 'true'" /> <Copy SourceFiles="$(MSBuildThisFileDirectory)scripts\tieringtest.cmd" DestinationFolder="$(CoreRootDirectory)" Condition=" '$(TestWrapperTargetsWindows)' == 'true' and '$(_TieringTest)' == 'true'" /> <Copy SourceFiles="$(MSBuildThisFileDirectory)scripts/tieringtest.sh" DestinationFolder="$(CoreRootDirectory)" Condition=" '$(TestWrapperTargetsWindows)' != 'true' and '$(_TieringTest)' == 'true'" /> </Target> <Target Name="CreateTestEnvFiles" Condition="'$(PayloadGroups)' != ''"> <!-- This target creates one __TestEnv file for each combination of %(_PayloadGroups.Identity) and $(Scenario). --> <ItemGroup> <_PayloadGroups Include="$(PayloadGroups)" /> <_ProjectsToBuild Include="testenvironment.proj" Condition="!$(IsMergedTestWrapper)"> <Properties>Scenario=$(Scenario);TestEnvFileName=$(LegacyPayloadsRootDirectory)%(_PayloadGroups.Identity)\$(TestEnvFileName);TargetsWindows=$(TestWrapperTargetsWindows);RuntimeVariant=$(_RuntimeVariant)</Properties> </_ProjectsToBuild> <_ProjectsToBuild Include="testenvironment.proj" Condition="$(IsMergedTestWrapper)"> <Properties>Scenario=$(Scenario);TestEnvFileName=$(MergedPayloadsRootDirectory)%(_PayloadGroups.Identity)\$(TestEnvFileName);TargetsWindows=$(TestWrapperTargetsWindows);RuntimeVariant=$(_RuntimeVariant)</Properties> </_ProjectsToBuild> </ItemGroup> <MSBuild Projects="@(_ProjectsToBuild)" Targets="CreateTestEnvFile" StopOnFirstFailure="true" /> </Target> <Target Name="PreparePALTestArchive"> <Exec Condition="'$(PALTestsDir)' != '' and '$(TestWrapperTargetsWindows)' != 'true'" WorkingDirectory="$(PALTestsDir)" Command="tar -czvf $(LegacyPayloadsRootDirectory)paltests.tar.gz `ls -A`"/> </Target> <Target Name="PreparePayloadDirectories" DependsOnTargets="PrepareMergedTestPayloadDirectories;PrepareLegacyPayloadDirectories" /> <Target Name="PrepareLegacyPayloadDirectories" DependsOnTargets="PrepareLegacyPayloadDirectory"> <ItemGroup> <_LegacyPayloadGroups Include="@(_XUnitWrapperDll->Metadata('PayloadGroup')->DistinctWithCase())" /> <_Scenario Include="$(_Scenarios.Split(','))" /> <_ProjectsToBuild Include="$(MSBuildProjectFile)"> <AdditionalProperties>Scenario=%(_Scenario.Identity);PayloadGroups=@(_LegacyPayloadGroups);IsMergedTestWrapper=false</AdditionalProperties> </_ProjectsToBuild> </ItemGroup> <MSBuild Projects="@(_ProjectsToBuild)" Targets="CreateTestEnvFiles" StopOnFirstFailure="true" /> </Target> <Target Name="PrepareMergedTestPayloadDirectories" DependsOnTargets="PrepareMergedTestPayloadDirectory"> <ItemGroup> <_Scenario Include="$(_Scenarios.Split(','))" /> <_ProjectsToBuild Include="$(MSBuildProjectFile)"> <AdditionalProperties>Scenario=%(_Scenario.Identity);PayloadGroups=@(_MergedPayloadGroups);IsMergedTestWrapper=true</AdditionalProperties> </_ProjectsToBuild> </ItemGroup> <MSBuild Projects="@(_ProjectsToBuild)" Targets="CreateTestEnvFiles" StopOnFirstFailure="true" /> </Target> <Target Name="DiscoverMergedTestWrappers"> <ItemGroup> <_MergedWrapperMarker Include="$(TestBinDir)**\*.MergedTestAssembly" /> </ItemGroup> </Target> <Target Name="PrepareMergedTestPayloadDirectoryForDesktop" Condition="'$(TargetsMobile)' != 'true'" Outputs="%(_MergedWrapperMarker.FileName)" DependsOnTargets="DiscoverMergedTestWrappers"> <ItemGroup> <_MergedWrapperRunScript Include="$([System.IO.Path]::ChangeExtension('%(_MergedWrapperMarker.Identity)', '.$(TestScriptExtension)'))" /> </ItemGroup> <PropertyGroup> <_MergedWrapperDirectory>%(_MergedWrapperRunScript.RootDir)%(Directory)</_MergedWrapperDirectory> <_MergedWrapperName>%(_MergedWrapperRunScript.FileName)</_MergedWrapperName> <_MergedWrapperRunScriptRelative Condition="'%(_MergedWrapperRunScript.Identity)' != ''">$([System.IO.Path]::GetRelativePath($(TestBinDir), %(_MergedWrapperRunScript.FullPath)))</_MergedWrapperRunScriptRelative> </PropertyGroup> <ItemGroup> <_MergedPayloadGroups Include="$(_MergedWrapperName)" /> <_MergedPayloadFiles Include="$(_MergedWrapperDirectory)**" /> <_MergedPayloadFiles Update="@(_MergedPayloadFiles)"> <!-- Never use [MSBuild]::MakeRelative here! We have some files containing Unicode characters in their %(FullPath) and MakeRelative function calls Escape function internally that replaces all the Unicode characters with %<xx>. --> <FileRelativeToPayloadsRootDirectory>$([System.IO.Path]::GetRelativePath($(TestBinDir), %(FullPath)))</FileRelativeToPayloadsRootDirectory> </_MergedPayloadFiles> </ItemGroup> <ItemGroup> <!-- Remove the managed pdbs from our payloads. This is for performance reasons to reduce our helix payload size --> <ReducedMergedPayloadFilesFinal Include="@(_MergedPayloadFiles)" Condition=" '%(Extension)' != '.pdb' " /> </ItemGroup> <Copy SourceFiles="@(ReducedMergedPayloadFilesFinal)" DestinationFiles="@(ReducedMergedPayloadFilesFinal->'$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\%(FileRelativeToPayloadsRootDirectory)')" /> <WriteLinesToFile File="$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\HelixCommand.txt" Lines="$(_MergedWrapperRunScriptRelative)" /> </Target> <Target Name="PrepareMergedTestPayloadDirectoryForAndroid" Condition="'$(TargetsAndroid)' == 'true'" Outputs="%(_MergedWrapperMarker.FileName)" DependsOnTargets="DiscoverMergedTestWrappers"> <PropertyGroup> <_MergedWrapperDirectory>%(_MergedWrapperMarker.RootDir)%(Directory)</_MergedWrapperDirectory> <_MergedWrapperName>%(_MergedWrapperMarker.FileName)</_MergedWrapperName> </PropertyGroup> <ItemGroup> <_MergedPayloadGroups Include="$(_MergedWrapperName)" /> <_MergedPayloadFiles Include="@(_MergedPayloadGroups->'$(_MergedWrapperDirectory)AppBundle/bin/%(Identity).apk')" /> </ItemGroup> <Copy SourceFiles="@(_MergedPayloadFiles)" DestinationFiles="@(_MergedPayloadFiles->'$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\%(FileName)%(Extension)')" /> </Target> <Target Name="PrepareMergedTestPayloadDirectoryForWasm" Condition="'$(TargetsBrowser)' == 'true'" Outputs="%(_MergedWrapperMarker.FileName)" DependsOnTargets="DiscoverMergedTestWrappers"> <ItemGroup> <_MergedWrapperRunScript Include="@(_MergedWrapperMarker->'%(RootDir)%(Directory)AppBundle/RunTests.$(TestScriptExtension)')" /> </ItemGroup> <PropertyGroup> <_MergedWrapperDirectory>%(_MergedWrapperMarker.RootDir)%(Directory)</_MergedWrapperDirectory> <_MergedWrapperName>%(_MergedWrapperMarker.FileName)</_MergedWrapperName> <_MergedWrapperRunScriptRelative Condition="'%(_MergedWrapperRunScript.Identity)' != ''">$([System.IO.Path]::GetRelativePath('$(_MergedWrapperDirectory)AppBundle', %(_MergedWrapperRunScript.FullPath)))</_MergedWrapperRunScriptRelative> <_MergedWrapperRunScriptRelative Condition="'$(TestWrapperTargetsWindows)' != 'true'">./$(_MergedWrapperRunScriptRelative)</_MergedWrapperRunScriptRelative> </PropertyGroup> <ItemGroup> <_MergedPayloadGroups Include="$(_MergedWrapperName)" /> <_MergedPayloadFiles Include="$(_MergedWrapperDirectory)AppBundle/**" /> <_MergedPayloadFiles Update="@(_MergedPayloadFiles)"> <!-- Never use [MSBuild]::MakeRelative here! We have some files containing Unicode characters in their %(FullPath) and MakeRelative function calls Escape function internally that replaces all the Unicode characters with %<xx>. --> <FileRelativeToPayloadsRootDirectory>$([System.IO.Path]::GetRelativePath('$(_MergedWrapperDirectory)AppBundle', %(FullPath)))</FileRelativeToPayloadsRootDirectory> </_MergedPayloadFiles> </ItemGroup> <Copy SourceFiles="@(_MergedPayloadFiles)" DestinationFiles="@(_MergedPayloadFiles->'$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\%(FileRelativeToPayloadsRootDirectory)')" /> <WriteLinesToFile File="$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\HelixCommand.txt" Lines="$(_MergedWrapperRunScriptRelative)" /> </Target> <Target Name="PrepareMergedTestPayloadDirectoryForAppleMobile" Condition="'$(TargetsAppleMobile)' == 'true'" Outputs="%(_MergedWrapperMarker.FileName)" DependsOnTargets="DiscoverMergedTestWrappers"> <PropertyGroup> <_MergedWrapperDirectory>%(_MergedWrapperMarker.RootDir)%(Directory)</_MergedWrapperDirectory> <_MergedWrapperName>%(_MergedWrapperMarker.FileName)</_MergedWrapperName> </PropertyGroup> <PropertyGroup> <XCodeSdk Condition="'$(TargetsiOS)' == 'true'">iphone</XCodeSdk> <XCodeSdk Condition="'$(TargetsiOSSimulator)' == 'true'">iphonesimulator</XCodeSdk> <XCodeSdk Condition="'$(TargetstvOS)' == 'true'">appletvos</XCodeSdk> <XCodeSdk Condition="'$(TargetstvOSSimulator)' == 'true'">appletvsimulator</XCodeSdk> <XCodeSdk Condition="'$(TargetsMacCatalyst)' == 'true'">maccatalyst</XCodeSdk> </PropertyGroup> <ItemGroup> <_MergedPayloadGroups Include="$(_MergedWrapperName)" /> </ItemGroup> <ItemGroup> <_MergedPayloadFiles Include="$(_MergedWrapperDirectory)AppBundle/$(_MergedWrapperName)/$(Configuration)-$(XCodeSdk)/$(_MergedWrapperName).app/**" /> <_MergedPayloadFiles Update="@(_MergedPayloadFiles)"> <!-- Never use [MSBuild]::MakeRelative here! We have some files containing Unicode characters in their %(FullPath) and MakeRelative function calls Escape function internally that replaces all the Unicode characters with %<xx>. --> <FileRelativeToPayloadsRootDirectory>$([System.IO.Path]::GetRelativePath('$(_MergedWrapperDirectory)AppBundle/$(_MergedWrapperName)/$(Configuration)-$(XCodeSdk)', %(FullPath)))</FileRelativeToPayloadsRootDirectory> </_MergedPayloadFiles> </ItemGroup> <Copy SourceFiles="@(_MergedPayloadFiles)" DestinationFiles="@(_MergedPayloadFiles->'$(MergedPayloadsRootDirectory)\$(_MergedWrapperName)\%(FileRelativeToPayloadsRootDirectory)')" /> </Target> <Target Name="PrepareMergedTestPayloadDirectory" DependsOnTargets="DiscoverMergedTestWrappers;PrepareMergedTestPayloadDirectoryForDesktop;PrepareMergedTestPayloadDirectoryForAndroid;PrepareMergedTestPayloadDirectoryForWasm;PrepareMergedTestPayloadDirectoryForAppleMobile" /> <Target Name="ZipLegacyPayloadDirectory" AfterTargets="PrepareLegacyPayloadDirectories" Condition="'$(TargetHasHelixXHarnessSdkSupport)' == 'true'"> <ItemGroup> <LegacyPayloads Include="$([System.IO.Directory]::GetDirectories($(LegacyPayloadsRootDirectory)))" Condition="Exists('$(LegacyPayloadsRootDirectory)')" /> <LegacyPayloads Update="@(LegacyPayloads)"> <PayloadGroup>$([MSBuild]::MakeRelative($(LegacyPayloadsRootDirectory), %(FullPath)))</PayloadGroup> <PayloadDirectory>%(FullPath)</PayloadDirectory> </LegacyPayloads> </ItemGroup> <ZipDirectory SourceDirectory="@(LegacyPayloads->Metadata('PayloadDirectory'))" DestinationFile="$(LegacyPayloadsRootDirectory)\%(LegacyPayloads.PayloadGroup).zip" /> </Target> <Target Name="ZipMergedPayloadDirectory" AfterTargets="PrepareMergedTestPayloadDirectories" Condition="'$(TargetsBrowser)' == 'true'"> <ItemGroup> <MergedPayloads Include="$([System.IO.Directory]::GetDirectories($(MergedPayloadsRootDirectory)))" Condition="Exists('$(MergedPayloadsRootDirectory)')" /> <MergedPayloads Update="@(MergedPayloads)"> <PayloadGroup>$([MSBuild]::MakeRelative($(MergedPayloadsRootDirectory), %(FullPath)))</PayloadGroup> <PayloadDirectory>%(FullPath)</PayloadDirectory> </MergedPayloads> </ItemGroup> <ZipDirectory SourceDirectory="@(MergedPayloads->Metadata('PayloadDirectory'))" DestinationFile="$(MergedPayloadsRootDirectory)\%(MergedPayloads.PayloadGroup).zip" /> </Target> <PropertyGroup> <EnableAzurePipelinesReporter>$(PublishTestResults)</EnableAzurePipelinesReporter> <EnableAzurePipelinesReporter Condition=" '$(EnableAzurePipelinesReporter)' == '' ">false</EnableAzurePipelinesReporter> <FailOnMissionControlTestFailure>true</FailOnMissionControlTestFailure> <FailOnWorkItemFailure>true</FailOnWorkItemFailure> <HelixArchitecture>$(TargetArchitecture)</HelixArchitecture> <HelixConfiguration Condition=" '$(Scenario)' == 'normal' ">$(Configuration)</HelixConfiguration> <HelixConfiguration Condition=" '$(Scenario)' != 'normal' ">$(Configuration)-$(Scenario)</HelixConfiguration> <RunCrossGen Condition=" '$(RunCrossGen)' != 'true' ">false</RunCrossGen> <RunCrossGen2 Condition=" '$(RunCrossGen2)' != 'true' ">false</RunCrossGen2> <LongRunningGCTests Condition=" '$(LongRunningGCTests)' != 'true' ">false</LongRunningGCTests> <GcSimulatorTests Condition=" '$(GcSimulatorTests)' != 'true' ">false</GcSimulatorTests> <TestRunNamePrefix Condition="'$(RuntimeFlavorDisplayName)' != ''">$(RuntimeFlavorDisplayName) </TestRunNamePrefix> <TestRunNamePrefix Condition=" '$(RunCrossGen)' == 'true' ">R2R </TestRunNamePrefix> <TestRunNamePrefix Condition=" '$(RunCrossGen2)' == 'true' ">R2R-CG2 </TestRunNamePrefix> <TestRunNamePrefix Condition=" '$(Scenario)' == 'normal' ">$(TestRunNamePrefix)$(TargetOS) $(TargetArchitecture) $(Configuration) @ </TestRunNamePrefix> <TestRunNamePrefix Condition=" '$(Scenario)' != 'normal' ">$(TestRunNamePrefix)$(TargetOS) $(TargetArchitecture) $(Configuration) $(Scenario) @ </TestRunNamePrefix> <TimeoutPerTestInMilliseconds Condition=" '$(TimeoutPerTestInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestInMinutes)).TotalMilliseconds)</TimeoutPerTestInMilliseconds> <WaitForWorkItemCompletion>true</WaitForWorkItemCompletion> <_XUnitParallelMode>collections</_XUnitParallelMode> <_XUnitParallelMode Condition=" '$(TargetsAndroid)' == 'true' or '$(TargetsiOSSimulator)' == 'true'">none</_XUnitParallelMode> <_XUnitParallelMode Condition=" '$(LongRunningGCTests)' == 'true' ">none</_XUnitParallelMode> <_XUnitParallelMode Condition=" '$(GcSimulatorTests)' == 'true' ">none</_XUnitParallelMode> <XUnitRunnerArgs>-parallel $(_XUnitParallelMode) -nocolor -noshadow -xml testResults.xml</XUnitRunnerArgs> </PropertyGroup> <!-- WARNING: HelixPreCommand ItemGroup is intentionally minimal and should be kept that way. --> <ItemGroup Condition=" '$(TestWrapperTargetsWindows)' == 'true' "> <HelixPreCommand Include="taskkill.exe /f /im corerun.exe"/> <HelixPreCommand Include="set CORE_ROOT=%HELIX_CORRELATION_PAYLOAD%" /> <!-- Set _NT_SYMBOL_PATH so VM _ASSERTE() asserts can find the symbol files when doing stack walks --> <HelixPreCommand Include="set _NT_SYMBOL_PATH=%HELIX_CORRELATION_PAYLOAD%\PDB" /> <HelixPreCommand Include="set RunCrossGen2=1" Condition=" '$(RunCrossGen)' == 'true' " /> <HelixPreCommand Include="set RunCrossGen2=1" Condition=" '$(RunCrossGen2)' == 'true' " /> <HelixPreCommand Include="set CompositeBuildMode=1" Condition=" '$(CompositeBuildMode)' == 'true' " /> <HelixPreCommand Include="set RunningLongGCTests=1" Condition=" '$(LongRunningGCTests)' == 'true' " /> <HelixPreCommand Include="set RunningGCSimulatorTests=1" Condition=" '$(GcSimulatorTests)' == 'true' " /> <HelixPreCommand Include="set RunInUnloadableContext=1" Condition=" '$(RunInUnloadableContext)' == 'true' " /> <HelixPreCommand Include="set RunTieringTest=1" Condition=" '$(TieringTest)' == 'true' " /> <HelixPreCommand Include="set CLRCustomTestLauncher=%HELIX_CORRELATION_PAYLOAD%\runincontext.cmd" Condition=" '$(RunInUnloadableContext)' == 'true' " /> <HelixPreCommand Include="set CLRCustomTestLauncher=%HELIX_CORRELATION_PAYLOAD%\tieringtest.cmd" Condition=" '$(TieringTest)' == 'true' " /> <HelixPreCommand Include="set __TestEnv=%HELIX_WORKITEM_PAYLOAD%\$(TestEnvFileName)" /> <HelixPreCommand Include="set __TestTimeout=$(TimeoutPerTestInMilliseconds)" Condition=" '$(TimeoutPerTestInMilliseconds)' != '' " /> <HelixPreCommand Include="set __CollectDumps=1" /> <HelixPreCommand Include="set __CrashDumpFolder=%HELIX_DUMP_FOLDER%" /> <HelixPreCommand Include="type %__TestEnv%" /> </ItemGroup> <ItemGroup Condition=" '$(TestWrapperTargetsWindows)' == 'true' "> <HelixPostCommand Include="taskkill.exe /f /im corerun.exe"/> </ItemGroup> <ItemGroup Condition=" '$(TestWrapperTargetsWindows)' != 'true' "> <HelixPreCommand Include="export CORE_ROOT=$HELIX_CORRELATION_PAYLOAD" /> <HelixPreCommand Include="export RunCrossGen2=1" Condition=" '$(RunCrossGen)' == 'true' " /> <HelixPreCommand Include="export RunCrossGen2=1" Condition=" '$(RunCrossGen2)' == 'true' " /> <HelixPreCommand Include="export CompositeBuildMode=1" Condition=" '$(CompositeBuildMode)' == 'true' " /> <HelixPreCommand Include="export RunningLongGCTests=1" Condition=" '$(LongRunningGCTests)' == 'true' " /> <HelixPreCommand Include="export RunningGCSimulatorTests=1" Condition=" '$(GcSimulatorTests)' == 'true' " /> <HelixPreCommand Include="export RunInUnloadableContext=1" Condition=" '$(RunInUnloadableContext)' == 'true' " /> <HelixPreCommand Include="export RunTieringTest=1" Condition=" '$(TieringTest)' == 'true' " /> <HelixPreCommand Include="export CLRCustomTestLauncher=$HELIX_CORRELATION_PAYLOAD/runincontext.sh" Condition=" '$(RunInUnloadableContext)' == 'true' " /> <HelixPreCommand Include="export CLRCustomTestLauncher=$HELIX_CORRELATION_PAYLOAD/tieringtest.sh" Condition=" '$(TieringTest)' == 'true' " /> <HelixPreCommand Include="export __TestEnv=$HELIX_WORKITEM_PAYLOAD/$(TestEnvFileName)" /> <HelixPreCommand Include="export __TestTimeout=$(TimeoutPerTestInMilliseconds)" Condition=" '$(TimeoutPerTestInMilliseconds)' != '' " /> <HelixPreCommand Include="export __CollectDumps=1" /> <HelixPreCommand Include="export __CrashDumpFolder=$HELIX_DUMP_FOLDER" /> <HelixPreCommand Include="cat $__TestEnv" /> </ItemGroup> <PropertyGroup> <HelixPreCommands>@(HelixPreCommand)</HelixPreCommands> <HelixPostCommands>@(HelixPostCommand)</HelixPostCommands> </PropertyGroup> <PropertyGroup Condition=" '$(TestWrapperTargetsWindows)' == 'true' "> <!-- When the target has XHarness support in the Helix SDK, the script runs in a powershell context. Otherwise it runs in a Batch context. --> <XUnitRunnerDll Condition="'$(TargetHasHelixXHarnessSdkSupport)' == 'true'">$Env:CORE_ROOT\xunit\xunit.console.dll</XUnitRunnerDll> <XUnitRunnerDll Condition="'$(TargetHasHelixXHarnessSdkSupport)' != 'true'">%CORE_ROOT%\xunit\xunit.console.dll</XUnitRunnerDll> </PropertyGroup> <PropertyGroup Condition=" '$(TestWrapperTargetsWindows)' != 'true' "> <XUnitRunnerDll>$CORE_ROOT/xunit/xunit.console.dll</XUnitRunnerDll> </PropertyGroup> <ItemGroup Condition=" '$(UsesHelixSdk)' == 'true' "> <HelixCorrelationPayload Include="$(CoreRootDirectory)" /> <LegacyPayloads Include="$([System.IO.Directory]::GetDirectories($(LegacyPayloadsRootDirectory)))" Condition="Exists('$(LegacyPayloadsRootDirectory)')" /> <LegacyPayloads Update="@(LegacyPayloads)"> <PayloadGroup>$([MSBuild]::MakeRelative($(LegacyPayloadsRootDirectory), %(FullPath)))</PayloadGroup> <PayloadDirectory>%(FullPath)</PayloadDirectory> <XUnitWrapperDlls>$([System.String]::Join(' ', $([System.IO.Directory]::GetFiles(%(FullPath), '*.XUnitWrapper.dll', SearchOption.AllDirectories))).Replace($([MSBuild]::EnsureTrailingSlash(%(FullPath))),''))</XUnitWrapperDlls> </LegacyPayloads> <LegacyPayloads Update="@(LegacyPayloads)"> <TestGroup>%(PayloadGroup)</TestGroup> <!-- When Payload contains more than one *.XUnitWrapper.dll TestGroup should not be specified. --> <TestGroup Condition=" $([MSBuild]::ValueOrDefault(%(XUnitWrapperDlls), '').IndexOf('.XUnitWrapper.dll')) != $([MSBuild]::ValueOrDefault(%(XUnitWrapperDlls), '').LastIndexOf('.XUnitWrapper.dll')) "></TestGroup> <PayloadZipFile>$(LegacyPayloadsRootDirectory)\%(PayloadGroup).zip</PayloadZipFile> </LegacyPayloads> </ItemGroup> <ItemGroup> <MergedPayloads Include="$([System.IO.Directory]::GetDirectories($(MergedPayloadsRootDirectory)))" Condition="Exists('$(MergedPayloadsRootDirectory)')" /> <MergedPayloads Update="@(MergedPayloads)"> <PayloadDirectory>%(FullPath)</PayloadDirectory> </MergedPayloads> </ItemGroup> <ItemGroup Condition="'$(TargetsMobile)' != 'true'"> <MergedPayloads Update="@(MergedPayloads)"> <PayloadHelixCommandFile>$(MergedPayloadsRootDirectory)%(FileName)%(Extension)\HelixCommand.txt</PayloadHelixCommandFile> <MergedTestHelixCommand>$([System.IO.File]::ReadAllText('%(PayloadHelixCommandFile)'))</MergedTestHelixCommand> <PayloadGroup>$([System.IO.Path]::GetDirectoryName('%(MergedTestHelixCommand)').Replace('/', '-').Replace('\', '-'))</PayloadGroup> <PayloadZipFile>$(MergedPayloadsRootDirectory)%(PayloadGroup).zip</PayloadZipFile> </MergedPayloads> </ItemGroup> <ItemGroup Condition="'$(TargetsBrowser)' == 'true'"> <MergedPayloads Update="@(MergedPayloads)"> <PayloadHelixCommandFile>$(MergedPayloadsRootDirectory)%(FileName)%(Extension)\HelixCommand.txt</PayloadHelixCommandFile> <MergedTestHelixCommand>$([System.IO.File]::ReadAllText('%(PayloadHelixCommandFile)'))</MergedTestHelixCommand> <PayloadGroup>%(FileName)%(Extension)</PayloadGroup> <PayloadZipFile>$(MergedPayloadsRootDirectory)%(PayloadGroup).zip</PayloadZipFile> </MergedPayloads> </ItemGroup> <ItemGroup Condition="'$(TargetHasHelixXHarnessSdkSupport)' != 'true'"> <MergedPayloads Update="@(MergedPayloads)" Condition="'$(TestWrapperTargetsWindows)' != 'true'"> <MergedTestHelixCommand>chmod +x %(MergedPayloads.MergedTestHelixCommand)%0A%(MergedPayloads.MergedTestHelixCommand)</MergedTestHelixCommand> </MergedPayloads> </ItemGroup> <ItemGroup Condition="'$(TargetHasHelixXHarnessSdkSupport)' == 'true'"> <MergedPayloads Update="@(MergedPayloads)"> <PayloadGroup>%(FileName)%(Extension)</PayloadGroup> <ApkPath>$(MergedPayloadsRootDirectory)%(FileName)%(Extension)/%(FileName)%(Extension).apk</ApkPath> <AppBundlePath>$(MergedPayloadsRootDirectory)%(FileName)%(Extension)/%(FileName)%(Extension).app</AppBundlePath> </MergedPayloads> </ItemGroup> <ItemGroup> <HelixWorkItem Include="@(LegacyPayloads->Metadata('PayloadGroup'))" Condition="'$(TargetHasHelixXHarnessSdkSupport)' != 'true'"> <PayloadDirectory>%(PayloadDirectory)</PayloadDirectory> <Command>dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs)</Command> <Command Condition=" '%(TestGroup)' != '' ">dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs) -trait TestGroup=%(TestGroup)</Command> <Timeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</Timeout> </HelixWorkItem> <HelixWorkItem Include="@(MergedPayloads->Metadata('PayloadGroup'))" Condition="'$(TargetHasHelixXHarnessSdkSupport)' != 'true'"> <PayloadDirectory>%(PayloadDirectory)</PayloadDirectory> <Command>%(MergedTestHelixCommand)</Command> <Timeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</Timeout> </HelixWorkItem> <XHarnessApkToTest Include="@(LegacyPayloads->Metadata('PayloadZipFile'))" Condition="'$(TargetsAndroid)' == 'true'"> <TestTimeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</TestTimeout> <CustomCommands>dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs)</CustomCommands> <CustomCommands Condition=" '%(TestGroup)' != '' ">dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs) -trait TestGroup=%(TestGroup)</CustomCommands> </XHarnessApkToTest> <XHarnessApkToTest Include="@(MergedPayloads->Metadata('PayloadGroup'))" Condition="'$(TargetsAndroid)' == 'true'"> <AndroidPackageName>net.dot.%(PayloadGroup)</AndroidPackageName> <AndroidInstrumentationName>net.dot.MonoRunner</AndroidInstrumentationName> <TestTimeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</TestTimeout> </XHarnessApkToTest> <XHarnessAppBundleToTest Include="@(LegacyPayloads->Metadata('PayloadZipFile'))" Condition="'$(TargetsAppleMobile)' == 'true'"> <TestTarget Condition="'$(TargetArchitecture)' == 'arm64'">ios-simulator-64</TestTarget> <TestTarget Condition="'$(TargetArchitecture)' == 'x64'">ios-simulator-64</TestTarget> <TestTimeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</TestTimeout> <CustomCommands>dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs)</CustomCommands> <CustomCommands Condition=" '%(TestGroup)' != '' ">dotnet $(XUnitRunnerDll) %(XUnitWrapperDlls) $(XUnitRunnerArgs) -trait TestGroup=%(TestGroup)</CustomCommands> </XHarnessAppBundleToTest> <XHarnessAppBundleToTest Include="@(MergedPayloads->Metadata('PayloadGroup'))" Condition="'$(TargetsAppleMobile)' == 'true'"> <TestTarget Condition="'$(TargetArchitecture)' == 'arm64'">ios-simulator-64</TestTarget> <TestTarget Condition="'$(TargetArchitecture)' == 'x64'">ios-simulator-64</TestTarget> <TestTimeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</TestTimeout> </XHarnessAppBundleToTest> <HelixWorkItem Condition="'$(PALTestsDir)' != '' and '$(TestWrapperTargetsWindows)' != 'true'" Include="PALTests"> <PayloadArchive>$(LegacyPayloadsRootDirectory)paltests.tar.gz</PayloadArchive> <Command>./runpaltestshelix.sh</Command> <Timeout Condition=" '$(TimeoutPerTestCollectionInMinutes)' != '' ">$([System.TimeSpan]::FromMinutes($(TimeoutPerTestCollectionInMinutes)))</Timeout> </HelixWorkItem> </ItemGroup> <Import Sdk="Microsoft.DotNet.Helix.Sdk" Project="Sdk.targets" Condition=" '$(UsesHelixSdk)' == 'true' " /> <Import Sdk="Microsoft.Build.NoTargets" Project="Sdk.targets" Condition=" '$(UsesHelixSdk)' != 'true' " /> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/jit64/gc/misc/struct4_5.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="struct4_5.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="struct4_5.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Ecma/EcmaModifiedTypeProvider.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.TypeLoading.Ecma { // // A special purpose ISignatureTypeProvider for the GetCustomModifiers() api. Unlike the normal one, this one produces RoModifiedTypes // when custom modifiers are present. // internal sealed class EcmaModifiedTypeProvider : EcmaWrappedTypeProvider { internal EcmaModifiedTypeProvider(EcmaModule module) : base(module) { } public sealed override RoType GetModifiedType(RoType modifier, RoType unmodifiedType, bool isRequired) => new RoModifiedType(modifier.SkipTypeWrappers(), unmodifiedType, isRequired); public sealed override RoType GetPinnedType(RoType elementType) => elementType; } }
// 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.TypeLoading.Ecma { // // A special purpose ISignatureTypeProvider for the GetCustomModifiers() api. Unlike the normal one, this one produces RoModifiedTypes // when custom modifiers are present. // internal sealed class EcmaModifiedTypeProvider : EcmaWrappedTypeProvider { internal EcmaModifiedTypeProvider(EcmaModule module) : base(module) { } public sealed override RoType GetModifiedType(RoType modifier, RoType unmodifiedType, bool isRequired) => new RoModifiedType(modifier.SkipTypeWrappers(), unmodifiedType, isRequired); public sealed override RoType GetPinnedType(RoType elementType) => elementType; } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M01/b11878/b11878.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="test_07.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="test_07.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ZipLow.Vector128.UInt64.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 ZipLow_Vector128_UInt64() { var test = new SimpleBinaryOpTest__ZipLow_Vector128_UInt64(); 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__ZipLow_Vector128_UInt64 { 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(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); 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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1; public Vector128<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ZipLow_Vector128_UInt64 testClass) { var result = AdvSimd.Arm64.ZipLow(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ZipLow_Vector128_UInt64 testClass) { fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(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<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector128<UInt64> _clsVar2; private Vector128<UInt64> _fld1; private Vector128<UInt64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ZipLow_Vector128_UInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public SimpleBinaryOpTest__ZipLow_Vector128_UInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt64[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.ZipLow( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipLow), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(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.ZipLow), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ZipLow( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(pClsVar1)), AdvSimd.LoadVector128((UInt64*)(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<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.ZipLow(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((UInt64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.ZipLow(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ZipLow_Vector128_UInt64(); var result = AdvSimd.Arm64.ZipLow(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__ZipLow_Vector128_UInt64(); fixed (Vector128<UInt64>* pFld1 = &test._fld1) fixed (Vector128<UInt64>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ZipLow(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ZipLow(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(&test._fld1)), AdvSimd.LoadVector128((UInt64*)(&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<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; int index = 0; int half = RetElementCount / 2; for (var i = 0; i < RetElementCount; i+=2, index++) { if (result[i] != left[index] || result[i+1] != right[index]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ZipLow)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {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 ZipLow_Vector128_UInt64() { var test = new SimpleBinaryOpTest__ZipLow_Vector128_UInt64(); 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__ZipLow_Vector128_UInt64 { 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(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); 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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1; public Vector128<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ZipLow_Vector128_UInt64 testClass) { var result = AdvSimd.Arm64.ZipLow(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ZipLow_Vector128_UInt64 testClass) { fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(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<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector128<UInt64> _clsVar2; private Vector128<UInt64> _fld1; private Vector128<UInt64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ZipLow_Vector128_UInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); } public SimpleBinaryOpTest__ZipLow_Vector128_UInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt64[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.ZipLow( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ZipLow), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(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.ZipLow), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ZipLow( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(pClsVar1)), AdvSimd.LoadVector128((UInt64*)(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<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.ZipLow(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((UInt64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.ZipLow(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ZipLow_Vector128_UInt64(); var result = AdvSimd.Arm64.ZipLow(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__ZipLow_Vector128_UInt64(); fixed (Vector128<UInt64>* pFld1 = &test._fld1) fixed (Vector128<UInt64>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ZipLow(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector128<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(pFld1)), AdvSimd.LoadVector128((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ZipLow(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ZipLow( AdvSimd.LoadVector128((UInt64*)(&test._fld1)), AdvSimd.LoadVector128((UInt64*)(&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<UInt64> op1, Vector128<UInt64> op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; int index = 0; int half = RetElementCount / 2; for (var i = 0; i < RetElementCount; i+=2, index++) { if (result[i] != left[index] || result[i+1] != right[index]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ZipLow)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {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,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/Loader/classloader/regressions/vsw529206/moduleCctorThrow.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Library</OutputType> <CLRTestKind>BuildOnly</CLRTestKind> </PropertyGroup> <ItemGroup> <Compile Include="moduleCctorThrow.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Library</OutputType> <CLRTestKind>BuildOnly</CLRTestKind> </PropertyGroup> <ItemGroup> <Compile Include="moduleCctorThrow.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.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; using System.Net.Http.Headers; using System.Net.Quic; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Net.Http.QPack; using System.Runtime.ExceptionServices; namespace System.Net.Http { [SupportedOSPlatform("windows")] [SupportedOSPlatform("linux")] [SupportedOSPlatform("macos")] internal sealed class Http3RequestStream : IHttpStreamHeadersHandler, IAsyncDisposable, IDisposable { private readonly HttpRequestMessage _request; private Http3Connection _connection; private long _streamId = -1; // A stream does not have an ID until the first I/O against it. This gets set almost immediately following construction. private QuicStream _stream; private ArrayBuffer _sendBuffer; private readonly ReadOnlyMemory<byte>[] _gatheredSendBuffer = new ReadOnlyMemory<byte>[2]; private ArrayBuffer _recvBuffer; private TaskCompletionSource<bool>? _expect100ContinueCompletionSource; // True indicates we should send content (e.g. received 100 Continue). private bool _disposed; private CancellationTokenSource? _goawayCancellationSource; private CancellationToken _goawayCancellationToken; private CancellationTokenSource? _sendContentCts; // Allocated when we receive a :status header. private HttpResponseMessage? _response; // Header decoding. private QPackDecoder _headerDecoder; private HeaderState _headerState; private long _headerBudgetRemaining; /// <summary>Reusable array used to get the values for each header being written to the wire.</summary> private string[] _headerValues = Array.Empty<string>(); /// <summary>Any trailing headers.</summary> private List<(HeaderDescriptor name, string value)>? _trailingHeaders; // When reading response content, keep track of the number of bytes left in the current data frame. private long _responseDataPayloadRemaining; // When our request content has a precomputed length, it is sent over a single DATA frame. // Keep track of how much is remaining in that frame. private long _requestContentLengthRemaining; // For the precomputed length case, we need to add the DATA framing for the first write only. private bool _singleDataFrameWritten; public long StreamId { get => Volatile.Read(ref _streamId); set => Volatile.Write(ref _streamId, value); } public Http3RequestStream(HttpRequestMessage request, Http3Connection connection, QuicStream stream) { _request = request; _connection = connection; _stream = stream; _sendBuffer = new ArrayBuffer(initialSize: 64, usePool: true); _recvBuffer = new ArrayBuffer(initialSize: 64, usePool: true); _headerBudgetRemaining = connection.Pool.Settings._maxResponseHeadersLength * 1024L; // _maxResponseHeadersLength is in KiB. _headerDecoder = new QPackDecoder(maxHeadersLength: (int)Math.Min(int.MaxValue, _headerBudgetRemaining)); _goawayCancellationSource = new CancellationTokenSource(); _goawayCancellationToken = _goawayCancellationSource.Token; } public void Dispose() { if (!_disposed) { _disposed = true; AbortStream(); _stream.Dispose(); DisposeSyncHelper(); } } public async ValueTask DisposeAsync() { if (!_disposed) { _disposed = true; AbortStream(); await _stream.DisposeAsync().ConfigureAwait(false); DisposeSyncHelper(); } } private void DisposeSyncHelper() { _connection.RemoveStream(_stream); _sendBuffer.Dispose(); _recvBuffer.Dispose(); // Dispose() might be called concurrently with GoAway(), we need to make sure to not Dispose/Cancel the CTS concurrently. Interlocked.Exchange(ref _goawayCancellationSource, null)?.Dispose(); } public void GoAway() { // Dispose() might be called concurrently with GoAway(), we need to make sure to not Dispose/Cancel the CTS concurrently. using CancellationTokenSource? cts = Interlocked.Exchange(ref _goawayCancellationSource, null); cts?.Cancel(); } public async Task<HttpResponseMessage> SendAsync(CancellationToken cancellationToken) { // If true, dispose the stream upon return. Will be set to false if we're duplex or returning content. bool disposeSelf = true; // Link the input token with _resetCancellationTokenSource, so cancellation will trigger on GoAway() or Abort(). using CancellationTokenSource requestCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _goawayCancellationToken); CancellationTokenRegistration sendContentCancellationRegistration = default; try { BufferHeaders(_request); // If using Expect 100 Continue, setup a TCS to wait to send content until we get a response. if (_request.HasHeaders && _request.Headers.ExpectContinue == true) { _expect100ContinueCompletionSource = new TaskCompletionSource<bool>(); } if (_expect100ContinueCompletionSource != null || _request.Content == null) { // Ideally, headers will be sent out in a gathered write inside of SendContentAsync(). // If we don't have content, or we are doing Expect 100 Continue, then we can't rely on // this and must send our headers immediately. // End the stream writing if there's no content to send, do it as part of the write so that the FIN flag isn't send in an empty QUIC frame. // Note that there's no need to call Shutdown separately since the FIN flag in the last write is the same thing. await FlushSendBufferAsync(endStream: _request.Content == null, requestCancellationSource.Token).ConfigureAwait(false); } Task sendContentTask; if (_request.Content != null) { // If using duplex content, the content will continue sending after this method completes. // So, only observe the cancellation token during this method. CancellationToken sendContentCancellationToken; if (requestCancellationSource.Token.CanBeCanceled) { _sendContentCts = new CancellationTokenSource(); sendContentCancellationToken = _sendContentCts.Token; sendContentCancellationRegistration = requestCancellationSource.Token.UnsafeRegister( static s => ((CancellationTokenSource)s!).Cancel(), _sendContentCts); } else { sendContentCancellationToken = default; } sendContentTask = SendContentAsync(_request.Content!, sendContentCancellationToken); } else { sendContentTask = Task.CompletedTask; } // In parallel, send content and read response. // Depending on Expect 100 Continue usage, one will depend on the other making progress. Task readResponseTask = ReadResponseAsync(requestCancellationSource.Token); bool sendContentObserved = false; // If we're not doing duplex, wait for content to finish sending here. // If we are doing duplex and have the unlikely event that it completes here, observe the result. // See Http2Connection.SendAsync for a full comment on this logic -- it is identical behavior. if (sendContentTask.IsCompleted || _request.Content?.AllowDuplex != true || await Task.WhenAny(sendContentTask, readResponseTask).ConfigureAwait(false) == sendContentTask || sendContentTask.IsCompleted) { try { await sendContentTask.ConfigureAwait(false); sendContentObserved = true; } catch { // Exceptions will be bubbled up from sendContentTask here, // which means the result of readResponseTask won't be observed directly: // Do a background await to log any exceptions. _connection.LogExceptions(readResponseTask); throw; } } else { // Duplex is being used, so we can't wait for content to finish sending. // Do a background await to log any exceptions. _connection.LogExceptions(sendContentTask); } // Wait for the response headers to be read. await readResponseTask.ConfigureAwait(false); // Now that we've received the response, we no longer need to observe GOAWAY. // Use an atomic exchange to avoid a race to Cancel()/Dispose(). Interlocked.Exchange(ref _goawayCancellationSource, null)?.Dispose(); Debug.Assert(_response != null && _response.Content != null); // Set our content stream. var responseContent = (HttpConnectionResponseContent)_response.Content; // If we have received Content-Length: 0 and have completed sending content (which may not be the case if duplex), // we can close our Http3RequestStream immediately and return a singleton empty content stream. Otherwise, we // need to return a Http3ReadStream which will be responsible for disposing the Http3RequestStream. bool useEmptyResponseContent = responseContent.Headers.ContentLength == 0 && sendContentObserved; if (useEmptyResponseContent) { // Drain the response frames to read any trailing headers. await DrainContentLength0Frames(requestCancellationSource.Token).ConfigureAwait(false); responseContent.SetStream(EmptyReadStream.Instance); } else { // A read stream is required to finish up the request. responseContent.SetStream(new Http3ReadStream(this)); } if (NetEventSource.Log.IsEnabled()) Trace($"Received response: {_response}"); // Process any Set-Cookie headers. if (_connection.Pool.Settings._useCookies) { CookieHelper.ProcessReceivedCookies(_response, _connection.Pool.Settings._cookieContainer!); } // To avoid a circular reference (stream->response->content->stream), null out the stream's response. HttpResponseMessage response = _response; _response = null; // If we're 100% done with the stream, dispose. disposeSelf = useEmptyResponseContent; return response; } catch (QuicStreamAbortedException ex) when (ex.ErrorCode == (long)Http3ErrorCode.VersionFallback) { // The server is requesting us fall back to an older HTTP version. throw new HttpRequestException(SR.net_http_retry_on_older_version, ex, RequestRetryType.RetryOnLowerHttpVersion); } catch (QuicStreamAbortedException ex) when (ex.ErrorCode == (long)Http3ErrorCode.RequestRejected) { // The server is rejecting the request without processing it, retry it on a different connection. throw new HttpRequestException(SR.net_http_request_aborted, ex, RequestRetryType.RetryOnConnectionFailure); } catch (QuicStreamAbortedException ex) { // Our stream was reset. Exception? abortException = _connection.AbortException; throw new HttpRequestException(SR.net_http_client_execution_error, abortException ?? ex); } catch (QuicConnectionAbortedException ex) { // Our connection was reset. Start shutting down the connection. Exception abortException = _connection.Abort(ex); throw new HttpRequestException(SR.net_http_client_execution_error, abortException); } // It is possible for user's Content code to throw an unexpected OperationCanceledException. catch (OperationCanceledException ex) when (ex.CancellationToken == requestCancellationSource.Token || ex.CancellationToken == _sendContentCts?.Token) { // We're either observing GOAWAY, or the cancellationToken parameter has been canceled. if (cancellationToken.IsCancellationRequested) { _stream.AbortWrite((long)Http3ErrorCode.RequestCancelled); throw new TaskCanceledException(ex.Message, ex, cancellationToken); } else { Debug.Assert(_goawayCancellationToken.IsCancellationRequested == true); throw new HttpRequestException(SR.net_http_request_aborted, ex, RequestRetryType.RetryOnConnectionFailure); } } catch (Http3ConnectionException ex) { // A connection-level protocol error has occurred on our stream. _connection.Abort(ex); throw new HttpRequestException(SR.net_http_client_execution_error, ex); } catch (Exception ex) { _stream.AbortWrite((long)Http3ErrorCode.InternalError); if (ex is HttpRequestException) { throw; } throw new HttpRequestException(SR.net_http_client_execution_error, ex); } finally { sendContentCancellationRegistration.Dispose(); if (disposeSelf) { await DisposeAsync().ConfigureAwait(false); } } } /// <summary> /// Waits for the response headers to be read, and handles (Expect 100 etc.) informational statuses. /// </summary> private async Task ReadResponseAsync(CancellationToken cancellationToken) { if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStart(); Debug.Assert(_response == null); do { _headerState = HeaderState.StatusHeader; (Http3FrameType? frameType, long payloadLength) = await ReadFrameEnvelopeAsync(cancellationToken).ConfigureAwait(false); if (frameType != Http3FrameType.Headers) { if (NetEventSource.Log.IsEnabled()) { Trace($"Expected HEADERS as first response frame; received {frameType}."); } throw new HttpRequestException(SR.net_http_invalid_response); } await ReadHeadersAsync(payloadLength, cancellationToken).ConfigureAwait(false); Debug.Assert(_response != null); } while ((int)_response.StatusCode < 200); _headerState = HeaderState.TrailingHeaders; if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStop(); } private async Task SendContentAsync(HttpContent content, CancellationToken cancellationToken) { // If we're using Expect 100 Continue, wait to send content // until we get a response back or until our timeout elapses. if (_expect100ContinueCompletionSource != null) { Timer? timer = null; try { if (_connection.Pool.Settings._expect100ContinueTimeout != Timeout.InfiniteTimeSpan) { timer = new Timer(static o => ((Http3RequestStream)o!)._expect100ContinueCompletionSource!.TrySetResult(true), this, _connection.Pool.Settings._expect100ContinueTimeout, Timeout.InfiniteTimeSpan); } if (!await _expect100ContinueCompletionSource.Task.ConfigureAwait(false)) { // We received an error response code, so the body should not be sent. return; } } finally { if (timer != null) { await timer.DisposeAsync().ConfigureAwait(false); } } } if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestContentStart(); // If we have a Content-Length, keep track of it so we don't over-send and so we can send in a single DATA frame. _requestContentLengthRemaining = content.Headers.ContentLength ?? -1; var writeStream = new Http3WriteStream(this); try { await content.CopyToAsync(writeStream, null, cancellationToken).ConfigureAwait(false); } finally { writeStream.Dispose(); } if (_requestContentLengthRemaining > 0) { // The number of bytes we actually sent doesn't match the advertised Content-Length long contentLength = content.Headers.ContentLength.GetValueOrDefault(); long sent = contentLength - _requestContentLengthRemaining; throw new HttpRequestException(SR.Format(SR.net_http_request_content_length_mismatch, sent, contentLength)); } // Set to 0 to recognize that the whole request body has been sent and therefore there's no need to abort write side in case of a premature disposal. _requestContentLengthRemaining = 0; if (_sendBuffer.ActiveLength != 0) { // Our initial send buffer, which has our headers, is normally sent out on the first write to the Http3WriteStream. // If we get here, it means the content didn't actually do any writing. Send out the headers now. // Also send the FIN flag, since this is the last write. No need to call Shutdown separately. await FlushSendBufferAsync(endStream: true, cancellationToken).ConfigureAwait(false); } else { _stream.Shutdown(); } if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestContentStop(writeStream.BytesWritten); } private async ValueTask WriteRequestContentAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { if (buffer.Length == 0) { return; } long remaining = _requestContentLengthRemaining; if (remaining != -1) { // This HttpContent had a precomputed length, and a DATA frame was written as part of the headers. We can write directly without framing. if (buffer.Length > _requestContentLengthRemaining) { throw new HttpRequestException(SR.net_http_content_write_larger_than_content_length); } _requestContentLengthRemaining -= buffer.Length; if (!_singleDataFrameWritten) { // Note we may not have sent headers yet; if so, _sendBuffer.ActiveLength will be > 0, and we will write them in a single write. // Because we have a Content-Length, we can write it in a single DATA frame. BufferFrameEnvelope(Http3FrameType.Data, remaining); _gatheredSendBuffer[0] = _sendBuffer.ActiveMemory; _gatheredSendBuffer[1] = buffer; await _stream.WriteAsync(_gatheredSendBuffer, cancellationToken).ConfigureAwait(false); _sendBuffer.Discard(_sendBuffer.ActiveLength); _singleDataFrameWritten = true; } else { // DATA frame already sent, send just the content buffer directly. await _stream.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); } } else { // Variable-length content: write both a DATA frame and buffer. (and headers, which will still be in _sendBuffer if this is the first content write) // It's up to the HttpContent to give us sufficiently large writes to avoid excessively small DATA frames. BufferFrameEnvelope(Http3FrameType.Data, buffer.Length); _gatheredSendBuffer[0] = _sendBuffer.ActiveMemory; _gatheredSendBuffer[1] = buffer; await _stream.WriteAsync(_gatheredSendBuffer, cancellationToken).ConfigureAwait(false); _sendBuffer.Discard(_sendBuffer.ActiveLength); } } private async ValueTask FlushSendBufferAsync(bool endStream, CancellationToken cancellationToken) { await _stream.WriteAsync(_sendBuffer.ActiveMemory, endStream, cancellationToken).ConfigureAwait(false); _sendBuffer.Discard(_sendBuffer.ActiveLength); await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); } private async ValueTask DrainContentLength0Frames(CancellationToken cancellationToken) { Http3FrameType? frameType; long payloadLength; while (true) { (frameType, payloadLength) = await ReadFrameEnvelopeAsync(cancellationToken).ConfigureAwait(false); switch (frameType) { case Http3FrameType.Headers: // Pick up any trailing headers. _trailingHeaders = new List<(HeaderDescriptor name, string value)>(); await ReadHeadersAsync(payloadLength, cancellationToken).ConfigureAwait(false); // Stop looping after a trailing header. // There may be extra frames after this one, but they would all be unknown extension // frames that can be safely ignored. Just stop reading here. // Note: this does leave us open to a bad server sending us an out of order DATA frame. goto case null; case null: // Done receiving: copy over trailing headers. CopyTrailersToResponseMessage(_response!); _responseDataPayloadRemaining = -1; // Set to -1 to indicate EOS. return; case Http3FrameType.Data: // The sum of data frames must equal content length. Because this method is only // called for a Content-Length of 0, anything other than 0 here would be an error. // Per spec, 0-length payload is allowed. if (payloadLength != 0) { if (NetEventSource.Log.IsEnabled()) { Trace("Response content exceeded Content-Length."); } throw new HttpRequestException(SR.net_http_invalid_response); } break; default: Debug.Fail($"Received unexpected frame type {frameType}."); return; } } } private void CopyTrailersToResponseMessage(HttpResponseMessage responseMessage) { if (_trailingHeaders?.Count > 0) { foreach ((HeaderDescriptor name, string value) in _trailingHeaders) { responseMessage.TrailingHeaders.TryAddWithoutValidation(name, value); } _trailingHeaders.Clear(); } } private void BufferHeaders(HttpRequestMessage request) { if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestHeadersStart(); // Reserve space for the header frame envelope. // The envelope needs to be written after headers are serialized, as we need to know the payload length first. const int PreHeadersReserveSpace = Http3Frame.MaximumEncodedFrameEnvelopeLength; // This should be the first write to our buffer. The trick of reserving space won't otherwise work. Debug.Assert(_sendBuffer.ActiveLength == 0); // Reserve space for header frame envelope. _sendBuffer.Commit(PreHeadersReserveSpace); // Add header block prefix. We aren't using dynamic table, so these are simple zeroes. // https://tools.ietf.org/html/draft-ietf-quic-qpack-11#section-4.5.1 _sendBuffer.EnsureAvailableSpace(2); _sendBuffer.AvailableSpan[0] = 0x00; // required insert count. _sendBuffer.AvailableSpan[1] = 0x00; // s + delta base. _sendBuffer.Commit(2); HttpMethod normalizedMethod = HttpMethod.Normalize(request.Method); BufferBytes(normalizedMethod.Http3EncodedBytes); BufferIndexedHeader(H3StaticTable.SchemeHttps); if (request.HasHeaders && request.Headers.Host != null) { BufferLiteralHeaderWithStaticNameReference(H3StaticTable.Authority, request.Headers.Host); } else { BufferBytes(_connection.Pool._http3EncodedAuthorityHostHeader); } Debug.Assert(request.RequestUri != null); string pathAndQuery = request.RequestUri.PathAndQuery; if (pathAndQuery == "/") { BufferIndexedHeader(H3StaticTable.PathSlash); } else { BufferLiteralHeaderWithStaticNameReference(H3StaticTable.PathSlash, pathAndQuery); } // The only way to reach H3 is to upgrade via an Alt-Svc header, so we can encode Alt-Used for every connection. BufferBytes(_connection.AltUsedEncodedHeaderBytes); if (request.HasHeaders) { // H3 does not support Transfer-Encoding: chunked. if (request.HasHeaders && request.Headers.TransferEncodingChunked == true) { request.Headers.TransferEncodingChunked = false; } BufferHeaderCollection(request.Headers); } if (_connection.Pool.Settings._useCookies) { string cookiesFromContainer = _connection.Pool.Settings._cookieContainer!.GetCookieHeader(request.RequestUri); if (cookiesFromContainer != string.Empty) { Encoding? valueEncoding = _connection.Pool.Settings._requestHeaderEncodingSelector?.Invoke(HttpKnownHeaderNames.Cookie, request); BufferLiteralHeaderWithStaticNameReference(H3StaticTable.Cookie, cookiesFromContainer, valueEncoding); } } if (request.Content == null) { if (normalizedMethod.MustHaveRequestBody) { BufferIndexedHeader(H3StaticTable.ContentLength0); } } else { BufferHeaderCollection(request.Content.Headers); } // Determine our header envelope size. // The reserved space was the maximum required; discard what wasn't used. int headersLength = _sendBuffer.ActiveLength - PreHeadersReserveSpace; int headersLengthEncodedSize = VariableLengthIntegerHelper.GetByteCount(headersLength); _sendBuffer.Discard(PreHeadersReserveSpace - headersLengthEncodedSize - 1); // Encode header type in first byte, and payload length in subsequent bytes. _sendBuffer.ActiveSpan[0] = (byte)Http3FrameType.Headers; int actualHeadersLengthEncodedSize = VariableLengthIntegerHelper.WriteInteger(_sendBuffer.ActiveSpan.Slice(1, headersLengthEncodedSize), headersLength); Debug.Assert(actualHeadersLengthEncodedSize == headersLengthEncodedSize); if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestHeadersStop(); } // TODO: special-case Content-Type for static table values values? private void BufferHeaderCollection(HttpHeaders headers) { HeaderEncodingSelector<HttpRequestMessage>? encodingSelector = _connection.Pool.Settings._requestHeaderEncodingSelector; foreach (HeaderEntry header in headers.GetEntries()) { int headerValuesCount = HttpHeaders.GetStoreValuesIntoStringArray(header.Key, header.Value, ref _headerValues); Debug.Assert(headerValuesCount > 0, "No values for header??"); ReadOnlySpan<string> headerValues = _headerValues.AsSpan(0, headerValuesCount); Encoding? valueEncoding = encodingSelector?.Invoke(header.Key.Name, _request); KnownHeader? knownHeader = header.Key.KnownHeader; if (knownHeader != null) { // The Host header is not sent for HTTP/3 because we send the ":authority" pseudo-header instead // (see pseudo-header handling below in WriteHeaders). // The Connection, Upgrade and ProxyConnection headers are also not supported in HTTP/3. if (knownHeader != KnownHeaders.Host && knownHeader != KnownHeaders.Connection && knownHeader != KnownHeaders.Upgrade && knownHeader != KnownHeaders.ProxyConnection) { if (knownHeader == KnownHeaders.TE) { // HTTP/2 allows only 'trailers' TE header. rfc7540 8.1.2.2 // HTTP/3 does not mention this one way or another; assume it has the same rule. foreach (string value in headerValues) { if (string.Equals(value, "trailers", StringComparison.OrdinalIgnoreCase)) { BufferLiteralHeaderWithoutNameReference("TE", value, valueEncoding); break; } } continue; } // For all other known headers, send them via their pre-encoded name and the associated value. BufferBytes(knownHeader.Http3EncodedName); string? separator = null; if (headerValues.Length > 1) { HttpHeaderParser? parser = header.Key.Parser; if (parser != null && parser.SupportsMultipleValues) { separator = parser.Separator; } else { separator = HttpHeaderParser.DefaultSeparator; } } BufferLiteralHeaderValues(headerValues, separator, valueEncoding); } } else { // The header is not known: fall back to just encoding the header name and value(s). BufferLiteralHeaderWithoutNameReference(header.Key.Name, headerValues, HttpHeaderParser.DefaultSeparator, valueEncoding); } } } private void BufferIndexedHeader(int index) { int bytesWritten; while (!QPackEncoder.EncodeStaticIndexedHeaderField(index, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderWithStaticNameReference(int nameIndex, string value, Encoding? valueEncoding = null) { int bytesWritten; while (!QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReference(nameIndex, value, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderWithoutNameReference(string name, ReadOnlySpan<string> values, string separator, Encoding? valueEncoding) { int bytesWritten; while (!QPackEncoder.EncodeLiteralHeaderFieldWithoutNameReference(name, values, separator, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderWithoutNameReference(string name, string value, Encoding? valueEncoding) { int bytesWritten; while (!QPackEncoder.EncodeLiteralHeaderFieldWithoutNameReference(name, value, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderValues(ReadOnlySpan<string> values, string? separator, Encoding? valueEncoding) { int bytesWritten; while (!QPackEncoder.EncodeValueString(values, separator, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferFrameEnvelope(Http3FrameType frameType, long payloadLength) { int bytesWritten; while (!Http3Frame.TryWriteFrameEnvelope(frameType, payloadLength, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferBytes(ReadOnlySpan<byte> span) { _sendBuffer.EnsureAvailableSpace(span.Length); span.CopyTo(_sendBuffer.AvailableSpan); _sendBuffer.Commit(span.Length); } private async ValueTask<(Http3FrameType? frameType, long payloadLength)> ReadFrameEnvelopeAsync(CancellationToken cancellationToken) { long frameType, payloadLength; int bytesRead; while (true) { while (!Http3Frame.TryReadIntegerPair(_recvBuffer.ActiveSpan, out frameType, out payloadLength, out bytesRead)) { _recvBuffer.EnsureAvailableSpace(VariableLengthIntegerHelper.MaximumEncodedLength * 2); bytesRead = await _stream.ReadAsync(_recvBuffer.AvailableMemory, cancellationToken).ConfigureAwait(false); if (bytesRead != 0) { _recvBuffer.Commit(bytesRead); } else if (_recvBuffer.ActiveLength == 0) { // End of stream. return (null, 0); } else { // Our buffer has partial frame data in it but not enough to complete the read: bail out. throw new HttpRequestException(SR.net_http_invalid_response_premature_eof); } } _recvBuffer.Discard(bytesRead); if (NetEventSource.Log.IsEnabled()) { Trace($"Received frame {frameType} of length {payloadLength}."); } switch ((Http3FrameType)frameType) { case Http3FrameType.Headers: case Http3FrameType.Data: return ((Http3FrameType)frameType, payloadLength); case Http3FrameType.Settings: // These frames should only be received on a control stream, not a response stream. case Http3FrameType.GoAway: case Http3FrameType.MaxPushId: case Http3FrameType.ReservedHttp2Priority: // These frames are explicitly reserved and must never be sent. case Http3FrameType.ReservedHttp2Ping: case Http3FrameType.ReservedHttp2WindowUpdate: case Http3FrameType.ReservedHttp2Continuation: throw new Http3ConnectionException(Http3ErrorCode.UnexpectedFrame); case Http3FrameType.PushPromise: case Http3FrameType.CancelPush: // Because we haven't sent any MAX_PUSH_ID frames, any of these push-related // frames that the server sends will have an out-of-range push ID. throw new Http3ConnectionException(Http3ErrorCode.IdError); default: // Unknown frame types should be skipped. await SkipUnknownPayloadAsync(payloadLength, cancellationToken).ConfigureAwait(false); break; } } } private async ValueTask ReadHeadersAsync(long headersLength, CancellationToken cancellationToken) { // TODO: this header budget is sent as SETTINGS_MAX_HEADER_LIST_SIZE, so it should not use frame payload but rather 32 bytes + uncompressed size per entry. // https://tools.ietf.org/html/draft-ietf-quic-http-24#section-4.1.1 if (headersLength > _headerBudgetRemaining) { _stream.AbortWrite((long)Http3ErrorCode.ExcessiveLoad); throw new HttpRequestException(SR.Format(SR.net_http_response_headers_exceeded_length, _connection.Pool.Settings._maxResponseHeadersLength * 1024L)); } _headerBudgetRemaining -= headersLength; while (headersLength != 0) { if (_recvBuffer.ActiveLength == 0) { _recvBuffer.EnsureAvailableSpace(1); int bytesRead = await _stream.ReadAsync(_recvBuffer.AvailableMemory, cancellationToken).ConfigureAwait(false); if (bytesRead != 0) { _recvBuffer.Commit(bytesRead); } else { if (NetEventSource.Log.IsEnabled()) Trace($"Server closed response stream before entire header payload could be read. {headersLength:N0} bytes remaining."); throw new HttpRequestException(SR.net_http_invalid_response_premature_eof); } } int processLength = (int)Math.Min(headersLength, _recvBuffer.ActiveLength); bool endHeaders = headersLength == processLength; _headerDecoder.Decode(_recvBuffer.ActiveSpan.Slice(0, processLength), endHeaders, this); _recvBuffer.Discard(processLength); headersLength -= processLength; } // Reset decoder state. Require because one decoder instance is reused to decode headers and trailers. _headerDecoder.Reset(); } private static ReadOnlySpan<byte> StatusHeaderNameBytes => new byte[] { (byte)'s', (byte)'t', (byte)'a', (byte)'t', (byte)'u', (byte)'s' }; void IHttpStreamHeadersHandler.OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { Debug.Assert(name.Length > 0); if (!HeaderDescriptor.TryGet(name, out HeaderDescriptor descriptor)) { // Invalid header name throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_header_name, Encoding.ASCII.GetString(name))); } OnHeader(staticIndex: null, descriptor, staticValue: default, literalValue: value); } void IHttpStreamHeadersHandler.OnStaticIndexedHeader(int index) { GetStaticQPackHeader(index, out HeaderDescriptor descriptor, out string? knownValue); OnHeader(index, descriptor, knownValue, literalValue: default); } void IHttpStreamHeadersHandler.OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value) { GetStaticQPackHeader(index, out HeaderDescriptor descriptor, knownValue: out _); OnHeader(index, descriptor, staticValue: null, literalValue: value); } void IHttpStreamHeadersHandler.OnDynamicIndexedHeader(int? index, ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { ((IHttpStreamHeadersHandler)this).OnHeader(name, value); } private void GetStaticQPackHeader(int index, out HeaderDescriptor descriptor, out string? knownValue) { if (!HeaderDescriptor.TryGetStaticQPackHeader(index, out descriptor, out knownValue)) { if (NetEventSource.Log.IsEnabled()) Trace($"Response contains invalid static header index '{index}'."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); } } /// <param name="staticIndex">The static index of the header, if any.</param> /// <param name="descriptor">A descriptor for either a known header or unknown header.</param> /// <param name="staticValue">The static indexed value, if any.</param> /// <param name="literalValue">The literal ASCII value, if any.</param> /// <remarks>One of <paramref name="staticValue"/> or <paramref name="literalValue"/> will be set.</remarks> private void OnHeader(int? staticIndex, HeaderDescriptor descriptor, string? staticValue, ReadOnlySpan<byte> literalValue) { if (descriptor.Name[0] == ':') { if (!descriptor.Equals(KnownHeaders.PseudoStatus)) { if (NetEventSource.Log.IsEnabled()) Trace($"Received unknown pseudo-header '{descriptor.Name}'."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); } if (_headerState != HeaderState.StatusHeader) { if (NetEventSource.Log.IsEnabled()) Trace("Received extra status header."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); } int statusCode; if (staticValue != null) // Indexed Header Field -- both name and value are taken from the table { statusCode = staticIndex switch { H3StaticTable.Status103 => 103, H3StaticTable.Status200 => 200, H3StaticTable.Status304 => 304, H3StaticTable.Status404 => 404, H3StaticTable.Status503 => 503, H3StaticTable.Status100 => 100, H3StaticTable.Status204 => 204, H3StaticTable.Status206 => 206, H3StaticTable.Status302 => 302, H3StaticTable.Status400 => 400, H3StaticTable.Status403 => 403, H3StaticTable.Status421 => 421, H3StaticTable.Status425 => 425, H3StaticTable.Status500 => 500, // We should never get here, at least while we only use static table. But we can still parse staticValue. _ => ParseStatusCode(staticIndex, staticValue) }; int ParseStatusCode(int? index, string value) { string message = $"Unexpected QPACK table reference for Status code: index={index} value=\'{value}\'"; Debug.Fail(message); if (NetEventSource.Log.IsEnabled()) Trace(message); // TODO: The parsing is not optimal, but I don't expect this line to be executed at all for now. return HttpConnectionBase.ParseStatusCode(Encoding.ASCII.GetBytes(value)); } } else // Literal Header Field With Name Reference -- only name is taken from the table { statusCode = HttpConnectionBase.ParseStatusCode(literalValue); } _response = new HttpResponseMessage() { Version = HttpVersion.Version30, RequestMessage = _request, Content = new HttpConnectionResponseContent(), StatusCode = (HttpStatusCode)statusCode }; if (statusCode < 200) { // Informational responses should not contain headers -- skip them. _headerState = HeaderState.SkipExpect100Headers; if (_response.StatusCode == HttpStatusCode.Continue && _expect100ContinueCompletionSource != null) { _expect100ContinueCompletionSource.TrySetResult(true); } } else { _headerState = HeaderState.ResponseHeaders; if (_expect100ContinueCompletionSource != null) { // If the final status code is >= 300, skip sending the body. bool shouldSendBody = (statusCode < 300); if (NetEventSource.Log.IsEnabled()) Trace($"Expecting 100 Continue but received final status {statusCode}."); _expect100ContinueCompletionSource.TrySetResult(shouldSendBody); } } } else if (_headerState == HeaderState.SkipExpect100Headers) { // Ignore any headers that came as part of an informational (i.e. 100 Continue) response. return; } else { string? headerValue = staticValue; if (headerValue is null) { Encoding? encoding = _connection.Pool.Settings._responseHeaderEncodingSelector?.Invoke(descriptor.Name, _request); headerValue = _connection.GetResponseHeaderValueWithCaching(descriptor, literalValue, encoding); } switch (_headerState) { case HeaderState.StatusHeader: if (NetEventSource.Log.IsEnabled()) Trace($"Received headers without :status."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); case HeaderState.ResponseHeaders when descriptor.HeaderType.HasFlag(HttpHeaderType.Content): _response!.Content!.Headers.TryAddWithoutValidation(descriptor, headerValue); break; case HeaderState.ResponseHeaders: _response!.Headers.TryAddWithoutValidation(descriptor.HeaderType.HasFlag(HttpHeaderType.Request) ? descriptor.AsCustomHeader() : descriptor, headerValue); break; case HeaderState.TrailingHeaders: _trailingHeaders!.Add((descriptor.HeaderType.HasFlag(HttpHeaderType.Request) ? descriptor.AsCustomHeader() : descriptor, headerValue)); break; default: Debug.Fail($"Unexpected {nameof(Http3RequestStream)}.{nameof(_headerState)} '{_headerState}'."); break; } } } void IHttpStreamHeadersHandler.OnHeadersComplete(bool endStream) { Debug.Fail($"This has no use in HTTP/3 and should never be called by {nameof(QPackDecoder)}."); } private async ValueTask SkipUnknownPayloadAsync(long payloadLength, CancellationToken cancellationToken) { while (payloadLength != 0) { if (_recvBuffer.ActiveLength == 0) { _recvBuffer.EnsureAvailableSpace(1); int bytesRead = await _stream.ReadAsync(_recvBuffer.AvailableMemory, cancellationToken).ConfigureAwait(false); if (bytesRead != 0) { _recvBuffer.Commit(bytesRead); } else { // Our buffer has partial frame data in it but not enough to complete the read: bail out. throw new Http3ConnectionException(Http3ErrorCode.FrameError); } } long readLength = Math.Min(payloadLength, _recvBuffer.ActiveLength); _recvBuffer.Discard((int)readLength); payloadLength -= readLength; } } private int ReadResponseContent(HttpResponseMessage response, Span<byte> buffer) { // Response headers should be done reading by the time this is called. _response is nulled out as part of this. // Verify that this is being called in correct order. Debug.Assert(_response == null); try { int totalBytesRead = 0; do { // Sync over async here -- QUIC implementation does it per-I/O already; this is at least more coarse-grained. if (_responseDataPayloadRemaining <= 0 && !ReadNextDataFrameAsync(response, CancellationToken.None).AsTask().GetAwaiter().GetResult()) { // End of stream. break; } if (_recvBuffer.ActiveLength != 0) { // Some of the payload is in our receive buffer, so copy it. int copyLen = (int)Math.Min(buffer.Length, Math.Min(_responseDataPayloadRemaining, _recvBuffer.ActiveLength)); _recvBuffer.ActiveSpan.Slice(0, copyLen).CopyTo(buffer); totalBytesRead += copyLen; _responseDataPayloadRemaining -= copyLen; _recvBuffer.Discard(copyLen); buffer = buffer.Slice(copyLen); // Stop, if we've reached the end of a data frame and start of the next data frame is not buffered yet // Waiting for the next data frame may cause a hang, e.g. in echo scenario // TODO: this is inefficient if data is already available in transport if (_responseDataPayloadRemaining == 0 && _recvBuffer.ActiveLength == 0) { break; } } else { // Receive buffer is empty -- bypass it and read directly into user's buffer. int copyLen = (int)Math.Min(buffer.Length, _responseDataPayloadRemaining); int bytesRead = _stream.Read(buffer.Slice(0, copyLen)); if (bytesRead == 0 && buffer.Length != 0) { throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, _responseDataPayloadRemaining)); } totalBytesRead += bytesRead; _responseDataPayloadRemaining -= bytesRead; buffer = buffer.Slice(bytesRead); // Stop, even if we are in the middle of a data frame. Waiting for the next data may cause a hang // TODO: this is inefficient if data is already available in transport break; } } while (buffer.Length != 0); return totalBytesRead; } catch (Exception ex) { HandleReadResponseContentException(ex, CancellationToken.None); return 0; // never reached. } } private async ValueTask<int> ReadResponseContentAsync(HttpResponseMessage response, Memory<byte> buffer, CancellationToken cancellationToken) { // Response headers should be done reading by the time this is called. _response is nulled out as part of this. // Verify that this is being called in correct order. Debug.Assert(_response == null); try { int totalBytesRead = 0; do { if (_responseDataPayloadRemaining <= 0 && !await ReadNextDataFrameAsync(response, cancellationToken).ConfigureAwait(false)) { // End of stream. break; } if (_recvBuffer.ActiveLength != 0) { // Some of the payload is in our receive buffer, so copy it. int copyLen = (int)Math.Min(buffer.Length, Math.Min(_responseDataPayloadRemaining, _recvBuffer.ActiveLength)); _recvBuffer.ActiveSpan.Slice(0, copyLen).CopyTo(buffer.Span); totalBytesRead += copyLen; _responseDataPayloadRemaining -= copyLen; _recvBuffer.Discard(copyLen); buffer = buffer.Slice(copyLen); // Stop, if we've reached the end of a data frame and start of the next data frame is not buffered yet // Waiting for the next data frame may cause a hang, e.g. in echo scenario // TODO: this is inefficient if data is already available in transport if (_responseDataPayloadRemaining == 0 && _recvBuffer.ActiveLength == 0) { break; } } else { // Receive buffer is empty -- bypass it and read directly into user's buffer. int copyLen = (int)Math.Min(buffer.Length, _responseDataPayloadRemaining); int bytesRead = await _stream.ReadAsync(buffer.Slice(0, copyLen), cancellationToken).ConfigureAwait(false); if (bytesRead == 0 && buffer.Length != 0) { throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, _responseDataPayloadRemaining)); } totalBytesRead += bytesRead; _responseDataPayloadRemaining -= bytesRead; buffer = buffer.Slice(bytesRead); // Stop, even if we are in the middle of a data frame. Waiting for the next data may cause a hang // TODO: this is inefficient if data is already available in transport break; } } while (buffer.Length != 0); return totalBytesRead; } catch (Exception ex) { HandleReadResponseContentException(ex, cancellationToken); return 0; // never reached. } } private void HandleReadResponseContentException(Exception ex, CancellationToken cancellationToken) { switch (ex) { // Peer aborted the stream case QuicStreamAbortedException _: // User aborted the stream case QuicOperationAbortedException _: throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, ex)); case QuicConnectionAbortedException _: // Our connection was reset. Start aborting the connection. Exception abortException = _connection.Abort(ex); throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, abortException)); case Http3ConnectionException _: // A connection-level protocol error has occurred on our stream. _connection.Abort(ex); throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, ex)); case OperationCanceledException oce when oce.CancellationToken == cancellationToken: _stream.AbortRead((long)Http3ErrorCode.RequestCancelled); ExceptionDispatchInfo.Throw(ex); // Rethrow. return; // Never reached. default: _stream.AbortRead((long)Http3ErrorCode.InternalError); throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, ex)); } } private async ValueTask<bool> ReadNextDataFrameAsync(HttpResponseMessage response, CancellationToken cancellationToken) { if (_responseDataPayloadRemaining == -1) { // EOS -- this branch will only be taken if user calls Read again after EOS. return false; } Http3FrameType? frameType; long payloadLength; while (true) { (frameType, payloadLength) = await ReadFrameEnvelopeAsync(cancellationToken).ConfigureAwait(false); switch (frameType) { case Http3FrameType.Data: // Ignore DATA frames with 0 length. if (payloadLength == 0) { continue; } _responseDataPayloadRemaining = payloadLength; return true; case Http3FrameType.Headers: // Read any trailing headers. _trailingHeaders = new List<(HeaderDescriptor name, string value)>(); await ReadHeadersAsync(payloadLength, cancellationToken).ConfigureAwait(false); // There may be more frames after this one, but they would all be unknown extension // frames that we are allowed to skip. Just close the stream early. // Note: if a server sends additional HEADERS or DATA frames at this point, it // would be a connection error -- not draining the stream means we won't catch this. goto case null; case null: // End of stream. CopyTrailersToResponseMessage(response); _responseDataPayloadRemaining = -1; // Set to -1 to indicate EOS. return false; } } } public void Trace(string message, [CallerMemberName] string? memberName = null) => _connection.Trace(StreamId, message, memberName); private void AbortStream() { // If the request body isn't completed, cancel it now. if (_requestContentLengthRemaining != 0) // 0 is used for the end of content writing, -1 is used for unknown Content-Length { _stream.AbortWrite((long)Http3ErrorCode.RequestCancelled); } // If the response body isn't completed, cancel it now. if (_responseDataPayloadRemaining != -1) // -1 is used for EOF, 0 for consumed DATA frame payload before the next read { _stream.AbortRead((long)Http3ErrorCode.RequestCancelled); } } // TODO: it may be possible for Http3RequestStream to implement Stream directly and avoid this allocation. private sealed class Http3ReadStream : HttpBaseStream { private Http3RequestStream? _stream; private HttpResponseMessage? _response; public override bool CanRead => _stream != null; public override bool CanWrite => false; public Http3ReadStream(Http3RequestStream stream) { _stream = stream; _response = stream._response; } ~Http3ReadStream() { Dispose(false); } protected override void Dispose(bool disposing) { Http3RequestStream? stream = Interlocked.Exchange(ref _stream, null); if (stream is null) { return; } if (disposing) { // This will remove the stream from the connection properly. stream.Dispose(); } else { // We shouldn't be using a managed instance here, but don't have much choice -- we // need to remove the stream from the connection's GOAWAY collection and properly abort. stream.AbortStream(); stream._connection.RemoveStream(stream._stream); stream._connection = null!; } _response = null; base.Dispose(disposing); } public override async ValueTask DisposeAsync() { Http3RequestStream? stream = Interlocked.Exchange(ref _stream, null); if (stream is null) { return; } await stream.DisposeAsync().ConfigureAwait(false); _response = null; await base.DisposeAsync().ConfigureAwait(false); } public override int Read(Span<byte> buffer) { Http3RequestStream? stream = _stream; if (stream is null) { throw new ObjectDisposedException(nameof(Http3RequestStream)); } Debug.Assert(_response != null); return stream.ReadResponseContent(_response, buffer); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) { Http3RequestStream? stream = _stream; if (stream is null) { return ValueTask.FromException<int>(new ObjectDisposedException(nameof(Http3RequestStream))); } Debug.Assert(_response != null); return stream.ReadResponseContentAsync(_response, buffer, cancellationToken); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { throw new NotSupportedException(); } } // TODO: it may be possible for Http3RequestStream to implement Stream directly and avoid this allocation. private sealed class Http3WriteStream : HttpBaseStream { private Http3RequestStream? _stream; public long BytesWritten { get; private set; } public override bool CanRead => false; public override bool CanWrite => _stream != null; public Http3WriteStream(Http3RequestStream stream) { _stream = stream; } protected override void Dispose(bool disposing) { _stream = null; base.Dispose(disposing); } public override int Read(Span<byte> buffer) { throw new NotSupportedException(); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) { throw new NotSupportedException(); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { BytesWritten += buffer.Length; Http3RequestStream? stream = _stream; if (stream is null) { return ValueTask.FromException(new ObjectDisposedException(nameof(Http3WriteStream))); } return stream.WriteRequestContentAsync(buffer, cancellationToken); } public override Task FlushAsync(CancellationToken cancellationToken) { Http3RequestStream? stream = _stream; if (stream is null) { return Task.FromException(new ObjectDisposedException(nameof(Http3WriteStream))); } return stream.FlushSendBufferAsync(endStream: false, cancellationToken).AsTask(); } } private enum HeaderState { StatusHeader, SkipExpect100Headers, ResponseHeaders, TrailingHeaders } } }
// 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; using System.Net.Http.Headers; using System.Net.Quic; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Net.Http.QPack; using System.Runtime.ExceptionServices; namespace System.Net.Http { [SupportedOSPlatform("windows")] [SupportedOSPlatform("linux")] [SupportedOSPlatform("macos")] internal sealed class Http3RequestStream : IHttpStreamHeadersHandler, IAsyncDisposable, IDisposable { private readonly HttpRequestMessage _request; private Http3Connection _connection; private long _streamId = -1; // A stream does not have an ID until the first I/O against it. This gets set almost immediately following construction. private QuicStream _stream; private ArrayBuffer _sendBuffer; private readonly ReadOnlyMemory<byte>[] _gatheredSendBuffer = new ReadOnlyMemory<byte>[2]; private ArrayBuffer _recvBuffer; private TaskCompletionSource<bool>? _expect100ContinueCompletionSource; // True indicates we should send content (e.g. received 100 Continue). private bool _disposed; private CancellationTokenSource? _goawayCancellationSource; private CancellationToken _goawayCancellationToken; private CancellationTokenSource? _sendContentCts; // Allocated when we receive a :status header. private HttpResponseMessage? _response; // Header decoding. private QPackDecoder _headerDecoder; private HeaderState _headerState; private long _headerBudgetRemaining; /// <summary>Reusable array used to get the values for each header being written to the wire.</summary> private string[] _headerValues = Array.Empty<string>(); /// <summary>Any trailing headers.</summary> private List<(HeaderDescriptor name, string value)>? _trailingHeaders; // When reading response content, keep track of the number of bytes left in the current data frame. private long _responseDataPayloadRemaining; // When our request content has a precomputed length, it is sent over a single DATA frame. // Keep track of how much is remaining in that frame. private long _requestContentLengthRemaining; // For the precomputed length case, we need to add the DATA framing for the first write only. private bool _singleDataFrameWritten; public long StreamId { get => Volatile.Read(ref _streamId); set => Volatile.Write(ref _streamId, value); } public Http3RequestStream(HttpRequestMessage request, Http3Connection connection, QuicStream stream) { _request = request; _connection = connection; _stream = stream; _sendBuffer = new ArrayBuffer(initialSize: 64, usePool: true); _recvBuffer = new ArrayBuffer(initialSize: 64, usePool: true); _headerBudgetRemaining = connection.Pool.Settings._maxResponseHeadersLength * 1024L; // _maxResponseHeadersLength is in KiB. _headerDecoder = new QPackDecoder(maxHeadersLength: (int)Math.Min(int.MaxValue, _headerBudgetRemaining)); _goawayCancellationSource = new CancellationTokenSource(); _goawayCancellationToken = _goawayCancellationSource.Token; } public void Dispose() { if (!_disposed) { _disposed = true; AbortStream(); _stream.Dispose(); DisposeSyncHelper(); } } public async ValueTask DisposeAsync() { if (!_disposed) { _disposed = true; AbortStream(); await _stream.DisposeAsync().ConfigureAwait(false); DisposeSyncHelper(); } } private void DisposeSyncHelper() { _connection.RemoveStream(_stream); _sendBuffer.Dispose(); _recvBuffer.Dispose(); // Dispose() might be called concurrently with GoAway(), we need to make sure to not Dispose/Cancel the CTS concurrently. Interlocked.Exchange(ref _goawayCancellationSource, null)?.Dispose(); } public void GoAway() { // Dispose() might be called concurrently with GoAway(), we need to make sure to not Dispose/Cancel the CTS concurrently. using CancellationTokenSource? cts = Interlocked.Exchange(ref _goawayCancellationSource, null); cts?.Cancel(); } public async Task<HttpResponseMessage> SendAsync(CancellationToken cancellationToken) { // If true, dispose the stream upon return. Will be set to false if we're duplex or returning content. bool disposeSelf = true; // Link the input token with _resetCancellationTokenSource, so cancellation will trigger on GoAway() or Abort(). using CancellationTokenSource requestCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _goawayCancellationToken); CancellationTokenRegistration sendContentCancellationRegistration = default; try { BufferHeaders(_request); // If using Expect 100 Continue, setup a TCS to wait to send content until we get a response. if (_request.HasHeaders && _request.Headers.ExpectContinue == true) { _expect100ContinueCompletionSource = new TaskCompletionSource<bool>(); } if (_expect100ContinueCompletionSource != null || _request.Content == null) { // Ideally, headers will be sent out in a gathered write inside of SendContentAsync(). // If we don't have content, or we are doing Expect 100 Continue, then we can't rely on // this and must send our headers immediately. // End the stream writing if there's no content to send, do it as part of the write so that the FIN flag isn't send in an empty QUIC frame. // Note that there's no need to call Shutdown separately since the FIN flag in the last write is the same thing. await FlushSendBufferAsync(endStream: _request.Content == null, requestCancellationSource.Token).ConfigureAwait(false); } Task sendContentTask; if (_request.Content != null) { // If using duplex content, the content will continue sending after this method completes. // So, only observe the cancellation token during this method. CancellationToken sendContentCancellationToken; if (requestCancellationSource.Token.CanBeCanceled) { _sendContentCts = new CancellationTokenSource(); sendContentCancellationToken = _sendContentCts.Token; sendContentCancellationRegistration = requestCancellationSource.Token.UnsafeRegister( static s => ((CancellationTokenSource)s!).Cancel(), _sendContentCts); } else { sendContentCancellationToken = default; } sendContentTask = SendContentAsync(_request.Content!, sendContentCancellationToken); } else { sendContentTask = Task.CompletedTask; } // In parallel, send content and read response. // Depending on Expect 100 Continue usage, one will depend on the other making progress. Task readResponseTask = ReadResponseAsync(requestCancellationSource.Token); bool sendContentObserved = false; // If we're not doing duplex, wait for content to finish sending here. // If we are doing duplex and have the unlikely event that it completes here, observe the result. // See Http2Connection.SendAsync for a full comment on this logic -- it is identical behavior. if (sendContentTask.IsCompleted || _request.Content?.AllowDuplex != true || await Task.WhenAny(sendContentTask, readResponseTask).ConfigureAwait(false) == sendContentTask || sendContentTask.IsCompleted) { try { await sendContentTask.ConfigureAwait(false); sendContentObserved = true; } catch { // Exceptions will be bubbled up from sendContentTask here, // which means the result of readResponseTask won't be observed directly: // Do a background await to log any exceptions. _connection.LogExceptions(readResponseTask); throw; } } else { // Duplex is being used, so we can't wait for content to finish sending. // Do a background await to log any exceptions. _connection.LogExceptions(sendContentTask); } // Wait for the response headers to be read. await readResponseTask.ConfigureAwait(false); // Now that we've received the response, we no longer need to observe GOAWAY. // Use an atomic exchange to avoid a race to Cancel()/Dispose(). Interlocked.Exchange(ref _goawayCancellationSource, null)?.Dispose(); Debug.Assert(_response != null && _response.Content != null); // Set our content stream. var responseContent = (HttpConnectionResponseContent)_response.Content; // If we have received Content-Length: 0 and have completed sending content (which may not be the case if duplex), // we can close our Http3RequestStream immediately and return a singleton empty content stream. Otherwise, we // need to return a Http3ReadStream which will be responsible for disposing the Http3RequestStream. bool useEmptyResponseContent = responseContent.Headers.ContentLength == 0 && sendContentObserved; if (useEmptyResponseContent) { // Drain the response frames to read any trailing headers. await DrainContentLength0Frames(requestCancellationSource.Token).ConfigureAwait(false); responseContent.SetStream(EmptyReadStream.Instance); } else { // A read stream is required to finish up the request. responseContent.SetStream(new Http3ReadStream(this)); } if (NetEventSource.Log.IsEnabled()) Trace($"Received response: {_response}"); // Process any Set-Cookie headers. if (_connection.Pool.Settings._useCookies) { CookieHelper.ProcessReceivedCookies(_response, _connection.Pool.Settings._cookieContainer!); } // To avoid a circular reference (stream->response->content->stream), null out the stream's response. HttpResponseMessage response = _response; _response = null; // If we're 100% done with the stream, dispose. disposeSelf = useEmptyResponseContent; return response; } catch (QuicStreamAbortedException ex) when (ex.ErrorCode == (long)Http3ErrorCode.VersionFallback) { // The server is requesting us fall back to an older HTTP version. throw new HttpRequestException(SR.net_http_retry_on_older_version, ex, RequestRetryType.RetryOnLowerHttpVersion); } catch (QuicStreamAbortedException ex) when (ex.ErrorCode == (long)Http3ErrorCode.RequestRejected) { // The server is rejecting the request without processing it, retry it on a different connection. throw new HttpRequestException(SR.net_http_request_aborted, ex, RequestRetryType.RetryOnConnectionFailure); } catch (QuicStreamAbortedException ex) { // Our stream was reset. Exception? abortException = _connection.AbortException; throw new HttpRequestException(SR.net_http_client_execution_error, abortException ?? ex); } catch (QuicConnectionAbortedException ex) { // Our connection was reset. Start shutting down the connection. Exception abortException = _connection.Abort(ex); throw new HttpRequestException(SR.net_http_client_execution_error, abortException); } // It is possible for user's Content code to throw an unexpected OperationCanceledException. catch (OperationCanceledException ex) when (ex.CancellationToken == requestCancellationSource.Token || ex.CancellationToken == _sendContentCts?.Token) { // We're either observing GOAWAY, or the cancellationToken parameter has been canceled. if (cancellationToken.IsCancellationRequested) { _stream.AbortWrite((long)Http3ErrorCode.RequestCancelled); throw new TaskCanceledException(ex.Message, ex, cancellationToken); } else { Debug.Assert(_goawayCancellationToken.IsCancellationRequested == true); throw new HttpRequestException(SR.net_http_request_aborted, ex, RequestRetryType.RetryOnConnectionFailure); } } catch (Http3ConnectionException ex) { // A connection-level protocol error has occurred on our stream. _connection.Abort(ex); throw new HttpRequestException(SR.net_http_client_execution_error, ex); } catch (Exception ex) { _stream.AbortWrite((long)Http3ErrorCode.InternalError); if (ex is HttpRequestException) { throw; } throw new HttpRequestException(SR.net_http_client_execution_error, ex); } finally { sendContentCancellationRegistration.Dispose(); if (disposeSelf) { await DisposeAsync().ConfigureAwait(false); } } } /// <summary> /// Waits for the response headers to be read, and handles (Expect 100 etc.) informational statuses. /// </summary> private async Task ReadResponseAsync(CancellationToken cancellationToken) { if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStart(); Debug.Assert(_response == null); do { _headerState = HeaderState.StatusHeader; (Http3FrameType? frameType, long payloadLength) = await ReadFrameEnvelopeAsync(cancellationToken).ConfigureAwait(false); if (frameType != Http3FrameType.Headers) { if (NetEventSource.Log.IsEnabled()) { Trace($"Expected HEADERS as first response frame; received {frameType}."); } throw new HttpRequestException(SR.net_http_invalid_response); } await ReadHeadersAsync(payloadLength, cancellationToken).ConfigureAwait(false); Debug.Assert(_response != null); } while ((int)_response.StatusCode < 200); _headerState = HeaderState.TrailingHeaders; if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStop(); } private async Task SendContentAsync(HttpContent content, CancellationToken cancellationToken) { // If we're using Expect 100 Continue, wait to send content // until we get a response back or until our timeout elapses. if (_expect100ContinueCompletionSource != null) { Timer? timer = null; try { if (_connection.Pool.Settings._expect100ContinueTimeout != Timeout.InfiniteTimeSpan) { timer = new Timer(static o => ((Http3RequestStream)o!)._expect100ContinueCompletionSource!.TrySetResult(true), this, _connection.Pool.Settings._expect100ContinueTimeout, Timeout.InfiniteTimeSpan); } if (!await _expect100ContinueCompletionSource.Task.ConfigureAwait(false)) { // We received an error response code, so the body should not be sent. return; } } finally { if (timer != null) { await timer.DisposeAsync().ConfigureAwait(false); } } } if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestContentStart(); // If we have a Content-Length, keep track of it so we don't over-send and so we can send in a single DATA frame. _requestContentLengthRemaining = content.Headers.ContentLength ?? -1; var writeStream = new Http3WriteStream(this); try { await content.CopyToAsync(writeStream, null, cancellationToken).ConfigureAwait(false); } finally { writeStream.Dispose(); } if (_requestContentLengthRemaining > 0) { // The number of bytes we actually sent doesn't match the advertised Content-Length long contentLength = content.Headers.ContentLength.GetValueOrDefault(); long sent = contentLength - _requestContentLengthRemaining; throw new HttpRequestException(SR.Format(SR.net_http_request_content_length_mismatch, sent, contentLength)); } // Set to 0 to recognize that the whole request body has been sent and therefore there's no need to abort write side in case of a premature disposal. _requestContentLengthRemaining = 0; if (_sendBuffer.ActiveLength != 0) { // Our initial send buffer, which has our headers, is normally sent out on the first write to the Http3WriteStream. // If we get here, it means the content didn't actually do any writing. Send out the headers now. // Also send the FIN flag, since this is the last write. No need to call Shutdown separately. await FlushSendBufferAsync(endStream: true, cancellationToken).ConfigureAwait(false); } else { _stream.Shutdown(); } if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestContentStop(writeStream.BytesWritten); } private async ValueTask WriteRequestContentAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { if (buffer.Length == 0) { return; } long remaining = _requestContentLengthRemaining; if (remaining != -1) { // This HttpContent had a precomputed length, and a DATA frame was written as part of the headers. We can write directly without framing. if (buffer.Length > _requestContentLengthRemaining) { throw new HttpRequestException(SR.net_http_content_write_larger_than_content_length); } _requestContentLengthRemaining -= buffer.Length; if (!_singleDataFrameWritten) { // Note we may not have sent headers yet; if so, _sendBuffer.ActiveLength will be > 0, and we will write them in a single write. // Because we have a Content-Length, we can write it in a single DATA frame. BufferFrameEnvelope(Http3FrameType.Data, remaining); _gatheredSendBuffer[0] = _sendBuffer.ActiveMemory; _gatheredSendBuffer[1] = buffer; await _stream.WriteAsync(_gatheredSendBuffer, cancellationToken).ConfigureAwait(false); _sendBuffer.Discard(_sendBuffer.ActiveLength); _singleDataFrameWritten = true; } else { // DATA frame already sent, send just the content buffer directly. await _stream.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); } } else { // Variable-length content: write both a DATA frame and buffer. (and headers, which will still be in _sendBuffer if this is the first content write) // It's up to the HttpContent to give us sufficiently large writes to avoid excessively small DATA frames. BufferFrameEnvelope(Http3FrameType.Data, buffer.Length); _gatheredSendBuffer[0] = _sendBuffer.ActiveMemory; _gatheredSendBuffer[1] = buffer; await _stream.WriteAsync(_gatheredSendBuffer, cancellationToken).ConfigureAwait(false); _sendBuffer.Discard(_sendBuffer.ActiveLength); } } private async ValueTask FlushSendBufferAsync(bool endStream, CancellationToken cancellationToken) { await _stream.WriteAsync(_sendBuffer.ActiveMemory, endStream, cancellationToken).ConfigureAwait(false); _sendBuffer.Discard(_sendBuffer.ActiveLength); await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); } private async ValueTask DrainContentLength0Frames(CancellationToken cancellationToken) { Http3FrameType? frameType; long payloadLength; while (true) { (frameType, payloadLength) = await ReadFrameEnvelopeAsync(cancellationToken).ConfigureAwait(false); switch (frameType) { case Http3FrameType.Headers: // Pick up any trailing headers. _trailingHeaders = new List<(HeaderDescriptor name, string value)>(); await ReadHeadersAsync(payloadLength, cancellationToken).ConfigureAwait(false); // Stop looping after a trailing header. // There may be extra frames after this one, but they would all be unknown extension // frames that can be safely ignored. Just stop reading here. // Note: this does leave us open to a bad server sending us an out of order DATA frame. goto case null; case null: // Done receiving: copy over trailing headers. CopyTrailersToResponseMessage(_response!); _responseDataPayloadRemaining = -1; // Set to -1 to indicate EOS. return; case Http3FrameType.Data: // The sum of data frames must equal content length. Because this method is only // called for a Content-Length of 0, anything other than 0 here would be an error. // Per spec, 0-length payload is allowed. if (payloadLength != 0) { if (NetEventSource.Log.IsEnabled()) { Trace("Response content exceeded Content-Length."); } throw new HttpRequestException(SR.net_http_invalid_response); } break; default: Debug.Fail($"Received unexpected frame type {frameType}."); return; } } } private void CopyTrailersToResponseMessage(HttpResponseMessage responseMessage) { if (_trailingHeaders?.Count > 0) { foreach ((HeaderDescriptor name, string value) in _trailingHeaders) { responseMessage.TrailingHeaders.TryAddWithoutValidation(name, value); } _trailingHeaders.Clear(); } } private void BufferHeaders(HttpRequestMessage request) { if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestHeadersStart(); // Reserve space for the header frame envelope. // The envelope needs to be written after headers are serialized, as we need to know the payload length first. const int PreHeadersReserveSpace = Http3Frame.MaximumEncodedFrameEnvelopeLength; // This should be the first write to our buffer. The trick of reserving space won't otherwise work. Debug.Assert(_sendBuffer.ActiveLength == 0); // Reserve space for header frame envelope. _sendBuffer.Commit(PreHeadersReserveSpace); // Add header block prefix. We aren't using dynamic table, so these are simple zeroes. // https://tools.ietf.org/html/draft-ietf-quic-qpack-11#section-4.5.1 _sendBuffer.EnsureAvailableSpace(2); _sendBuffer.AvailableSpan[0] = 0x00; // required insert count. _sendBuffer.AvailableSpan[1] = 0x00; // s + delta base. _sendBuffer.Commit(2); HttpMethod normalizedMethod = HttpMethod.Normalize(request.Method); BufferBytes(normalizedMethod.Http3EncodedBytes); BufferIndexedHeader(H3StaticTable.SchemeHttps); if (request.HasHeaders && request.Headers.Host != null) { BufferLiteralHeaderWithStaticNameReference(H3StaticTable.Authority, request.Headers.Host); } else { BufferBytes(_connection.Pool._http3EncodedAuthorityHostHeader); } Debug.Assert(request.RequestUri != null); string pathAndQuery = request.RequestUri.PathAndQuery; if (pathAndQuery == "/") { BufferIndexedHeader(H3StaticTable.PathSlash); } else { BufferLiteralHeaderWithStaticNameReference(H3StaticTable.PathSlash, pathAndQuery); } // The only way to reach H3 is to upgrade via an Alt-Svc header, so we can encode Alt-Used for every connection. BufferBytes(_connection.AltUsedEncodedHeaderBytes); if (request.HasHeaders) { // H3 does not support Transfer-Encoding: chunked. if (request.HasHeaders && request.Headers.TransferEncodingChunked == true) { request.Headers.TransferEncodingChunked = false; } BufferHeaderCollection(request.Headers); } if (_connection.Pool.Settings._useCookies) { string cookiesFromContainer = _connection.Pool.Settings._cookieContainer!.GetCookieHeader(request.RequestUri); if (cookiesFromContainer != string.Empty) { Encoding? valueEncoding = _connection.Pool.Settings._requestHeaderEncodingSelector?.Invoke(HttpKnownHeaderNames.Cookie, request); BufferLiteralHeaderWithStaticNameReference(H3StaticTable.Cookie, cookiesFromContainer, valueEncoding); } } if (request.Content == null) { if (normalizedMethod.MustHaveRequestBody) { BufferIndexedHeader(H3StaticTable.ContentLength0); } } else { BufferHeaderCollection(request.Content.Headers); } // Determine our header envelope size. // The reserved space was the maximum required; discard what wasn't used. int headersLength = _sendBuffer.ActiveLength - PreHeadersReserveSpace; int headersLengthEncodedSize = VariableLengthIntegerHelper.GetByteCount(headersLength); _sendBuffer.Discard(PreHeadersReserveSpace - headersLengthEncodedSize - 1); // Encode header type in first byte, and payload length in subsequent bytes. _sendBuffer.ActiveSpan[0] = (byte)Http3FrameType.Headers; int actualHeadersLengthEncodedSize = VariableLengthIntegerHelper.WriteInteger(_sendBuffer.ActiveSpan.Slice(1, headersLengthEncodedSize), headersLength); Debug.Assert(actualHeadersLengthEncodedSize == headersLengthEncodedSize); if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.RequestHeadersStop(); } // TODO: special-case Content-Type for static table values values? private void BufferHeaderCollection(HttpHeaders headers) { HeaderEncodingSelector<HttpRequestMessage>? encodingSelector = _connection.Pool.Settings._requestHeaderEncodingSelector; foreach (HeaderEntry header in headers.GetEntries()) { int headerValuesCount = HttpHeaders.GetStoreValuesIntoStringArray(header.Key, header.Value, ref _headerValues); Debug.Assert(headerValuesCount > 0, "No values for header??"); ReadOnlySpan<string> headerValues = _headerValues.AsSpan(0, headerValuesCount); Encoding? valueEncoding = encodingSelector?.Invoke(header.Key.Name, _request); KnownHeader? knownHeader = header.Key.KnownHeader; if (knownHeader != null) { // The Host header is not sent for HTTP/3 because we send the ":authority" pseudo-header instead // (see pseudo-header handling below in WriteHeaders). // The Connection, Upgrade and ProxyConnection headers are also not supported in HTTP/3. if (knownHeader != KnownHeaders.Host && knownHeader != KnownHeaders.Connection && knownHeader != KnownHeaders.Upgrade && knownHeader != KnownHeaders.ProxyConnection) { if (knownHeader == KnownHeaders.TE) { // HTTP/2 allows only 'trailers' TE header. rfc7540 8.1.2.2 // HTTP/3 does not mention this one way or another; assume it has the same rule. foreach (string value in headerValues) { if (string.Equals(value, "trailers", StringComparison.OrdinalIgnoreCase)) { BufferLiteralHeaderWithoutNameReference("TE", value, valueEncoding); break; } } continue; } // For all other known headers, send them via their pre-encoded name and the associated value. BufferBytes(knownHeader.Http3EncodedName); string? separator = null; if (headerValues.Length > 1) { HttpHeaderParser? parser = header.Key.Parser; if (parser != null && parser.SupportsMultipleValues) { separator = parser.Separator; } else { separator = HttpHeaderParser.DefaultSeparator; } } BufferLiteralHeaderValues(headerValues, separator, valueEncoding); } } else { // The header is not known: fall back to just encoding the header name and value(s). BufferLiteralHeaderWithoutNameReference(header.Key.Name, headerValues, HttpHeaderParser.DefaultSeparator, valueEncoding); } } } private void BufferIndexedHeader(int index) { int bytesWritten; while (!QPackEncoder.EncodeStaticIndexedHeaderField(index, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderWithStaticNameReference(int nameIndex, string value, Encoding? valueEncoding = null) { int bytesWritten; while (!QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReference(nameIndex, value, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderWithoutNameReference(string name, ReadOnlySpan<string> values, string separator, Encoding? valueEncoding) { int bytesWritten; while (!QPackEncoder.EncodeLiteralHeaderFieldWithoutNameReference(name, values, separator, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderWithoutNameReference(string name, string value, Encoding? valueEncoding) { int bytesWritten; while (!QPackEncoder.EncodeLiteralHeaderFieldWithoutNameReference(name, value, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderValues(ReadOnlySpan<string> values, string? separator, Encoding? valueEncoding) { int bytesWritten; while (!QPackEncoder.EncodeValueString(values, separator, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferFrameEnvelope(Http3FrameType frameType, long payloadLength) { int bytesWritten; while (!Http3Frame.TryWriteFrameEnvelope(frameType, payloadLength, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferBytes(ReadOnlySpan<byte> span) { _sendBuffer.EnsureAvailableSpace(span.Length); span.CopyTo(_sendBuffer.AvailableSpan); _sendBuffer.Commit(span.Length); } private async ValueTask<(Http3FrameType? frameType, long payloadLength)> ReadFrameEnvelopeAsync(CancellationToken cancellationToken) { long frameType, payloadLength; int bytesRead; while (true) { while (!Http3Frame.TryReadIntegerPair(_recvBuffer.ActiveSpan, out frameType, out payloadLength, out bytesRead)) { _recvBuffer.EnsureAvailableSpace(VariableLengthIntegerHelper.MaximumEncodedLength * 2); bytesRead = await _stream.ReadAsync(_recvBuffer.AvailableMemory, cancellationToken).ConfigureAwait(false); if (bytesRead != 0) { _recvBuffer.Commit(bytesRead); } else if (_recvBuffer.ActiveLength == 0) { // End of stream. return (null, 0); } else { // Our buffer has partial frame data in it but not enough to complete the read: bail out. throw new HttpRequestException(SR.net_http_invalid_response_premature_eof); } } _recvBuffer.Discard(bytesRead); if (NetEventSource.Log.IsEnabled()) { Trace($"Received frame {frameType} of length {payloadLength}."); } switch ((Http3FrameType)frameType) { case Http3FrameType.Headers: case Http3FrameType.Data: return ((Http3FrameType)frameType, payloadLength); case Http3FrameType.Settings: // These frames should only be received on a control stream, not a response stream. case Http3FrameType.GoAway: case Http3FrameType.MaxPushId: case Http3FrameType.ReservedHttp2Priority: // These frames are explicitly reserved and must never be sent. case Http3FrameType.ReservedHttp2Ping: case Http3FrameType.ReservedHttp2WindowUpdate: case Http3FrameType.ReservedHttp2Continuation: throw new Http3ConnectionException(Http3ErrorCode.UnexpectedFrame); case Http3FrameType.PushPromise: case Http3FrameType.CancelPush: // Because we haven't sent any MAX_PUSH_ID frames, any of these push-related // frames that the server sends will have an out-of-range push ID. throw new Http3ConnectionException(Http3ErrorCode.IdError); default: // Unknown frame types should be skipped. await SkipUnknownPayloadAsync(payloadLength, cancellationToken).ConfigureAwait(false); break; } } } private async ValueTask ReadHeadersAsync(long headersLength, CancellationToken cancellationToken) { // TODO: this header budget is sent as SETTINGS_MAX_HEADER_LIST_SIZE, so it should not use frame payload but rather 32 bytes + uncompressed size per entry. // https://tools.ietf.org/html/draft-ietf-quic-http-24#section-4.1.1 if (headersLength > _headerBudgetRemaining) { _stream.AbortWrite((long)Http3ErrorCode.ExcessiveLoad); throw new HttpRequestException(SR.Format(SR.net_http_response_headers_exceeded_length, _connection.Pool.Settings._maxResponseHeadersLength * 1024L)); } _headerBudgetRemaining -= headersLength; while (headersLength != 0) { if (_recvBuffer.ActiveLength == 0) { _recvBuffer.EnsureAvailableSpace(1); int bytesRead = await _stream.ReadAsync(_recvBuffer.AvailableMemory, cancellationToken).ConfigureAwait(false); if (bytesRead != 0) { _recvBuffer.Commit(bytesRead); } else { if (NetEventSource.Log.IsEnabled()) Trace($"Server closed response stream before entire header payload could be read. {headersLength:N0} bytes remaining."); throw new HttpRequestException(SR.net_http_invalid_response_premature_eof); } } int processLength = (int)Math.Min(headersLength, _recvBuffer.ActiveLength); bool endHeaders = headersLength == processLength; _headerDecoder.Decode(_recvBuffer.ActiveSpan.Slice(0, processLength), endHeaders, this); _recvBuffer.Discard(processLength); headersLength -= processLength; } // Reset decoder state. Require because one decoder instance is reused to decode headers and trailers. _headerDecoder.Reset(); } private static ReadOnlySpan<byte> StatusHeaderNameBytes => new byte[] { (byte)'s', (byte)'t', (byte)'a', (byte)'t', (byte)'u', (byte)'s' }; void IHttpStreamHeadersHandler.OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { Debug.Assert(name.Length > 0); if (!HeaderDescriptor.TryGet(name, out HeaderDescriptor descriptor)) { // Invalid header name throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_header_name, Encoding.ASCII.GetString(name))); } OnHeader(staticIndex: null, descriptor, staticValue: default, literalValue: value); } void IHttpStreamHeadersHandler.OnStaticIndexedHeader(int index) { GetStaticQPackHeader(index, out HeaderDescriptor descriptor, out string? knownValue); OnHeader(index, descriptor, knownValue, literalValue: default); } void IHttpStreamHeadersHandler.OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value) { GetStaticQPackHeader(index, out HeaderDescriptor descriptor, knownValue: out _); OnHeader(index, descriptor, staticValue: null, literalValue: value); } void IHttpStreamHeadersHandler.OnDynamicIndexedHeader(int? index, ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { ((IHttpStreamHeadersHandler)this).OnHeader(name, value); } private void GetStaticQPackHeader(int index, out HeaderDescriptor descriptor, out string? knownValue) { if (!HeaderDescriptor.TryGetStaticQPackHeader(index, out descriptor, out knownValue)) { if (NetEventSource.Log.IsEnabled()) Trace($"Response contains invalid static header index '{index}'."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); } } /// <param name="staticIndex">The static index of the header, if any.</param> /// <param name="descriptor">A descriptor for either a known header or unknown header.</param> /// <param name="staticValue">The static indexed value, if any.</param> /// <param name="literalValue">The literal ASCII value, if any.</param> /// <remarks>One of <paramref name="staticValue"/> or <paramref name="literalValue"/> will be set.</remarks> private void OnHeader(int? staticIndex, HeaderDescriptor descriptor, string? staticValue, ReadOnlySpan<byte> literalValue) { if (descriptor.Name[0] == ':') { if (!descriptor.Equals(KnownHeaders.PseudoStatus)) { if (NetEventSource.Log.IsEnabled()) Trace($"Received unknown pseudo-header '{descriptor.Name}'."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); } if (_headerState != HeaderState.StatusHeader) { if (NetEventSource.Log.IsEnabled()) Trace("Received extra status header."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); } int statusCode; if (staticValue != null) // Indexed Header Field -- both name and value are taken from the table { statusCode = staticIndex switch { H3StaticTable.Status103 => 103, H3StaticTable.Status200 => 200, H3StaticTable.Status304 => 304, H3StaticTable.Status404 => 404, H3StaticTable.Status503 => 503, H3StaticTable.Status100 => 100, H3StaticTable.Status204 => 204, H3StaticTable.Status206 => 206, H3StaticTable.Status302 => 302, H3StaticTable.Status400 => 400, H3StaticTable.Status403 => 403, H3StaticTable.Status421 => 421, H3StaticTable.Status425 => 425, H3StaticTable.Status500 => 500, // We should never get here, at least while we only use static table. But we can still parse staticValue. _ => ParseStatusCode(staticIndex, staticValue) }; int ParseStatusCode(int? index, string value) { string message = $"Unexpected QPACK table reference for Status code: index={index} value=\'{value}\'"; Debug.Fail(message); if (NetEventSource.Log.IsEnabled()) Trace(message); // TODO: The parsing is not optimal, but I don't expect this line to be executed at all for now. return HttpConnectionBase.ParseStatusCode(Encoding.ASCII.GetBytes(value)); } } else // Literal Header Field With Name Reference -- only name is taken from the table { statusCode = HttpConnectionBase.ParseStatusCode(literalValue); } _response = new HttpResponseMessage() { Version = HttpVersion.Version30, RequestMessage = _request, Content = new HttpConnectionResponseContent(), StatusCode = (HttpStatusCode)statusCode }; if (statusCode < 200) { // Informational responses should not contain headers -- skip them. _headerState = HeaderState.SkipExpect100Headers; if (_response.StatusCode == HttpStatusCode.Continue && _expect100ContinueCompletionSource != null) { _expect100ContinueCompletionSource.TrySetResult(true); } } else { _headerState = HeaderState.ResponseHeaders; if (_expect100ContinueCompletionSource != null) { // If the final status code is >= 300, skip sending the body. bool shouldSendBody = (statusCode < 300); if (NetEventSource.Log.IsEnabled()) Trace($"Expecting 100 Continue but received final status {statusCode}."); _expect100ContinueCompletionSource.TrySetResult(shouldSendBody); } } } else if (_headerState == HeaderState.SkipExpect100Headers) { // Ignore any headers that came as part of an informational (i.e. 100 Continue) response. return; } else { string? headerValue = staticValue; if (headerValue is null) { Encoding? encoding = _connection.Pool.Settings._responseHeaderEncodingSelector?.Invoke(descriptor.Name, _request); headerValue = _connection.GetResponseHeaderValueWithCaching(descriptor, literalValue, encoding); } switch (_headerState) { case HeaderState.StatusHeader: if (NetEventSource.Log.IsEnabled()) Trace($"Received headers without :status."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); case HeaderState.ResponseHeaders when descriptor.HeaderType.HasFlag(HttpHeaderType.Content): _response!.Content!.Headers.TryAddWithoutValidation(descriptor, headerValue); break; case HeaderState.ResponseHeaders: _response!.Headers.TryAddWithoutValidation(descriptor.HeaderType.HasFlag(HttpHeaderType.Request) ? descriptor.AsCustomHeader() : descriptor, headerValue); break; case HeaderState.TrailingHeaders: _trailingHeaders!.Add((descriptor.HeaderType.HasFlag(HttpHeaderType.Request) ? descriptor.AsCustomHeader() : descriptor, headerValue)); break; default: Debug.Fail($"Unexpected {nameof(Http3RequestStream)}.{nameof(_headerState)} '{_headerState}'."); break; } } } void IHttpStreamHeadersHandler.OnHeadersComplete(bool endStream) { Debug.Fail($"This has no use in HTTP/3 and should never be called by {nameof(QPackDecoder)}."); } private async ValueTask SkipUnknownPayloadAsync(long payloadLength, CancellationToken cancellationToken) { while (payloadLength != 0) { if (_recvBuffer.ActiveLength == 0) { _recvBuffer.EnsureAvailableSpace(1); int bytesRead = await _stream.ReadAsync(_recvBuffer.AvailableMemory, cancellationToken).ConfigureAwait(false); if (bytesRead != 0) { _recvBuffer.Commit(bytesRead); } else { // Our buffer has partial frame data in it but not enough to complete the read: bail out. throw new Http3ConnectionException(Http3ErrorCode.FrameError); } } long readLength = Math.Min(payloadLength, _recvBuffer.ActiveLength); _recvBuffer.Discard((int)readLength); payloadLength -= readLength; } } private int ReadResponseContent(HttpResponseMessage response, Span<byte> buffer) { // Response headers should be done reading by the time this is called. _response is nulled out as part of this. // Verify that this is being called in correct order. Debug.Assert(_response == null); try { int totalBytesRead = 0; do { // Sync over async here -- QUIC implementation does it per-I/O already; this is at least more coarse-grained. if (_responseDataPayloadRemaining <= 0 && !ReadNextDataFrameAsync(response, CancellationToken.None).AsTask().GetAwaiter().GetResult()) { // End of stream. break; } if (_recvBuffer.ActiveLength != 0) { // Some of the payload is in our receive buffer, so copy it. int copyLen = (int)Math.Min(buffer.Length, Math.Min(_responseDataPayloadRemaining, _recvBuffer.ActiveLength)); _recvBuffer.ActiveSpan.Slice(0, copyLen).CopyTo(buffer); totalBytesRead += copyLen; _responseDataPayloadRemaining -= copyLen; _recvBuffer.Discard(copyLen); buffer = buffer.Slice(copyLen); // Stop, if we've reached the end of a data frame and start of the next data frame is not buffered yet // Waiting for the next data frame may cause a hang, e.g. in echo scenario // TODO: this is inefficient if data is already available in transport if (_responseDataPayloadRemaining == 0 && _recvBuffer.ActiveLength == 0) { break; } } else { // Receive buffer is empty -- bypass it and read directly into user's buffer. int copyLen = (int)Math.Min(buffer.Length, _responseDataPayloadRemaining); int bytesRead = _stream.Read(buffer.Slice(0, copyLen)); if (bytesRead == 0 && buffer.Length != 0) { throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, _responseDataPayloadRemaining)); } totalBytesRead += bytesRead; _responseDataPayloadRemaining -= bytesRead; buffer = buffer.Slice(bytesRead); // Stop, even if we are in the middle of a data frame. Waiting for the next data may cause a hang // TODO: this is inefficient if data is already available in transport break; } } while (buffer.Length != 0); return totalBytesRead; } catch (Exception ex) { HandleReadResponseContentException(ex, CancellationToken.None); return 0; // never reached. } } private async ValueTask<int> ReadResponseContentAsync(HttpResponseMessage response, Memory<byte> buffer, CancellationToken cancellationToken) { // Response headers should be done reading by the time this is called. _response is nulled out as part of this. // Verify that this is being called in correct order. Debug.Assert(_response == null); try { int totalBytesRead = 0; do { if (_responseDataPayloadRemaining <= 0 && !await ReadNextDataFrameAsync(response, cancellationToken).ConfigureAwait(false)) { // End of stream. break; } if (_recvBuffer.ActiveLength != 0) { // Some of the payload is in our receive buffer, so copy it. int copyLen = (int)Math.Min(buffer.Length, Math.Min(_responseDataPayloadRemaining, _recvBuffer.ActiveLength)); _recvBuffer.ActiveSpan.Slice(0, copyLen).CopyTo(buffer.Span); totalBytesRead += copyLen; _responseDataPayloadRemaining -= copyLen; _recvBuffer.Discard(copyLen); buffer = buffer.Slice(copyLen); // Stop, if we've reached the end of a data frame and start of the next data frame is not buffered yet // Waiting for the next data frame may cause a hang, e.g. in echo scenario // TODO: this is inefficient if data is already available in transport if (_responseDataPayloadRemaining == 0 && _recvBuffer.ActiveLength == 0) { break; } } else { // Receive buffer is empty -- bypass it and read directly into user's buffer. int copyLen = (int)Math.Min(buffer.Length, _responseDataPayloadRemaining); int bytesRead = await _stream.ReadAsync(buffer.Slice(0, copyLen), cancellationToken).ConfigureAwait(false); if (bytesRead == 0 && buffer.Length != 0) { throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, _responseDataPayloadRemaining)); } totalBytesRead += bytesRead; _responseDataPayloadRemaining -= bytesRead; buffer = buffer.Slice(bytesRead); // Stop, even if we are in the middle of a data frame. Waiting for the next data may cause a hang // TODO: this is inefficient if data is already available in transport break; } } while (buffer.Length != 0); return totalBytesRead; } catch (Exception ex) { HandleReadResponseContentException(ex, cancellationToken); return 0; // never reached. } } private void HandleReadResponseContentException(Exception ex, CancellationToken cancellationToken) { switch (ex) { // Peer aborted the stream case QuicStreamAbortedException _: // User aborted the stream case QuicOperationAbortedException _: throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, ex)); case QuicConnectionAbortedException _: // Our connection was reset. Start aborting the connection. Exception abortException = _connection.Abort(ex); throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, abortException)); case Http3ConnectionException _: // A connection-level protocol error has occurred on our stream. _connection.Abort(ex); throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, ex)); case OperationCanceledException oce when oce.CancellationToken == cancellationToken: _stream.AbortRead((long)Http3ErrorCode.RequestCancelled); ExceptionDispatchInfo.Throw(ex); // Rethrow. return; // Never reached. default: _stream.AbortRead((long)Http3ErrorCode.InternalError); throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, ex)); } } private async ValueTask<bool> ReadNextDataFrameAsync(HttpResponseMessage response, CancellationToken cancellationToken) { if (_responseDataPayloadRemaining == -1) { // EOS -- this branch will only be taken if user calls Read again after EOS. return false; } Http3FrameType? frameType; long payloadLength; while (true) { (frameType, payloadLength) = await ReadFrameEnvelopeAsync(cancellationToken).ConfigureAwait(false); switch (frameType) { case Http3FrameType.Data: // Ignore DATA frames with 0 length. if (payloadLength == 0) { continue; } _responseDataPayloadRemaining = payloadLength; return true; case Http3FrameType.Headers: // Read any trailing headers. _trailingHeaders = new List<(HeaderDescriptor name, string value)>(); await ReadHeadersAsync(payloadLength, cancellationToken).ConfigureAwait(false); // There may be more frames after this one, but they would all be unknown extension // frames that we are allowed to skip. Just close the stream early. // Note: if a server sends additional HEADERS or DATA frames at this point, it // would be a connection error -- not draining the stream means we won't catch this. goto case null; case null: // End of stream. CopyTrailersToResponseMessage(response); _responseDataPayloadRemaining = -1; // Set to -1 to indicate EOS. return false; } } } public void Trace(string message, [CallerMemberName] string? memberName = null) => _connection.Trace(StreamId, message, memberName); private void AbortStream() { // If the request body isn't completed, cancel it now. if (_requestContentLengthRemaining != 0) // 0 is used for the end of content writing, -1 is used for unknown Content-Length { _stream.AbortWrite((long)Http3ErrorCode.RequestCancelled); } // If the response body isn't completed, cancel it now. if (_responseDataPayloadRemaining != -1) // -1 is used for EOF, 0 for consumed DATA frame payload before the next read { _stream.AbortRead((long)Http3ErrorCode.RequestCancelled); } } // TODO: it may be possible for Http3RequestStream to implement Stream directly and avoid this allocation. private sealed class Http3ReadStream : HttpBaseStream { private Http3RequestStream? _stream; private HttpResponseMessage? _response; public override bool CanRead => _stream != null; public override bool CanWrite => false; public Http3ReadStream(Http3RequestStream stream) { _stream = stream; _response = stream._response; } ~Http3ReadStream() { Dispose(false); } protected override void Dispose(bool disposing) { Http3RequestStream? stream = Interlocked.Exchange(ref _stream, null); if (stream is null) { return; } if (disposing) { // This will remove the stream from the connection properly. stream.Dispose(); } else { // We shouldn't be using a managed instance here, but don't have much choice -- we // need to remove the stream from the connection's GOAWAY collection and properly abort. stream.AbortStream(); stream._connection.RemoveStream(stream._stream); stream._connection = null!; } _response = null; base.Dispose(disposing); } public override async ValueTask DisposeAsync() { Http3RequestStream? stream = Interlocked.Exchange(ref _stream, null); if (stream is null) { return; } await stream.DisposeAsync().ConfigureAwait(false); _response = null; await base.DisposeAsync().ConfigureAwait(false); } public override int Read(Span<byte> buffer) { Http3RequestStream? stream = _stream; if (stream is null) { throw new ObjectDisposedException(nameof(Http3RequestStream)); } Debug.Assert(_response != null); return stream.ReadResponseContent(_response, buffer); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) { Http3RequestStream? stream = _stream; if (stream is null) { return ValueTask.FromException<int>(new ObjectDisposedException(nameof(Http3RequestStream))); } Debug.Assert(_response != null); return stream.ReadResponseContentAsync(_response, buffer, cancellationToken); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { throw new NotSupportedException(); } } // TODO: it may be possible for Http3RequestStream to implement Stream directly and avoid this allocation. private sealed class Http3WriteStream : HttpBaseStream { private Http3RequestStream? _stream; public long BytesWritten { get; private set; } public override bool CanRead => false; public override bool CanWrite => _stream != null; public Http3WriteStream(Http3RequestStream stream) { _stream = stream; } protected override void Dispose(bool disposing) { _stream = null; base.Dispose(disposing); } public override int Read(Span<byte> buffer) { throw new NotSupportedException(); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) { throw new NotSupportedException(); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { BytesWritten += buffer.Length; Http3RequestStream? stream = _stream; if (stream is null) { return ValueTask.FromException(new ObjectDisposedException(nameof(Http3WriteStream))); } return stream.WriteRequestContentAsync(buffer, cancellationToken); } public override Task FlushAsync(CancellationToken cancellationToken) { Http3RequestStream? stream = _stream; if (stream is null) { return Task.FromException(new ObjectDisposedException(nameof(Http3WriteStream))); } return stream.FlushSendBufferAsync(endStream: false, cancellationToken).AsTask(); } } private enum HeaderState { StatusHeader, SkipExpect100Headers, ResponseHeaders, TrailingHeaders } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_OnesComplement.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 op_OnesComplementInt16() { var test = new VectorUnaryOpTest__op_OnesComplementInt16(); // 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 VectorUnaryOpTest__op_OnesComplementInt16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, 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); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int16> _fld1; 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>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__op_OnesComplementInt16 testClass) { var result = ~_fld1; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Vector256<Int16> _clsVar1; private Vector256<Int16> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__op_OnesComplementInt16() { 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>>()); } public VectorUnaryOpTest__op_OnesComplementInt16() { 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 < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, new Int16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = ~Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector256<Int16>).GetMethod("op_OnesComplement", new Type[] { typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = ~_clsVar1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var result = ~op1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__op_OnesComplementInt16(); var result = ~test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = ~_fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = ~test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Int16> op1, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; 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 outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (short)(~firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (short)(~firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_OnesComplement<Int16>(Vector256<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_OnesComplementInt16() { var test = new VectorUnaryOpTest__op_OnesComplementInt16(); // 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 VectorUnaryOpTest__op_OnesComplementInt16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, 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); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int16> _fld1; 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>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__op_OnesComplementInt16 testClass) { var result = ~_fld1; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Vector256<Int16> _clsVar1; private Vector256<Int16> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__op_OnesComplementInt16() { 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>>()); } public VectorUnaryOpTest__op_OnesComplementInt16() { 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 < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, new Int16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = ~Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector256<Int16>).GetMethod("op_OnesComplement", new Type[] { typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = ~_clsVar1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var result = ~op1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__op_OnesComplementInt16(); var result = ~test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = ~_fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = ~test._fld1; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Int16> op1, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; 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 outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (short)(~firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (short)(~firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_OnesComplement<Int16>(Vector256<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/Common/src/System/Collections/Generic/EnumerableExtensions.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.Diagnostics; using System.Collections.Generic; namespace System.Collections.Generic { internal static class EnumerableExtensions { // Used to prevent returning values out of IEnumerable<>-typed properties // that an untrusted caller could cast back to array or List. public static IEnumerable<T> AsNothingButIEnumerable<T>(this IEnumerable<T> en) { foreach (T t in en) yield return t; } } }
// 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.Diagnostics; using System.Collections.Generic; namespace System.Collections.Generic { internal static class EnumerableExtensions { // Used to prevent returning values out of IEnumerable<>-typed properties // that an untrusted caller could cast back to array or List. public static IEnumerable<T> AsNothingButIEnumerable<T>(this IEnumerable<T> en) { foreach (T t in en) yield return t; } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16238/b16238.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace DefaultNamespace { using System; class AA { #pragma warning disable 0414 public uint m_field1 = 151; public bool m_field2 = false; public bool m_field3 = false; public int m_field4 = 78; public static bool m_static1 = false; #pragma warning restore 0414 public static int Static1(int param1, int param2) { try { throw new Exception(); } catch (Exception) { GC.Collect(); } return 457444902; /* 7 operator(s) emitted */ } } class BB { #pragma warning disable 0414 public uint m_field1 = 91; #pragma warning restore 0414 public static int m_static1 = 34041; public uint Method1(bool param1) { int local2 = 135; if (new AA().m_field1 > new AA().m_field1) { AA.Static1(12299, BB.m_static1); AA.Static1(125, local2); AA.Static1(5196889, AA.Static1(13191820, new AA().m_field4)); } else local2 = BB.m_static1; return 49548; /* 6 operator(s) emitted */ } public static int Main() { new BB().Method1(false); return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace DefaultNamespace { using System; class AA { #pragma warning disable 0414 public uint m_field1 = 151; public bool m_field2 = false; public bool m_field3 = false; public int m_field4 = 78; public static bool m_static1 = false; #pragma warning restore 0414 public static int Static1(int param1, int param2) { try { throw new Exception(); } catch (Exception) { GC.Collect(); } return 457444902; /* 7 operator(s) emitted */ } } class BB { #pragma warning disable 0414 public uint m_field1 = 91; #pragma warning restore 0414 public static int m_static1 = 34041; public uint Method1(bool param1) { int local2 = 135; if (new AA().m_field1 > new AA().m_field1) { AA.Static1(12299, BB.m_static1); AA.Static1(125, local2); AA.Static1(5196889, AA.Static1(13191820, new AA().m_field4)); } else local2 = BB.m_static1; return 49548; /* 6 operator(s) emitted */ } public static int Main() { new BB().Method1(false); return 100; } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/X86/Sse41_Overloaded/RoundToNearestIntegerScalar.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundToNearestIntegerScalarSingle() { var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.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 (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.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 (Sse.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 (Sse.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 (Sse.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 SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, 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); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.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<Single> _fld1; 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<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle testClass) { var result = Sse41.RoundToNearestIntegerScalar(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.RoundToNearestIntegerScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.RoundToNearestIntegerScalar( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = Sse41.RoundToNearestIntegerScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToNearestIntegerScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToNearestIntegerScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle(); var result = Sse41.RoundToNearestIntegerScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.RoundToNearestIntegerScalar(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.RoundToNearestIntegerScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _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<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[0], MidpointRounding.AwayFromZero))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToNearestIntegerScalar)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundToNearestIntegerScalarSingle() { var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.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 (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.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 (Sse.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 (Sse.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 (Sse.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 SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, 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); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.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<Single> _fld1; 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<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle testClass) { var result = Sse41.RoundToNearestIntegerScalar(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.RoundToNearestIntegerScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNearestIntegerScalar), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.RoundToNearestIntegerScalar( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = Sse41.RoundToNearestIntegerScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToNearestIntegerScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToNearestIntegerScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle(); var result = Sse41.RoundToNearestIntegerScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__RoundToNearestIntegerScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.RoundToNearestIntegerScalar(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.RoundToNearestIntegerScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.RoundToNearestIntegerScalar( Sse.LoadVector128((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _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<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[0], MidpointRounding.AwayFromZero))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToNearestIntegerScalar)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApi/AddParameterEB7.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" omit-xml-declaration="yes" /> <xsl:param name="param1" select="'default global'"/> <xsl:template match="/"> <xsl:call-template name="Test"> <xsl:with-param name="param1"/> </xsl:call-template> </xsl:template> <xsl:template name="Test"> <result><xsl:value-of select="$param1" /></result> </xsl:template> </xsl:stylesheet>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" omit-xml-declaration="yes" /> <xsl:param name="param1" select="'default global'"/> <xsl:template match="/"> <xsl:call-template name="Test"> <xsl:with-param name="param1"/> </xsl:call-template> </xsl:template> <xsl:template name="Test"> <result><xsl:value-of select="$param1" /></result> </xsl:template> </xsl:stylesheet>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/AddPairwise.Vector128.Int64.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 AddPairwise_Vector128_Int64() { var test = new SimpleBinaryOpTest__AddPairwise_Vector128_Int64(); 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__AddPairwise_Vector128_Int64 { 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(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); 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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, 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<Int64> _fld1; public Vector128<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddPairwise_Vector128_Int64 testClass) { var result = AdvSimd.Arm64.AddPairwise(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddPairwise_Vector128_Int64 testClass) { fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(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<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddPairwise_Vector128_Int64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public SimpleBinaryOpTest__AddPairwise_Vector128_Int64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[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.AddPairwise( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AddPairwise), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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.AddPairwise), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.AddPairwise( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int64>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(pClsVar1)), AdvSimd.LoadVector128((Int64*)(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<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.AddPairwise(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((Int64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.AddPairwise(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddPairwise_Vector128_Int64(); var result = AdvSimd.Arm64.AddPairwise(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__AddPairwise_Vector128_Int64(); fixed (Vector128<Int64>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.AddPairwise(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.AddPairwise(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(&test._fld1)), AdvSimd.LoadVector128((Int64*)(&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<Int64> op1, Vector128<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AddPairwise(left, right, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.AddPairwise)}<Int64>(Vector128<Int64>, Vector128<Int64>): {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 AddPairwise_Vector128_Int64() { var test = new SimpleBinaryOpTest__AddPairwise_Vector128_Int64(); 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__AddPairwise_Vector128_Int64 { 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(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); 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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, 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<Int64> _fld1; public Vector128<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddPairwise_Vector128_Int64 testClass) { var result = AdvSimd.Arm64.AddPairwise(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddPairwise_Vector128_Int64 testClass) { fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(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<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddPairwise_Vector128_Int64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public SimpleBinaryOpTest__AddPairwise_Vector128_Int64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[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.AddPairwise( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AddPairwise), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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.AddPairwise), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.AddPairwise( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int64>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(pClsVar1)), AdvSimd.LoadVector128((Int64*)(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<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.AddPairwise(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((Int64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.AddPairwise(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddPairwise_Vector128_Int64(); var result = AdvSimd.Arm64.AddPairwise(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__AddPairwise_Vector128_Int64(); fixed (Vector128<Int64>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.AddPairwise(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.AddPairwise(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.AddPairwise( AdvSimd.LoadVector128((Int64*)(&test._fld1)), AdvSimd.LoadVector128((Int64*)(&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<Int64> op1, Vector128<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AddPairwise(left, right, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.AddPairwise)}<Int64>(Vector128<Int64>, Vector128<Int64>): {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,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Methodical/MDArray/DataTypes/short_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="short.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="short.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Private.Xml.Linq/tests/XDocument.Common/InputSpace.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 System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; using XmlCoreTest.Common; namespace CoreXml.Test.XLinq { // used in DOMXmlFiles public enum DocumentStatus { valid, invalid, notWellFormed, all } ////////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Class for input generation used by all tests /// </summary> ////////////////////////////////////////////////////////////////////////////////////////////////////// public static class InputSpace { // loads either the file for DMLCreate public static void Load(object loadObject, ref XDocument xDoc, ref XDocument xmlDoc) { Load(loadObject as string, ref xDoc, ref xmlDoc); } // Creates XDocument and XmlDocument from a input file public static void Load(string fileName, ref XDocument xDoc, ref XDocument xmlDoc) { XmlReaderSettings rs = new XmlReaderSettings(); rs.IgnoreWhitespace = true; rs.DtdProcessing = DtdProcessing.Ignore; string filePath = Path.Combine("TestData", "XLinq", fileName); using (XmlReader r1 = XmlReader.Create(FilePathUtil.getStream(filePath), rs)) xDoc = XDocument.Load(r1); using (XmlReader r2 = XmlReader.Create(FilePathUtil.getStream(filePath), rs)) { xmlDoc = XDocument.Load(r2); } } // List of input xml files used in DOM Control files public static IEnumerable<string> DOMXmlFiles(DocumentStatus docStatus) { string status, file, filePath; XNamespace ns = "WebData/TestSpec"; // look in each one of the DOM test control files for xml files used foreach (string controlFile in DOMControlFiles()) { XDocument xDoc = null; XmlReaderSettings rs = new XmlReaderSettings(); rs.IgnoreWhitespace = true; using (XmlReader reader = XmlReader.Create(FilePathUtil.getStream(controlFile), rs)) { xDoc = XDocument.Load(reader); } // get the filePath from the control file filePath = (string)xDoc.Descendants(ns + "global").Attributes("filePath").FirstOrDefault(); if (filePath.StartsWith(@"$(DataPath)\StandardTests\")) { filePath = Path.Combine(XLinqTestCase.StandardPath, filePath.Substring(@"$(DataPath)\StandardTests\".Length)); } // get xml file used in each variation foreach (XElement e in xDoc.Descendants(ns + "variation").Where(x => x.Attribute("implemented").Value == "true")) { file = e.Descendants(ns + "xml").FirstOrDefault().Value.Trim(); file = Path.Combine(filePath, file); // check if the file exists, if not then continue try { if (FilePathUtil.getStream(file) == null) continue; } catch (Exception) { continue; } // if there are more than one "result" nodes then find the one that is used for System.Xml IEnumerable<XElement> resultNodes = e.Descendants(ns + "result"); IEnumerable<XElement> systemXml = e.Descendants(ns + "System.Xml"); if (resultNodes.Count() > 1 && systemXml.Count() > 0) { string resultID = (string)systemXml.Select(x => x.Element(ns + "expectedResult")).Attributes("id").FirstOrDefault(); status = (string)resultNodes.Where(x => x.Attribute("id").Value == resultID).Attributes("expected").FirstOrDefault(); } else status = (string)resultNodes.Attributes("expected").FirstOrDefault(); switch (docStatus) { case DocumentStatus.valid: if ("valid".Equals(status)) yield return file; break; case DocumentStatus.invalid: if ("invalid".Equals(status)) yield return file; break; case DocumentStatus.notWellFormed: if ("not-wf".Equals(status)) yield return file; break; default: yield return file; break; } } } } // List of control files used in DOM tests public static IEnumerable<string> DOMControlFiles() { XDocument xDoc = null; XmlReaderSettings rs = new XmlReaderSettings(); rs.IgnoreWhitespace = true; string masterControlFile = @"xlinq_master_xml.xml"; using (XmlReader reader = XmlReader.Create(FilePathUtil.getStream(masterControlFile), rs)) { xDoc = XDocument.Load(reader); } // Get test specific control files foreach (XElement x in xDoc.Descendants("testCase")) { yield return ((string)x.Attribute("uri")); } } public static XElement GetElement(int elementCount, int childElementCount) { XElement root = new XElement("root"); for (int l = 0; l < elementCount; l++) { XElement nl = new XElement("e" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); root.Add(nl); for (int e = 0; e < childElementCount; e++) { XElement child = new XElement("e" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); nl.Add(child); } } return root; } public static XElement GetAttributeElement(int elementCount, int attributeCount) { XElement root = new XElement("root"); for (int l = 0; l < elementCount; l++) { XElement nl = new XElement("e" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); for (int a = 0; a < attributeCount; a++) { XAttribute attribute = new XAttribute("a" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); nl.Add(attribute); } root.Add(nl); } return root; } public static XElement GetNamespaceElement(int namespaceCount, int elementCount, int childElementCount) { XElement root = new XElement("root"); Random random = new Random(unchecked((int)DateTime.Now.Ticks)); Guid[] namespaces = new Guid[namespaceCount]; for (int n = 0; n < namespaceCount; n++) namespaces[n] = Guid.NewGuid(); for (int l = 0; l < elementCount; l++) { XElement nl = new XElement("{n" + namespaces[random.Next(namespaceCount)] + "}p" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); root.Add(nl); for (int e = 0; e < childElementCount; e++) { XElement child = new XElement("{n" + namespaces[random.Next(namespaceCount)] + "}c" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); nl.Add(child); } } return root; } public static void RootElement(ref XDocument xDoc, ref XDocument xmlDoc) { xDoc = XDocument.Parse("<root/>"); xmlDoc = XDocument.Parse(xDoc.ToString(SaveOptions.DisableFormatting)); } public static void TextNodes(ref XDocument xDoc, ref XDocument xmlDoc) { xDoc = XDocument.Parse("<root>some text</root>"); xmlDoc = XDocument.Parse(xDoc.ToString(SaveOptions.DisableFormatting)); } public static void Contacts(ref XDocument xDoc, ref XDocument xmlDoc) { xDoc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XProcessingInstruction("AppName", "Processing Instruction Data"), new XComment("Personal Contacts"), new XElement("contacts", new XAttribute("category", "friends"), new XAttribute("gender", "male"), new XElement("contact", new XAttribute("netWorth", "100"), new XElement("name", "John Hopkins"), new XElement("phone", new XAttribute("type", "home"), "214-459-8907"), new XElement("phone", new XAttribute("type", "work"), "817-283-9670")), new XElement("contact", new XAttribute("netWorth", "10"), new XElement("name", "Patrick Hines"), new XElement("phone", new XAttribute("type", "home"), "206-555-0144"), new XElement("phone", new XAttribute("type", "work"), "425-555-0145")))); xmlDoc = XDocument.Parse(xDoc.ToString(SaveOptions.DisableFormatting)); } public static void Teams(ref XDocument xDoc, ref XDocument xmlDoc) { XNamespace sp = "http://www.sportsleagues.com/"; XNamespace nba = "http://www.nba.com/"; xDoc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XProcessingInstruction("AppName", "Processing Instruction Data"), new XComment("Sport Leaques"), new XElement(sp + "SportLeagues", new XAttribute(XNamespace.Xmlns + "sp", sp), new XElement("League", new XAttribute("type", "Basketball"), new XAttribute("name", "National Basketball Association"), new XAttribute("id", "NBA"), new XAttribute(XNamespace.Xmlns + "nba", nba), new XElement("commissioner", "David Stern"), new XElement(nba + "Conference", new XAttribute(nba + "name", "Eastern"), new XElement(nba + "Division", new XAttribute(nba + "name", "Central") ), new XElement(nba + "Division", new XAttribute(nba + "name", "SouthEast") ), new XElement(nba + "Division", new XAttribute(nba + "name", "Atlantic"), new XElement(nba + "Teams", new XElement(nba + "Team", new XAttribute(nba + "name", "New Jersy Nets"), new XElement(nba + "Players", new XElement(nba + "Player", new XComment(" The best player on the team "), "\n" + " Or Is he the best player on the team?\n" + " ", new XElement(nba + "Name", "Richard Jefferson"), "<>,;:.@#$%^&*()?/`~+-", new XProcessingInstruction("Player", "processing instruction") ), new XElement(nba + "Player") ) ), new XElement(nba + "Team") ) ) ), new XElement(nba + "Conference", new XAttribute(nba + "name", "Western"), new XElement(nba + "Division", new XAttribute("name", "NorthWest") ), new XElement(nba + "Division", new XAttribute(nba + "name", "SouthWest") ), new XElement(nba + "Division", new XAttribute(nba + "name", "Pacific") ) ) ), new XElement("League", new XAttribute("type", "Football"), new XAttribute("name", "National Football League"), new XAttribute("id", "NFL"), new XAttribute(XNamespace.Xmlns + "nfl", "http://www.nfl.com"), new XElement("commissioner", "Paul Taglibu"), new XElement("Conference", new XAttribute("name", "NFC"), new XElement("Division", new XAttribute("name", "East"), new XElement("Teams", new XElement("Team", new XAttribute("name", "Dallas Cowboys"), new XComment(" The best team in the division "), "\n" + " Or Is it the best team in the division?\n" + " ", new XElement("Coach", "Bill Parcells"), "<>,;:.@#$%^&*()?/`~+-", new XProcessingInstruction("Cowboys", "processing instruction"), new XElement("Players") ), new XElement("Team", new XAttribute("name", "New Your Giants"), new XComment(" The second best team in the division "), "\n" + " Or Is it the second best team in the division?\n" + " ", new XElement("Coach", "Tom Coughlin"), "<>,;:.@#$%^&*()?/`~+-", new XProcessingInstruction("Giants", "processing instruction"), new XElement("Players") ), new XElement("Team"), new XElement("Team") ) ), new XElement("Division", new XAttribute("name", "West"), new XElement("Teams", new XElement("Team", new XAttribute("name", "Seattle Seahawks"), new XComment(" The best team in the division "), "\n" + " Or Is it the best team in the division?\n" + " ", new XElement("Coach", "Mike Holmgren"), "This should be a text node", new XProcessingInstruction("Seakhwaks", "processing instruction"), new XElement("Players") ), new XElement("Team", new XAttribute("name", "Arizona Cardinals"), new XComment(" The second best team in the division "), "\n" + " Or Is it the second best team in the division?\n" + " ", new XElement("Coach", "Dennis Green"), "<>,;:.@#$%^&*()?/`~+-", new XProcessingInstruction("Cardinals", "processing instruction"), new XElement("Players") ), new XElement("Team"), new XElement("Team") ) ), new XElement("Division", new XAttribute("name", "North"), new XElement("Teams") ), new XElement("Division", new XAttribute("name", "South"), new XElement("Teams") ) ), new XElement("Conference", new XAttribute("name", "AFC"), new XElement("Division", new XAttribute("name", "East"), new XElement("Teams") ), new XElement("Division", new XAttribute("name", "West"), new XElement("Teams") ), new XElement("Division", new XAttribute("name", "North"), new XElement("Teams") ), new XElement("Division", new XAttribute("name", "South"), new XElement("Teams") ) ) ), new XElement("League", new XAttribute("type", "Baseball"), new XAttribute("name", "Major League Baseball"), new XAttribute("id", "MLB"), new XAttribute(XNamespace.Xmlns + "mlb", "http://www.mlb.com") ), new XElement("League", new XAttribute("type", "Hockey"), new XAttribute("name", "National Hockey League"), new XAttribute("id", "NHL"), new XAttribute(XNamespace.Xmlns + "nhl", "http://www.nhl.com") ) ) ); xmlDoc = XDocument.Parse(xDoc.ToString(SaveOptions.DisableFormatting)); } public static void Hamlet(ref XDocument xDoc, ref XDocument xmlDoc) { xDoc = new XDocument( new XElement("PLAY", new XElement("TITLE", "The Tragedy of Hamlet, Prince of Denmark"), new XElement("fm", new XElement("p", "Text placed in the public domain by Moby Lexical Tools, 1992."), new XElement("p", "SGML markup by Jon Bosak, 1992-1994."), new XElement("p", "XML version by Jon Bosak, 1996-1997."), new XElement("p", "This work may be freely copied and distributed worldwide.") ), new XElement("PERSONAE", new XElement("TITLE", "Dramatis Personae"), new XElement("PERSONA", "CLAUDIUS, king of Denmark. "), new XElement("PERSONA", "HAMLET, son to the late, and nephew to the present king."), new XElement("PERSONA", "POLONIUS, lord chamberlain. "), new XElement("PERSONA", "HORATIO, friend to Hamlet."), new XElement("PERSONA", "LAERTES, son to Polonius."), new XElement("PERSONA", "LUCIANUS, nephew to the king."), new XElement("PGROUP", new XElement("PERSONA", "VOLTIMAND"), new XElement("PERSONA", "CORNELIUS"), new XElement("PERSONA", "ROSENCRANTZ"), new XElement("PERSONA", "GUILDENSTERN"), new XElement("PERSONA", "OSRIC"), new XElement("GRPDESCR", "courtiers.") ), new XElement("PERSONA", "A Gentleman"), new XElement("PERSONA", "A Priest. "), new XElement("PGROUP", new XElement("PERSONA", "MARCELLUS"), new XElement("PERSONA", "BERNARDO"), new XElement("GRPDESCR", "officers.") ), new XElement("PERSONA", "FRANCISCO, a soldier."), new XElement("PERSONA", "REYNALDO, servant to Polonius."), new XElement("PERSONA", "Players."), new XElement("PERSONA", "Two Clowns, grave-diggers."), new XElement("PERSONA", "FORTINBRAS, prince of Norway. "), new XElement("PERSONA", "A Captain."), new XElement("PERSONA", "English Ambassadors. "), new XElement("PERSONA", "GERTRUDE, queen of Denmark, and mother to Hamlet. "), new XElement("PERSONA", "OPHELIA, daughter to Polonius."), new XElement("PERSONA", "Lords, Ladies, Officers, Soldiers, Sailors, Messengers, and other Attendants."), new XElement("PERSONA", "Ghost of Hamlet's Father. ") ), new XElement("SCNDESCR", "SCENE Denmark."), new XElement("PLAYSUBT", "HAMLET"), new XElement("ACT", new XElement("TITLE", "ACT I"), new XElement("SCENE", new XElement("TITLE", "SCENE I. Elsinore. A platform before the castle."), new XElement("STAGEDIR", "FRANCISCO at his post. Enter to him BERNARDO"), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Who's there?") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "Nay, answer me: stand, and unfold yourself.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Long live the king!") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "Bernardo?") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "He.") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "You come most carefully upon your hour.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "'Tis now struck twelve; get thee to bed, Francisco.") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "For this relief much thanks: 'tis bitter cold,"), new XElement("LINE", "And I am sick at heart.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Have you had quiet guard?") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "Not a mouse stirring.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Well, good night."), new XElement("LINE", "If you do meet Horatio and Marcellus,"), new XElement("LINE", "The rivals of my watch, bid them make haste.") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "I think I hear them. Stand, ho! Who's there?") ), new XElement("STAGEDIR", "Enter HORATIO and MARCELLUS"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Friends to this ground.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "And liegemen to the Dane.") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "Give you good night.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "O, farewell, honest soldier:"), new XElement("LINE", "Who hath relieved you?") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "Bernardo has my place."), new XElement("LINE", "Give you good night.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Holla! Bernardo!") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Say,"), new XElement("LINE", "What, is Horatio there?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "A piece of him.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Welcome, Horatio: welcome, good Marcellus.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "What, has this thing appear'd again to-night?") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "I have seen nothing.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Horatio says 'tis but our fantasy,"), new XElement("LINE", "And will not let belief take hold of him"), new XElement("LINE", "Touching this dreaded sight, twice seen of us:"), new XElement("LINE", "Therefore I have entreated him along"), new XElement("LINE", "With us to watch the minutes of this night;"), new XElement("LINE", "That if again this apparition come,"), new XElement("LINE", "He may approve our eyes and speak to it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Tush, tush, 'twill not appear.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Sit down awhile;"), new XElement("LINE", "And let us once again assail your ears,"), new XElement("LINE", "That are so fortified against our story"), new XElement("LINE", "What we have two nights seen.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Well, sit we down,"), new XElement("LINE", "And let us hear Bernardo speak of this.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Last night of all,"), new XElement("LINE", "When yond same star that's westward from the pole"), new XElement("LINE", "Had made his course to illume that part of heaven"), new XElement("LINE", "Where now it burns, Marcellus and myself,"), new XElement("LINE", "The bell then beating one,--") ), new XElement("STAGEDIR", "Enter Ghost"), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Peace, break thee off; look, where it comes again!") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "In the same figure, like the king that's dead.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Thou art a scholar; speak to it, Horatio.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Looks it not like the king? mark it, Horatio.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Most like: it harrows me with fear and wonder.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "It would be spoke to.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Question it, Horatio.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What art thou that usurp'st this time of night,"), new XElement("LINE", "Together with that fair and warlike form"), new XElement("LINE", "In which the majesty of buried Denmark"), new XElement("LINE", "Did sometimes march? by heaven I charge thee, speak!") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "It is offended.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "See, it stalks away!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Stay! speak, speak! I charge thee, speak!") ), new XElement("STAGEDIR", "Exit Ghost"), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "'Tis gone, and will not answer.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "How now, Horatio! you tremble and look pale:"), new XElement("LINE", "Is not this something more than fantasy?"), new XElement("LINE", "What think you on't?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Before my God, I might not this believe"), new XElement("LINE", "Without the sensible and true avouch"), new XElement("LINE", "Of mine own eyes.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Is it not like the king?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "As thou art to thyself:"), new XElement("LINE", "Such was the very armour he had on"), new XElement("LINE", "When he the ambitious Norway combated;"), new XElement("LINE", "So frown'd he once, when, in an angry parle,"), new XElement("LINE", "He smote the sledded Polacks on the ice."), new XElement("LINE", "'Tis strange.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Thus twice before, and jump at this dead hour,"), new XElement("LINE", "With martial stalk hath he gone by our watch.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "In what particular thought to work I know not;"), new XElement("LINE", "But in the gross and scope of my opinion,"), new XElement("LINE", "This bodes some strange eruption to our state.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Good now, sit down, and tell me, he that knows,"), new XElement("LINE", "Why this same strict and most observant watch"), new XElement("LINE", "So nightly toils the subject of the land,"), new XElement("LINE", "And why such daily cast of brazen cannon,"), new XElement("LINE", "And foreign mart for implements of war;"), new XElement("LINE", "Why such impress of shipwrights, whose sore task"), new XElement("LINE", "Does not divide the Sunday from the week;"), new XElement("LINE", "What might be toward, that this sweaty haste"), new XElement("LINE", "Doth make the night joint-labourer with the day:"), new XElement("LINE", "Who is't that can inform me?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "That can I;"), new XElement("LINE", "At least, the whisper goes so. Our last king,"), new XElement("LINE", "Whose image even but now appear'd to us,"), new XElement("LINE", "Was, as you know, by Fortinbras of Norway,"), new XElement("LINE", "Thereto prick'd on by a most emulate pride,"), new XElement("LINE", "Dared to the combat; in which our valiant Hamlet--"), new XElement("LINE", "For so this side of our known world esteem'd him--"), new XElement("LINE", "Did slay this Fortinbras; who by a seal'd compact,"), new XElement("LINE", "Well ratified by law and heraldry,"), new XElement("LINE", "Did forfeit, with his life, all those his lands"), new XElement("LINE", "Which he stood seized of, to the conqueror:"), new XElement("LINE", "Against the which, a moiety competent"), new XElement("LINE", "Was gaged by our king; which had return'd"), new XElement("LINE", "To the inheritance of Fortinbras,"), new XElement("LINE", "Had he been vanquisher; as, by the same covenant,"), new XElement("LINE", "And carriage of the article design'd,"), new XElement("LINE", "His fell to Hamlet. Now, sir, young Fortinbras,"), new XElement("LINE", "Of unimproved mettle hot and full,"), new XElement("LINE", "Hath in the skirts of Norway here and there"), new XElement("LINE", "Shark'd up a list of lawless resolutes,"), new XElement("LINE", "For food and diet, to some enterprise"), new XElement("LINE", "That hath a stomach in't; which is no other--"), new XElement("LINE", "As it doth well appear unto our state--"), new XElement("LINE", "But to recover of us, by strong hand"), new XElement("LINE", "And terms compulsatory, those foresaid lands"), new XElement("LINE", "So by his father lost: and this, I take it,"), new XElement("LINE", "Is the main motive of our preparations,"), new XElement("LINE", "The source of this our watch and the chief head"), new XElement("LINE", "Of this post-haste and romage in the land.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "I think it be no other but e'en so:"), new XElement("LINE", "Well may it sort that this portentous figure"), new XElement("LINE", "Comes armed through our watch; so like the king"), new XElement("LINE", "That was and is the question of these wars.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "A mote it is to trouble the mind's eye."), new XElement("LINE", "In the most high and palmy state of Rome,"), new XElement("LINE", "A little ere the mightiest Julius fell,"), new XElement("LINE", "The graves stood tenantless and the sheeted dead"), new XElement("LINE", "Did squeak and gibber in the Roman streets:"), new XElement("LINE", "As stars with trains of fire and dews of blood,"), new XElement("LINE", "Disasters in the sun; and the moist star"), new XElement("LINE", "Upon whose influence Neptune's empire stands"), new XElement("LINE", "Was sick almost to doomsday with eclipse:"), new XElement("LINE", "And even the like precurse of fierce events,"), new XElement("LINE", "As harbingers preceding still the fates"), new XElement("LINE", "And prologue to the omen coming on,"), new XElement("LINE", "Have heaven and earth together demonstrated"), new XElement("LINE", "Unto our climatures and countrymen.--"), new XElement("LINE", "But soft, behold! lo, where it comes again!"), new XElement("STAGEDIR", "Re-enter Ghost"), new XElement("LINE", "I'll cross it, though it blast me. Stay, illusion!"), new XElement("LINE", "If thou hast any sound, or use of voice,"), new XElement("LINE", "Speak to me:"), new XElement("LINE", "If there be any good thing to be done,"), new XElement("LINE", "That may to thee do ease and grace to me,"), new XElement("LINE", "Speak to me:"), new XElement("STAGEDIR", "Cock crows"), new XElement("LINE", "If thou art privy to thy country's fate,"), new XElement("LINE", "Which, happily, foreknowing may avoid, O, speak!"), new XElement("LINE", "Or if thou hast uphoarded in thy life"), new XElement("LINE", "Extorted treasure in the womb of earth,"), new XElement("LINE", "For which, they say, you spirits oft walk in death,"), new XElement("LINE", "Speak of it: stay, and speak! Stop it, Marcellus.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Shall I strike at it with my partisan?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Do, if it will not stand.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "'Tis here!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "'Tis here!") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "'Tis gone!"), new XElement("STAGEDIR", "Exit Ghost"), new XElement("LINE", "We do it wrong, being so majestical,"), new XElement("LINE", "To offer it the show of violence;"), new XElement("LINE", "For it is, as the air, invulnerable,"), new XElement("LINE", "And our vain blows malicious mockery.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "It was about to speak, when the cock crew.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "And then it started like a guilty thing"), new XElement("LINE", "Upon a fearful summons. I have heard,"), new XElement("LINE", "The cock, that is the trumpet to the morn,"), new XElement("LINE", "Doth with his lofty and shrill-sounding throat"), new XElement("LINE", "Awake the god of day; and, at his warning,"), new XElement("LINE", "Whether in sea or fire, in earth or air,"), new XElement("LINE", "The extravagant and erring spirit hies"), new XElement("LINE", "To his confine: and of the truth herein"), new XElement("LINE", "This present object made probation.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "It faded on the crowing of the cock."), new XElement("LINE", "Some say that ever 'gainst that season comes"), new XElement("LINE", "Wherein our Saviour's birth is celebrated,"), new XElement("LINE", "The bird of dawning singeth all night long:"), new XElement("LINE", "And then, they say, no spirit dares stir abroad;"), new XElement("LINE", "The nights are wholesome; then no planets strike,"), new XElement("LINE", "No fairy takes, nor witch hath power to charm,"), new XElement("LINE", "So hallow'd and so gracious is the time.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "So have I heard and do in part believe it."), new XElement("LINE", "But, look, the morn, in russet mantle clad,"), new XElement("LINE", "Walks o'er the dew of yon high eastward hill:"), new XElement("LINE", "Break we our watch up; and by my advice,"), new XElement("LINE", "Let us impart what we have seen to-night"), new XElement("LINE", "Unto young Hamlet; for, upon my life,"), new XElement("LINE", "This spirit, dumb to us, will speak to him."), new XElement("LINE", "Do you consent we shall acquaint him with it,"), new XElement("LINE", "As needful in our loves, fitting our duty?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Let's do't, I pray; and I this morning know"), new XElement("LINE", "Where we shall find him most conveniently.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE II. A room of state in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, QUEEN GERTRUDE, HAMLET,\n" + "POLONIUS, LAERTES, VOLTIMAND, CORNELIUS, Lords,\n" + "and Attendants" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Though yet of Hamlet our dear brother's death"), new XElement("LINE", "The memory be green, and that it us befitted"), new XElement("LINE", "To bear our hearts in grief and our whole kingdom"), new XElement("LINE", "To be contracted in one brow of woe,"), new XElement("LINE", "Yet so far hath discretion fought with nature"), new XElement("LINE", "That we with wisest sorrow think on him,"), new XElement("LINE", "Together with remembrance of ourselves."), new XElement("LINE", "Therefore our sometime sister, now our queen,"), new XElement("LINE", "The imperial jointress to this warlike state,"), new XElement("LINE", "Have we, as 'twere with a defeated joy,--"), new XElement("LINE", "With an auspicious and a dropping eye,"), new XElement("LINE", "With mirth in funeral and with dirge in marriage,"), new XElement("LINE", "In equal scale weighing delight and dole,--"), new XElement("LINE", "Taken to wife: nor have we herein barr'd"), new XElement("LINE", "Your better wisdoms, which have freely gone"), new XElement("LINE", "With this affair along. For all, our thanks."), new XElement("LINE", "Now follows, that you know, young Fortinbras,"), new XElement("LINE", "Holding a weak supposal of our worth,"), new XElement("LINE", "Or thinking by our late dear brother's death"), new XElement("LINE", "Our state to be disjoint and out of frame,"), new XElement("LINE", "Colleagued with the dream of his advantage,"), new XElement("LINE", "He hath not fail'd to pester us with message,"), new XElement("LINE", "Importing the surrender of those lands"), new XElement("LINE", "Lost by his father, with all bonds of law,"), new XElement("LINE", "To our most valiant brother. So much for him."), new XElement("LINE", "Now for ourself and for this time of meeting:"), new XElement("LINE", "Thus much the business is: we have here writ"), new XElement("LINE", "To Norway, uncle of young Fortinbras,--"), new XElement("LINE", "Who, impotent and bed-rid, scarcely hears"), new XElement("LINE", "Of this his nephew's purpose,--to suppress"), new XElement("LINE", "His further gait herein; in that the levies,"), new XElement("LINE", "The lists and full proportions, are all made"), new XElement("LINE", "Out of his subject: and we here dispatch"), new XElement("LINE", "You, good Cornelius, and you, Voltimand,"), new XElement("LINE", "For bearers of this greeting to old Norway;"), new XElement("LINE", "Giving to you no further personal power"), new XElement("LINE", "To business with the king, more than the scope"), new XElement("LINE", "Of these delated articles allow."), new XElement("LINE", "Farewell, and let your haste commend your duty.") ), new XElement("SPEECH", new XElement("SPEAKER", "CORNELIUS"), new XElement("SPEAKER", "VOLTIMAND"), new XElement("LINE", "In that and all things will we show our duty.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "We doubt it nothing: heartily farewell."), new XElement("STAGEDIR", "Exeunt VOLTIMAND and CORNELIUS"), new XElement("LINE", "And now, Laertes, what's the news with you?"), new XElement("LINE", "You told us of some suit; what is't, Laertes?"), new XElement("LINE", "You cannot speak of reason to the Dane,"), new XElement("LINE", "And loose your voice: what wouldst thou beg, Laertes,"), new XElement("LINE", "That shall not be my offer, not thy asking?"), new XElement("LINE", "The head is not more native to the heart,"), new XElement("LINE", "The hand more instrumental to the mouth,"), new XElement("LINE", "Than is the throne of Denmark to thy father."), new XElement("LINE", "What wouldst thou have, Laertes?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "My dread lord,"), new XElement("LINE", "Your leave and favour to return to France;"), new XElement("LINE", "From whence though willingly I came to Denmark,"), new XElement("LINE", "To show my duty in your coronation,"), new XElement("LINE", "Yet now, I must confess, that duty done,"), new XElement("LINE", "My thoughts and wishes bend again toward France"), new XElement("LINE", "And bow them to your gracious leave and pardon.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Have you your father's leave? What says Polonius?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "He hath, my lord, wrung from me my slow leave"), new XElement("LINE", "By laboursome petition, and at last"), new XElement("LINE", "Upon his will I seal'd my hard consent:"), new XElement("LINE", "I do beseech you, give him leave to go.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Take thy fair hour, Laertes; time be thine,"), new XElement("LINE", "And thy best graces spend it at thy will!"), new XElement("LINE", "But now, my cousin Hamlet, and my son,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " A little more than kin, and less than kind." ) ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "How is it that the clouds still hang on you?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Not so, my lord; I am too much i' the sun.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Good Hamlet, cast thy nighted colour off,"), new XElement("LINE", "And let thine eye look like a friend on Denmark."), new XElement("LINE", "Do not for ever with thy vailed lids"), new XElement("LINE", "Seek for thy noble father in the dust:"), new XElement("LINE", "Thou know'st 'tis common; all that lives must die,"), new XElement("LINE", "Passing through nature to eternity.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, madam, it is common.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "If it be,"), new XElement("LINE", "Why seems it so particular with thee?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Seems, madam! nay it is; I know not 'seems.'"), new XElement("LINE", "'Tis not alone my inky cloak, good mother,"), new XElement("LINE", "Nor customary suits of solemn black,"), new XElement("LINE", "Nor windy suspiration of forced breath,"), new XElement("LINE", "No, nor the fruitful river in the eye,"), new XElement("LINE", "Nor the dejected 'havior of the visage,"), new XElement("LINE", "Together with all forms, moods, shapes of grief,"), new XElement("LINE", "That can denote me truly: these indeed seem,"), new XElement("LINE", "For they are actions that a man might play:"), new XElement("LINE", "But I have that within which passeth show;"), new XElement("LINE", "These but the trappings and the suits of woe.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "'Tis sweet and commendable in your nature, Hamlet,"), new XElement("LINE", "To give these mourning duties to your father:"), new XElement("LINE", "But, you must know, your father lost a father;"), new XElement("LINE", "That father lost, lost his, and the survivor bound"), new XElement("LINE", "In filial obligation for some term"), new XElement("LINE", "To do obsequious sorrow: but to persever"), new XElement("LINE", "In obstinate condolement is a course"), new XElement("LINE", "Of impious stubbornness; 'tis unmanly grief;"), new XElement("LINE", "It shows a will most incorrect to heaven,"), new XElement("LINE", "A heart unfortified, a mind impatient,"), new XElement("LINE", "An understanding simple and unschool'd:"), new XElement("LINE", "For what we know must be and is as common"), new XElement("LINE", "As any the most vulgar thing to sense,"), new XElement("LINE", "Why should we in our peevish opposition"), new XElement("LINE", "Take it to heart? Fie! 'tis a fault to heaven,"), new XElement("LINE", "A fault against the dead, a fault to nature,"), new XElement("LINE", "To reason most absurd: whose common theme"), new XElement("LINE", "Is death of fathers, and who still hath cried,"), new XElement("LINE", "From the first corse till he that died to-day,"), new XElement("LINE", "'This must be so.' We pray you, throw to earth"), new XElement("LINE", "This unprevailing woe, and think of us"), new XElement("LINE", "As of a father: for let the world take note,"), new XElement("LINE", "You are the most immediate to our throne;"), new XElement("LINE", "And with no less nobility of love"), new XElement("LINE", "Than that which dearest father bears his son,"), new XElement("LINE", "Do I impart toward you. For your intent"), new XElement("LINE", "In going back to school in Wittenberg,"), new XElement("LINE", "It is most retrograde to our desire:"), new XElement("LINE", "And we beseech you, bend you to remain"), new XElement("LINE", "Here, in the cheer and comfort of our eye,"), new XElement("LINE", "Our chiefest courtier, cousin, and our son.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Let not thy mother lose her prayers, Hamlet:"), new XElement("LINE", "I pray thee, stay with us; go not to Wittenberg.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I shall in all my best obey you, madam.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Why, 'tis a loving and a fair reply:"), new XElement("LINE", "Be as ourself in Denmark. Madam, come;"), new XElement("LINE", "This gentle and unforced accord of Hamlet"), new XElement("LINE", "Sits smiling to my heart: in grace whereof,"), new XElement("LINE", "No jocund health that Denmark drinks to-day,"), new XElement("LINE", "But the great cannon to the clouds shall tell,"), new XElement("LINE", "And the king's rouse the heavens all bruit again,"), new XElement("LINE", "Re-speaking earthly thunder. Come away.") ), new XElement("STAGEDIR", "Exeunt all but HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, that this too too solid flesh would melt"), new XElement("LINE", "Thaw and resolve itself into a dew!"), new XElement("LINE", "Or that the Everlasting had not fix'd"), new XElement("LINE", "His canon 'gainst self-slaughter! O God! God!"), new XElement("LINE", "How weary, stale, flat and unprofitable,"), new XElement("LINE", "Seem to me all the uses of this world!"), new XElement("LINE", "Fie on't! ah fie! 'tis an unweeded garden,"), new XElement("LINE", "That grows to seed; things rank and gross in nature"), new XElement("LINE", "Possess it merely. That it should come to this!"), new XElement("LINE", "But two months dead: nay, not so much, not two:"), new XElement("LINE", "So excellent a king; that was, to this,"), new XElement("LINE", "Hyperion to a satyr; so loving to my mother"), new XElement("LINE", "That he might not beteem the winds of heaven"), new XElement("LINE", "Visit her face too roughly. Heaven and earth!"), new XElement("LINE", "Must I remember? why, she would hang on him,"), new XElement("LINE", "As if increase of appetite had grown"), new XElement("LINE", "By what it fed on: and yet, within a month--"), new XElement("LINE", "Let me not think on't--Frailty, thy name is woman!--"), new XElement("LINE", "A little month, or ere those shoes were old"), new XElement("LINE", "With which she follow'd my poor father's body,"), new XElement("LINE", "Like Niobe, all tears:--why she, even she--"), new XElement("LINE", "O, God! a beast, that wants discourse of reason,"), new XElement("LINE", "Would have mourn'd longer--married with my uncle,"), new XElement("LINE", "My father's brother, but no more like my father"), new XElement("LINE", "Than I to Hercules: within a month:"), new XElement("LINE", "Ere yet the salt of most unrighteous tears"), new XElement("LINE", "Had left the flushing in her galled eyes,"), new XElement("LINE", "She married. O, most wicked speed, to post"), new XElement("LINE", "With such dexterity to incestuous sheets!"), new XElement("LINE", "It is not nor it cannot come to good:"), new XElement("LINE", "But break, my heart; for I must hold my tongue.") ), new XElement("STAGEDIR", "Enter HORATIO, MARCELLUS, and BERNARDO"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Hail to your lordship!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am glad to see you well:"), new XElement("LINE", "Horatio,--or I do forget myself.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "The same, my lord, and your poor servant ever.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, my good friend; I'll change that name with you:"), new XElement("LINE", "And what make you from Wittenberg, Horatio? Marcellus?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "My good lord--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am very glad to see you. Good even, sir."), new XElement("LINE", "But what, in faith, make you from Wittenberg?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "A truant disposition, good my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I would not hear your enemy say so,"), new XElement("LINE", "Nor shall you do mine ear that violence,"), new XElement("LINE", "To make it truster of your own report"), new XElement("LINE", "Against yourself: I know you are no truant."), new XElement("LINE", "But what is your affair in Elsinore?"), new XElement("LINE", "We'll teach you to drink deep ere you depart.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "My lord, I came to see your father's funeral.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I pray thee, do not mock me, fellow-student;"), new XElement("LINE", "I think it was to see my mother's wedding.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Indeed, my lord, it follow'd hard upon.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Thrift, thrift, Horatio! the funeral baked meats"), new XElement("LINE", "Did coldly furnish forth the marriage tables."), new XElement("LINE", "Would I had met my dearest foe in heaven"), new XElement("LINE", "Or ever I had seen that day, Horatio!"), new XElement("LINE", "My father!--methinks I see my father.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Where, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "In my mind's eye, Horatio.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I saw him once; he was a goodly king.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "He was a man, take him for all in all,"), new XElement("LINE", "I shall not look upon his like again.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "My lord, I think I saw him yesternight.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Saw? who?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "My lord, the king your father.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The king my father!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Season your admiration for awhile"), new XElement("LINE", "With an attent ear, till I may deliver,"), new XElement("LINE", "Upon the witness of these gentlemen,"), new XElement("LINE", "This marvel to you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "For God's love, let me hear.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Two nights together had these gentlemen,"), new XElement("LINE", "Marcellus and Bernardo, on their watch,"), new XElement("LINE", "In the dead vast and middle of the night,"), new XElement("LINE", "Been thus encounter'd. A figure like your father,"), new XElement("LINE", "Armed at point exactly, cap-a-pe,"), new XElement("LINE", "Appears before them, and with solemn march"), new XElement("LINE", "Goes slow and stately by them: thrice he walk'd"), new XElement("LINE", "By their oppress'd and fear-surprised eyes,"), new XElement("LINE", "Within his truncheon's length; whilst they, distilled"), new XElement("LINE", "Almost to jelly with the act of fear,"), new XElement("LINE", "Stand dumb and speak not to him. This to me"), new XElement("LINE", "In dreadful secrecy impart they did;"), new XElement("LINE", "And I with them the third night kept the watch;"), new XElement("LINE", "Where, as they had deliver'd, both in time,"), new XElement("LINE", "Form of the thing, each word made true and good,"), new XElement("LINE", "The apparition comes: I knew your father;"), new XElement("LINE", "These hands are not more like.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "But where was this?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "My lord, upon the platform where we watch'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Did you not speak to it?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "My lord, I did;"), new XElement("LINE", "But answer made it none: yet once methought"), new XElement("LINE", "It lifted up its head and did address"), new XElement("LINE", "Itself to motion, like as it would speak;"), new XElement("LINE", "But even then the morning cock crew loud,"), new XElement("LINE", "And at the sound it shrunk in haste away,"), new XElement("LINE", "And vanish'd from our sight.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Tis very strange.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "As I do live, my honour'd lord, 'tis true;"), new XElement("LINE", "And we did think it writ down in our duty"), new XElement("LINE", "To let you know of it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Indeed, indeed, sirs, but this troubles me."), new XElement("LINE", "Hold you the watch to-night?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "We do, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Arm'd, say you?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Arm'd, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "From top to toe?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "My lord, from head to foot.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then saw you not his face?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "O, yes, my lord; he wore his beaver up.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What, look'd he frowningly?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "A countenance more in sorrow than in anger.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Pale or red?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Nay, very pale.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "And fix'd his eyes upon you?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Most constantly.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I would I had been there.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It would have much amazed you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Very like, very like. Stay'd it long?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "While one with moderate haste might tell a hundred.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Longer, longer.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Not when I saw't.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "His beard was grizzled--no?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It was, as I have seen it in his life,"), new XElement("LINE", "A sable silver'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I will watch to-night;"), new XElement("LINE", "Perchance 'twill walk again.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I warrant it will.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "If it assume my noble father's person,"), new XElement("LINE", "I'll speak to it, though hell itself should gape"), new XElement("LINE", "And bid me hold my peace. I pray you all,"), new XElement("LINE", "If you have hitherto conceal'd this sight,"), new XElement("LINE", "Let it be tenable in your silence still;"), new XElement("LINE", "And whatsoever else shall hap to-night,"), new XElement("LINE", "Give it an understanding, but no tongue:"), new XElement("LINE", "I will requite your loves. So, fare you well:"), new XElement("LINE", "Upon the platform, 'twixt eleven and twelve,"), new XElement("LINE", "I'll visit you.") ), new XElement("SPEECH", new XElement("SPEAKER", "All"), new XElement("LINE", "Our duty to your honour.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Your loves, as mine to you: farewell."), new XElement("STAGEDIR", "Exeunt all but HAMLET"), new XElement("LINE", "My father's spirit in arms! all is not well;"), new XElement("LINE", "I doubt some foul play: would the night were come!"), new XElement("LINE", "Till then sit still, my soul: foul deeds will rise,"), new XElement("LINE", "Though all the earth o'erwhelm them, to men's eyes.") ), new XElement("STAGEDIR", "Exit") ), new XElement("SCENE", new XElement("TITLE", "SCENE III. A room in Polonius' house."), new XElement("STAGEDIR", "Enter LAERTES and OPHELIA"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "My necessaries are embark'd: farewell:"), new XElement("LINE", "And, sister, as the winds give benefit"), new XElement("LINE", "And convoy is assistant, do not sleep,"), new XElement("LINE", "But let me hear from you.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Do you doubt that?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "For Hamlet and the trifling of his favour,"), new XElement("LINE", "Hold it a fashion and a toy in blood,"), new XElement("LINE", "A violet in the youth of primy nature,"), new XElement("LINE", "Forward, not permanent, sweet, not lasting,"), new XElement("LINE", "The perfume and suppliance of a minute; No more.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "No more but so?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Think it no more;"), new XElement("LINE", "For nature, crescent, does not grow alone"), new XElement("LINE", "In thews and bulk, but, as this temple waxes,"), new XElement("LINE", "The inward service of the mind and soul"), new XElement("LINE", "Grows wide withal. Perhaps he loves you now,"), new XElement("LINE", "And now no soil nor cautel doth besmirch"), new XElement("LINE", "The virtue of his will: but you must fear,"), new XElement("LINE", "His greatness weigh'd, his will is not his own;"), new XElement("LINE", "For he himself is subject to his birth:"), new XElement("LINE", "He may not, as unvalued persons do,"), new XElement("LINE", "Carve for himself; for on his choice depends"), new XElement("LINE", "The safety and health of this whole state;"), new XElement("LINE", "And therefore must his choice be circumscribed"), new XElement("LINE", "Unto the voice and yielding of that body"), new XElement("LINE", "Whereof he is the head. Then if he says he loves you,"), new XElement("LINE", "It fits your wisdom so far to believe it"), new XElement("LINE", "As he in his particular act and place"), new XElement("LINE", "May give his saying deed; which is no further"), new XElement("LINE", "Than the main voice of Denmark goes withal."), new XElement("LINE", "Then weigh what loss your honour may sustain,"), new XElement("LINE", "If with too credent ear you list his songs,"), new XElement("LINE", "Or lose your heart, or your chaste treasure open"), new XElement("LINE", "To his unmaster'd importunity."), new XElement("LINE", "Fear it, Ophelia, fear it, my dear sister,"), new XElement("LINE", "And keep you in the rear of your affection,"), new XElement("LINE", "Out of the shot and danger of desire."), new XElement("LINE", "The chariest maid is prodigal enough,"), new XElement("LINE", "If she unmask her beauty to the moon:"), new XElement("LINE", "Virtue itself 'scapes not calumnious strokes:"), new XElement("LINE", "The canker galls the infants of the spring,"), new XElement("LINE", "Too oft before their buttons be disclosed,"), new XElement("LINE", "And in the morn and liquid dew of youth"), new XElement("LINE", "Contagious blastments are most imminent."), new XElement("LINE", "Be wary then; best safety lies in fear:"), new XElement("LINE", "Youth to itself rebels, though none else near.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I shall the effect of this good lesson keep,"), new XElement("LINE", "As watchman to my heart. But, good my brother,"), new XElement("LINE", "Do not, as some ungracious pastors do,"), new XElement("LINE", "Show me the steep and thorny way to heaven;"), new XElement("LINE", "Whiles, like a puff'd and reckless libertine,"), new XElement("LINE", "Himself the primrose path of dalliance treads,"), new XElement("LINE", "And recks not his own rede.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "O, fear me not."), new XElement("LINE", "I stay too long: but here my father comes."), new XElement("STAGEDIR", "Enter POLONIUS"), new XElement("LINE", "A double blessing is a double grace,"), new XElement("LINE", "Occasion smiles upon a second leave.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Yet here, Laertes! aboard, aboard, for shame!"), new XElement("LINE", "The wind sits in the shoulder of your sail,"), new XElement("LINE", "And you are stay'd for. There; my blessing with thee!"), new XElement("LINE", "And these few precepts in thy memory"), new XElement("LINE", "See thou character. Give thy thoughts no tongue,"), new XElement("LINE", "Nor any unproportioned thought his act."), new XElement("LINE", "Be thou familiar, but by no means vulgar."), new XElement("LINE", "Those friends thou hast, and their adoption tried,"), new XElement("LINE", "Grapple them to thy soul with hoops of steel;"), new XElement("LINE", "But do not dull thy palm with entertainment"), new XElement("LINE", "Of each new-hatch'd, unfledged comrade. Beware"), new XElement("LINE", "Of entrance to a quarrel, but being in,"), new XElement("LINE", "Bear't that the opposed may beware of thee."), new XElement("LINE", "Give every man thy ear, but few thy voice;"), new XElement("LINE", "Take each man's censure, but reserve thy judgment."), new XElement("LINE", "Costly thy habit as thy purse can buy,"), new XElement("LINE", "But not express'd in fancy; rich, not gaudy;"), new XElement("LINE", "For the apparel oft proclaims the man,"), new XElement("LINE", "And they in France of the best rank and station"), new XElement("LINE", "Are of a most select and generous chief in that."), new XElement("LINE", "Neither a borrower nor a lender be;"), new XElement("LINE", "For loan oft loses both itself and friend,"), new XElement("LINE", "And borrowing dulls the edge of husbandry."), new XElement("LINE", "This above all: to thine ownself be true,"), new XElement("LINE", "And it must follow, as the night the day,"), new XElement("LINE", "Thou canst not then be false to any man."), new XElement("LINE", "Farewell: my blessing season this in thee!") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Most humbly do I take my leave, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "The time invites you; go; your servants tend.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Farewell, Ophelia; and remember well"), new XElement("LINE", "What I have said to you.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "'Tis in my memory lock'd,"), new XElement("LINE", "And you yourself shall keep the key of it.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Farewell.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What is't, Ophelia, be hath said to you?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "So please you, something touching the Lord Hamlet.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Marry, well bethought:"), new XElement("LINE", "'Tis told me, he hath very oft of late"), new XElement("LINE", "Given private time to you; and you yourself"), new XElement("LINE", "Have of your audience been most free and bounteous:"), new XElement("LINE", "If it be so, as so 'tis put on me,"), new XElement("LINE", "And that in way of caution, I must tell you,"), new XElement("LINE", "You do not understand yourself so clearly"), new XElement("LINE", "As it behoves my daughter and your honour."), new XElement("LINE", "What is between you? give me up the truth.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "He hath, my lord, of late made many tenders"), new XElement("LINE", "Of his affection to me.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Affection! pooh! you speak like a green girl,"), new XElement("LINE", "Unsifted in such perilous circumstance."), new XElement("LINE", "Do you believe his tenders, as you call them?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I do not know, my lord, what I should think.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Marry, I'll teach you: think yourself a baby;"), new XElement("LINE", "That you have ta'en these tenders for true pay,"), new XElement("LINE", "Which are not sterling. Tender yourself more dearly;"), new XElement("LINE", "Or--not to crack the wind of the poor phrase,"), new XElement("LINE", "Running it thus--you'll tender me a fool.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My lord, he hath importuned me with love"), new XElement("LINE", "In honourable fashion.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Ay, fashion you may call it; go to, go to.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "And hath given countenance to his speech, my lord,"), new XElement("LINE", "With almost all the holy vows of heaven.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Ay, springes to catch woodcocks. I do know,"), new XElement("LINE", "When the blood burns, how prodigal the soul"), new XElement("LINE", "Lends the tongue vows: these blazes, daughter,"), new XElement("LINE", "Giving more light than heat, extinct in both,"), new XElement("LINE", "Even in their promise, as it is a-making,"), new XElement("LINE", "You must not take for fire. From this time"), new XElement("LINE", "Be somewhat scanter of your maiden presence;"), new XElement("LINE", "Set your entreatments at a higher rate"), new XElement("LINE", "Than a command to parley. For Lord Hamlet,"), new XElement("LINE", "Believe so much in him, that he is young"), new XElement("LINE", "And with a larger tether may he walk"), new XElement("LINE", "Than may be given you: in few, Ophelia,"), new XElement("LINE", "Do not believe his vows; for they are brokers,"), new XElement("LINE", "Not of that dye which their investments show,"), new XElement("LINE", "But mere implorators of unholy suits,"), new XElement("LINE", "Breathing like sanctified and pious bawds,"), new XElement("LINE", "The better to beguile. This is for all:"), new XElement("LINE", "I would not, in plain terms, from this time forth,"), new XElement("LINE", "Have you so slander any moment leisure,"), new XElement("LINE", "As to give words or talk with the Lord Hamlet."), new XElement("LINE", "Look to't, I charge you: come your ways.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I shall obey, my lord.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE IV. The platform."), new XElement("STAGEDIR", "Enter HAMLET, HORATIO, and MARCELLUS"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The air bites shrewdly; it is very cold.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It is a nipping and an eager air.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What hour now?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I think it lacks of twelve.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, it is struck.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Indeed? I heard it not: then it draws near the season"), new XElement("LINE", "Wherein the spirit held his wont to walk."), new XElement("STAGEDIR", "A flourish of trumpets, and ordnance shot off, within"), new XElement("LINE", "What does this mean, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The king doth wake to-night and takes his rouse,"), new XElement("LINE", "Keeps wassail, and the swaggering up-spring reels;"), new XElement("LINE", "And, as he drains his draughts of Rhenish down,"), new XElement("LINE", "The kettle-drum and trumpet thus bray out"), new XElement("LINE", "The triumph of his pledge.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Is it a custom?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, marry, is't:"), new XElement("LINE", "But to my mind, though I am native here"), new XElement("LINE", "And to the manner born, it is a custom"), new XElement("LINE", "More honour'd in the breach than the observance."), new XElement("LINE", "This heavy-headed revel east and west"), new XElement("LINE", "Makes us traduced and tax'd of other nations:"), new XElement("LINE", "They clepe us drunkards, and with swinish phrase"), new XElement("LINE", "Soil our addition; and indeed it takes"), new XElement("LINE", "From our achievements, though perform'd at height,"), new XElement("LINE", "The pith and marrow of our attribute."), new XElement("LINE", "So, oft it chances in particular men,"), new XElement("LINE", "That for some vicious mole of nature in them,"), new XElement("LINE", "As, in their birth--wherein they are not guilty,"), new XElement("LINE", "Since nature cannot choose his origin--"), new XElement("LINE", "By the o'ergrowth of some complexion,"), new XElement("LINE", "Oft breaking down the pales and forts of reason,"), new XElement("LINE", "Or by some habit that too much o'er-leavens"), new XElement("LINE", "The form of plausive manners, that these men,"), new XElement("LINE", "Carrying, I say, the stamp of one defect,"), new XElement("LINE", "Being nature's livery, or fortune's star,--"), new XElement("LINE", "Their virtues else--be they as pure as grace,"), new XElement("LINE", "As infinite as man may undergo--"), new XElement("LINE", "Shall in the general censure take corruption"), new XElement("LINE", "From that particular fault: the dram of eale"), new XElement("LINE", "Doth all the noble substance of a doubt"), new XElement("LINE", "To his own scandal.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Look, my lord, it comes!") ), new XElement("STAGEDIR", "Enter Ghost"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Angels and ministers of grace defend us!"), new XElement("LINE", "Be thou a spirit of health or goblin damn'd,"), new XElement("LINE", "Bring with thee airs from heaven or blasts from hell,"), new XElement("LINE", "Be thy intents wicked or charitable,"), new XElement("LINE", "Thou comest in such a questionable shape"), new XElement("LINE", "That I will speak to thee: I'll call thee Hamlet,"), new XElement("LINE", "King, father, royal Dane: O, answer me!"), new XElement("LINE", "Let me not burst in ignorance; but tell"), new XElement("LINE", "Why thy canonized bones, hearsed in death,"), new XElement("LINE", "Have burst their cerements; why the sepulchre,"), new XElement("LINE", "Wherein we saw thee quietly inurn'd,"), new XElement("LINE", "Hath oped his ponderous and marble jaws,"), new XElement("LINE", "To cast thee up again. What may this mean,"), new XElement("LINE", "That thou, dead corse, again in complete steel"), new XElement("LINE", "Revisit'st thus the glimpses of the moon,"), new XElement("LINE", "Making night hideous; and we fools of nature"), new XElement("LINE", "So horridly to shake our disposition"), new XElement("LINE", "With thoughts beyond the reaches of our souls?"), new XElement("LINE", "Say, why is this? wherefore? what should we do?") ), new XElement("STAGEDIR", "Ghost beckons HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It beckons you to go away with it,"), new XElement("LINE", "As if it some impartment did desire"), new XElement("LINE", "To you alone.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Look, with what courteous action"), new XElement("LINE", "It waves you to a more removed ground:"), new XElement("LINE", "But do not go with it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "No, by no means.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It will not speak; then I will follow it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Do not, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, what should be the fear?"), new XElement("LINE", "I do not set my life in a pin's fee;"), new XElement("LINE", "And for my soul, what can it do to that,"), new XElement("LINE", "Being a thing immortal as itself?"), new XElement("LINE", "It waves me forth again: I'll follow it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What if it tempt you toward the flood, my lord,"), new XElement("LINE", "Or to the dreadful summit of the cliff"), new XElement("LINE", "That beetles o'er his base into the sea,"), new XElement("LINE", "And there assume some other horrible form,"), new XElement("LINE", "Which might deprive your sovereignty of reason"), new XElement("LINE", "And draw you into madness? think of it:"), new XElement("LINE", "The very place puts toys of desperation,"), new XElement("LINE", "Without more motive, into every brain"), new XElement("LINE", "That looks so many fathoms to the sea"), new XElement("LINE", "And hears it roar beneath.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It waves me still."), new XElement("LINE", "Go on; I'll follow thee.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "You shall not go, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Hold off your hands.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Be ruled; you shall not go.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "My fate cries out,"), new XElement("LINE", "And makes each petty artery in this body"), new XElement("LINE", "As hardy as the Nemean lion's nerve."), new XElement("LINE", "Still am I call'd. Unhand me, gentlemen."), new XElement("LINE", "By heaven, I'll make a ghost of him that lets me!"), new XElement("LINE", "I say, away! Go on; I'll follow thee.") ), new XElement("STAGEDIR", "Exeunt Ghost and HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "He waxes desperate with imagination.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Let's follow; 'tis not fit thus to obey him.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Have after. To what issue will this come?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Something is rotten in the state of Denmark.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Heaven will direct it.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Nay, let's follow him.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE V. Another part of the platform."), new XElement("STAGEDIR", "Enter GHOST and HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Where wilt thou lead me? speak; I'll go no further.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Mark me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I will.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "My hour is almost come,"), new XElement("LINE", "When I to sulphurous and tormenting flames"), new XElement("LINE", "Must render up myself.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Alas, poor ghost!") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Pity me not, but lend thy serious hearing"), new XElement("LINE", "To what I shall unfold.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Speak; I am bound to hear.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "So art thou to revenge, when thou shalt hear.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What?") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "I am thy father's spirit,"), new XElement("LINE", "Doom'd for a certain term to walk the night,"), new XElement("LINE", "And for the day confined to fast in fires,"), new XElement("LINE", "Till the foul crimes done in my days of nature"), new XElement("LINE", "Are burnt and purged away. But that I am forbid"), new XElement("LINE", "To tell the secrets of my prison-house,"), new XElement("LINE", "I could a tale unfold whose lightest word"), new XElement("LINE", "Would harrow up thy soul, freeze thy young blood,"), new XElement("LINE", "Make thy two eyes, like stars, start from their spheres,"), new XElement("LINE", "Thy knotted and combined locks to part"), new XElement("LINE", "And each particular hair to stand on end,"), new XElement("LINE", "Like quills upon the fretful porpentine:"), new XElement("LINE", "But this eternal blazon must not be"), new XElement("LINE", "To ears of flesh and blood. List, list, O, list!"), new XElement("LINE", "If thou didst ever thy dear father love--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O God!") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Revenge his foul and most unnatural murder.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Murder!") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Murder most foul, as in the best it is;"), new XElement("LINE", "But this most foul, strange and unnatural.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Haste me to know't, that I, with wings as swift"), new XElement("LINE", "As meditation or the thoughts of love,"), new XElement("LINE", "May sweep to my revenge.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "I find thee apt;"), new XElement("LINE", "And duller shouldst thou be than the fat weed"), new XElement("LINE", "That roots itself in ease on Lethe wharf,"), new XElement("LINE", "Wouldst thou not stir in this. Now, Hamlet, hear:"), new XElement("LINE", "'Tis given out that, sleeping in my orchard,"), new XElement("LINE", "A serpent stung me; so the whole ear of Denmark"), new XElement("LINE", "Is by a forged process of my death"), new XElement("LINE", "Rankly abused: but know, thou noble youth,"), new XElement("LINE", "The serpent that did sting thy father's life"), new XElement("LINE", "Now wears his crown.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O my prophetic soul! My uncle!") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Ay, that incestuous, that adulterate beast,"), new XElement("LINE", "With witchcraft of his wit, with traitorous gifts,--"), new XElement("LINE", "O wicked wit and gifts, that have the power"), new XElement("LINE", "So to seduce!--won to his shameful lust"), new XElement("LINE", "The will of my most seeming-virtuous queen:"), new XElement("LINE", "O Hamlet, what a falling-off was there!"), new XElement("LINE", "From me, whose love was of that dignity"), new XElement("LINE", "That it went hand in hand even with the vow"), new XElement("LINE", "I made to her in marriage, and to decline"), new XElement("LINE", "Upon a wretch whose natural gifts were poor"), new XElement("LINE", "To those of mine!"), new XElement("LINE", "But virtue, as it never will be moved,"), new XElement("LINE", "Though lewdness court it in a shape of heaven,"), new XElement("LINE", "So lust, though to a radiant angel link'd,"), new XElement("LINE", "Will sate itself in a celestial bed,"), new XElement("LINE", "And prey on garbage."), new XElement("LINE", "But, soft! methinks I scent the morning air;"), new XElement("LINE", "Brief let me be. Sleeping within my orchard,"), new XElement("LINE", "My custom always of the afternoon,"), new XElement("LINE", "Upon my secure hour thy uncle stole,"), new XElement("LINE", "With juice of cursed hebenon in a vial,"), new XElement("LINE", "And in the porches of my ears did pour"), new XElement("LINE", "The leperous distilment; whose effect"), new XElement("LINE", "Holds such an enmity with blood of man"), new XElement("LINE", "That swift as quicksilver it courses through"), new XElement("LINE", "The natural gates and alleys of the body,"), new XElement("LINE", "And with a sudden vigour doth posset"), new XElement("LINE", "And curd, like eager droppings into milk,"), new XElement("LINE", "The thin and wholesome blood: so did it mine;"), new XElement("LINE", "And a most instant tetter bark'd about,"), new XElement("LINE", "Most lazar-like, with vile and loathsome crust,"), new XElement("LINE", "All my smooth body."), new XElement("LINE", "Thus was I, sleeping, by a brother's hand"), new XElement("LINE", "Of life, of crown, of queen, at once dispatch'd:"), new XElement("LINE", "Cut off even in the blossoms of my sin,"), new XElement("LINE", "Unhousel'd, disappointed, unanel'd,"), new XElement("LINE", "No reckoning made, but sent to my account"), new XElement("LINE", "With all my imperfections on my head:"), new XElement("LINE", "O, horrible! O, horrible! most horrible!"), new XElement("LINE", "If thou hast nature in thee, bear it not;"), new XElement("LINE", "Let not the royal bed of Denmark be"), new XElement("LINE", "A couch for luxury and damned incest."), new XElement("LINE", "But, howsoever thou pursuest this act,"), new XElement("LINE", "Taint not thy mind, nor let thy soul contrive"), new XElement("LINE", "Against thy mother aught: leave her to heaven"), new XElement("LINE", "And to those thorns that in her bosom lodge,"), new XElement("LINE", "To prick and sting her. Fare thee well at once!"), new XElement("LINE", "The glow-worm shows the matin to be near,"), new XElement("LINE", "And 'gins to pale his uneffectual fire:"), new XElement("LINE", "Adieu, adieu! Hamlet, remember me.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O all you host of heaven! O earth! what else?"), new XElement("LINE", "And shall I couple hell? O, fie! Hold, hold, my heart;"), new XElement("LINE", "And you, my sinews, grow not instant old,"), new XElement("LINE", "But bear me stiffly up. Remember thee!"), new XElement("LINE", "Ay, thou poor ghost, while memory holds a seat"), new XElement("LINE", "In this distracted globe. Remember thee!"), new XElement("LINE", "Yea, from the table of my memory"), new XElement("LINE", "I'll wipe away all trivial fond records,"), new XElement("LINE", "All saws of books, all forms, all pressures past,"), new XElement("LINE", "That youth and observation copied there;"), new XElement("LINE", "And thy commandment all alone shall live"), new XElement("LINE", "Within the book and volume of my brain,"), new XElement("LINE", "Unmix'd with baser matter: yes, by heaven!"), new XElement("LINE", "O most pernicious woman!"), new XElement("LINE", "O villain, villain, smiling, damned villain!"), new XElement("LINE", "My tables,--meet it is I set it down,"), new XElement("LINE", "That one may smile, and smile, and be a villain;"), new XElement("LINE", "At least I'm sure it may be so in Denmark:"), new XElement("STAGEDIR", "Writing"), new XElement("LINE", "So, uncle, there you are. Now to my word;"), new XElement("LINE", "It is 'Adieu, adieu! remember me.'"), new XElement("LINE", "I have sworn 't.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("SPEAKER", "HORATIO"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " My lord, my lord,--" ) ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Lord Hamlet,--" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Heaven secure him!" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "So be it!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Hillo, ho, ho, my lord!" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Hillo, ho, ho, boy! come, bird, come.") ), new XElement("STAGEDIR", "Enter HORATIO and MARCELLUS"), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "How is't, my noble lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What news, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, wonderful!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Good my lord, tell it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No; you'll reveal it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Not I, my lord, by heaven.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Nor I, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How say you, then; would heart of man once think it?"), new XElement("LINE", "But you'll be secret?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Ay, by heaven, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "There's ne'er a villain dwelling in all Denmark"), new XElement("LINE", "But he's an arrant knave.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "There needs no ghost, my lord, come from the grave"), new XElement("LINE", "To tell us this.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, right; you are i' the right;"), new XElement("LINE", "And so, without more circumstance at all,"), new XElement("LINE", "I hold it fit that we shake hands and part:"), new XElement("LINE", "You, as your business and desire shall point you;"), new XElement("LINE", "For every man has business and desire,"), new XElement("LINE", "Such as it is; and for mine own poor part,"), new XElement("LINE", "Look you, I'll go pray.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "These are but wild and whirling words, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I'm sorry they offend you, heartily;"), new XElement("LINE", "Yes, 'faith heartily.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "There's no offence, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Yes, by Saint Patrick, but there is, Horatio,"), new XElement("LINE", "And much offence too. Touching this vision here,"), new XElement("LINE", "It is an honest ghost, that let me tell you:"), new XElement("LINE", "For your desire to know what is between us,"), new XElement("LINE", "O'ermaster 't as you may. And now, good friends,"), new XElement("LINE", "As you are friends, scholars and soldiers,"), new XElement("LINE", "Give me one poor request.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What is't, my lord? we will.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Never make known what you have seen to-night.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "My lord, we will not.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, but swear't.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "In faith,"), new XElement("LINE", "My lord, not I.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Nor I, my lord, in faith.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Upon my sword.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "We have sworn, my lord, already.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Indeed, upon my sword, indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", new XElement("STAGEDIR", "Beneath"), " Swear." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ah, ha, boy! say'st thou so? art thou there,"), new XElement("LINE", "truepenny?"), new XElement("LINE", "Come on--you hear this fellow in the cellarage--"), new XElement("LINE", "Consent to swear.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Propose the oath, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Never to speak of this that you have seen,"), new XElement("LINE", "Swear by my sword.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", new XElement("STAGEDIR", "Beneath"), " Swear." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Hic et ubique? then we'll shift our ground."), new XElement("LINE", "Come hither, gentlemen,"), new XElement("LINE", "And lay your hands again upon my sword:"), new XElement("LINE", "Never to speak of this that you have heard,"), new XElement("LINE", "Swear by my sword.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", new XElement("STAGEDIR", "Beneath"), " Swear." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Well said, old mole! canst work i' the earth so fast?"), new XElement("LINE", "A worthy pioner! Once more remove, good friends.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "O day and night, but this is wondrous strange!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "And therefore as a stranger give it welcome."), new XElement("LINE", "There are more things in heaven and earth, Horatio,"), new XElement("LINE", "Than are dreamt of in your philosophy. But come;"), new XElement("LINE", "Here, as before, never, so help you mercy,"), new XElement("LINE", "How strange or odd soe'er I bear myself,"), new XElement("LINE", "As I perchance hereafter shall think meet"), new XElement("LINE", "To put an antic disposition on,"), new XElement("LINE", "That you, at such times seeing me, never shall,"), new XElement("LINE", "With arms encumber'd thus, or this headshake,"), new XElement("LINE", "Or by pronouncing of some doubtful phrase,"), new XElement("LINE", "As 'Well, well, we know,' or 'We could, an if we would,'"), new XElement("LINE", "Or 'If we list to speak,' or 'There be, an if they might,'"), new XElement("LINE", "Or such ambiguous giving out, to note"), new XElement("LINE", "That you know aught of me: this not to do,"), new XElement("LINE", "So grace and mercy at your most need help you, Swear.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", new XElement("STAGEDIR", "Beneath"), " Swear." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Rest, rest, perturbed spirit!"), new XElement("STAGEDIR", "They swear"), new XElement("LINE", "So, gentlemen,"), new XElement("LINE", "With all my love I do commend me to you:"), new XElement("LINE", "And what so poor a man as Hamlet is"), new XElement("LINE", "May do, to express his love and friending to you,"), new XElement("LINE", "God willing, shall not lack. Let us go in together;"), new XElement("LINE", "And still your fingers on your lips, I pray."), new XElement("LINE", "The time is out of joint: O cursed spite,"), new XElement("LINE", "That ever I was born to set it right!"), new XElement("LINE", "Nay, come, let's go together.") ), new XElement("STAGEDIR", "Exeunt") ) ), new XElement("ACT", new XElement("TITLE", "ACT II"), new XElement("SCENE", new XElement("TITLE", "SCENE I. A room in POLONIUS' house."), new XElement("STAGEDIR", "Enter POLONIUS and REYNALDO"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Give him this money and these notes, Reynaldo.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "I will, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "You shall do marvellous wisely, good Reynaldo,"), new XElement("LINE", "Before you visit him, to make inquire"), new XElement("LINE", "Of his behavior.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "My lord, I did intend it.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Marry, well said; very well said. Look you, sir,"), new XElement("LINE", "Inquire me first what Danskers are in Paris;"), new XElement("LINE", "And how, and who, what means, and where they keep,"), new XElement("LINE", "What company, at what expense; and finding"), new XElement("LINE", "By this encompassment and drift of question"), new XElement("LINE", "That they do know my son, come you more nearer"), new XElement("LINE", "Than your particular demands will touch it:"), new XElement("LINE", "Take you, as 'twere, some distant knowledge of him;"), new XElement("LINE", "As thus, 'I know his father and his friends,"), new XElement("LINE", "And in part him: ' do you mark this, Reynaldo?") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "Ay, very well, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "'And in part him; but' you may say 'not well:"), new XElement("LINE", "But, if't be he I mean, he's very wild;"), new XElement("LINE", "Addicted so and so:' and there put on him"), new XElement("LINE", "What forgeries you please; marry, none so rank"), new XElement("LINE", "As may dishonour him; take heed of that;"), new XElement("LINE", "But, sir, such wanton, wild and usual slips"), new XElement("LINE", "As are companions noted and most known"), new XElement("LINE", "To youth and liberty.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "As gaming, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Ay, or drinking, fencing, swearing, quarrelling,"), new XElement("LINE", "Drabbing: you may go so far.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "My lord, that would dishonour him.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "'Faith, no; as you may season it in the charge"), new XElement("LINE", "You must not put another scandal on him,"), new XElement("LINE", "That he is open to incontinency;"), new XElement("LINE", "That's not my meaning: but breathe his faults so quaintly"), new XElement("LINE", "That they may seem the taints of liberty,"), new XElement("LINE", "The flash and outbreak of a fiery mind,"), new XElement("LINE", "A savageness in unreclaimed blood,"), new XElement("LINE", "Of general assault.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "But, my good lord,--") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Wherefore should you do this?") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "Ay, my lord,"), new XElement("LINE", "I would know that.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Marry, sir, here's my drift;"), new XElement("LINE", "And I believe, it is a fetch of wit:"), new XElement("LINE", "You laying these slight sullies on my son,"), new XElement("LINE", "As 'twere a thing a little soil'd i' the working, Mark you,"), new XElement("LINE", "Your party in converse, him you would sound,"), new XElement("LINE", "Having ever seen in the prenominate crimes"), new XElement("LINE", "The youth you breathe of guilty, be assured"), new XElement("LINE", "He closes with you in this consequence;"), new XElement("LINE", "'Good sir,' or so, or 'friend,' or 'gentleman,'"), new XElement("LINE", "According to the phrase or the addition"), new XElement("LINE", "Of man and country.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "Very good, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "And then, sir, does he this--he does--what was I"), new XElement("LINE", "about to say? By the mass, I was about to say"), new XElement("LINE", "something: where did I leave?") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "At 'closes in the consequence,' at 'friend or so,'"), new XElement("LINE", "and 'gentleman.'") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "At 'closes in the consequence,' ay, marry;"), new XElement("LINE", "He closes thus: 'I know the gentleman;"), new XElement("LINE", "I saw him yesterday, or t' other day,"), new XElement("LINE", "Or then, or then; with such, or such; and, as you say,"), new XElement("LINE", "There was a' gaming; there o'ertook in's rouse;"), new XElement("LINE", "There falling out at tennis:' or perchance,"), new XElement("LINE", "'I saw him enter such a house of sale,'"), new XElement("LINE", "Videlicet, a brothel, or so forth."), new XElement("LINE", "See you now;"), new XElement("LINE", "Your bait of falsehood takes this carp of truth:"), new XElement("LINE", "And thus do we of wisdom and of reach,"), new XElement("LINE", "With windlasses and with assays of bias,"), new XElement("LINE", "By indirections find directions out:"), new XElement("LINE", "So by my former lecture and advice,"), new XElement("LINE", "Shall you my son. You have me, have you not?") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "My lord, I have.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "God be wi' you; fare you well.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "Good my lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Observe his inclination in yourself.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "I shall, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "And let him ply his music.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "Well, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Farewell!"), new XElement("STAGEDIR", "Exit REYNALDO"), new XElement("STAGEDIR", "Enter OPHELIA"), new XElement("LINE", "How now, Ophelia! what's the matter?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "O, my lord, my lord, I have been so affrighted!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "With what, i' the name of God?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My lord, as I was sewing in my closet,"), new XElement("LINE", "Lord Hamlet, with his doublet all unbraced;"), new XElement("LINE", "No hat upon his head; his stockings foul'd,"), new XElement("LINE", "Ungarter'd, and down-gyved to his ancle;"), new XElement("LINE", "Pale as his shirt; his knees knocking each other;"), new XElement("LINE", "And with a look so piteous in purport"), new XElement("LINE", "As if he had been loosed out of hell"), new XElement("LINE", "To speak of horrors,--he comes before me.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Mad for thy love?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My lord, I do not know;"), new XElement("LINE", "But truly, I do fear it.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What said he?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "He took me by the wrist and held me hard;"), new XElement("LINE", "Then goes he to the length of all his arm;"), new XElement("LINE", "And, with his other hand thus o'er his brow,"), new XElement("LINE", "He falls to such perusal of my face"), new XElement("LINE", "As he would draw it. Long stay'd he so;"), new XElement("LINE", "At last, a little shaking of mine arm"), new XElement("LINE", "And thrice his head thus waving up and down,"), new XElement("LINE", "He raised a sigh so piteous and profound"), new XElement("LINE", "As it did seem to shatter all his bulk"), new XElement("LINE", "And end his being: that done, he lets me go:"), new XElement("LINE", "And, with his head over his shoulder turn'd,"), new XElement("LINE", "He seem'd to find his way without his eyes;"), new XElement("LINE", "For out o' doors he went without their helps,"), new XElement("LINE", "And, to the last, bended their light on me.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Come, go with me: I will go seek the king."), new XElement("LINE", "This is the very ecstasy of love,"), new XElement("LINE", "Whose violent property fordoes itself"), new XElement("LINE", "And leads the will to desperate undertakings"), new XElement("LINE", "As oft as any passion under heaven"), new XElement("LINE", "That does afflict our natures. I am sorry."), new XElement("LINE", "What, have you given him any hard words of late?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "No, my good lord, but, as you did command,"), new XElement("LINE", "I did repel his fetters and denied"), new XElement("LINE", "His access to me.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "That hath made him mad."), new XElement("LINE", "I am sorry that with better heed and judgment"), new XElement("LINE", "I had not quoted him: I fear'd he did but trifle,"), new XElement("LINE", "And meant to wreck thee; but, beshrew my jealousy!"), new XElement("LINE", "By heaven, it is as proper to our age"), new XElement("LINE", "To cast beyond ourselves in our opinions"), new XElement("LINE", "As it is common for the younger sort"), new XElement("LINE", "To lack discretion. Come, go we to the king:"), new XElement("LINE", "This must be known; which, being kept close, might"), new XElement("LINE", "move"), new XElement("LINE", "More grief to hide than hate to utter love.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE II. A room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, QUEEN GERTRUDE, ROSENCRANTZ,\n" + "GUILDENSTERN, and Attendants" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Welcome, dear Rosencrantz and Guildenstern!"), new XElement("LINE", "Moreover that we much did long to see you,"), new XElement("LINE", "The need we have to use you did provoke"), new XElement("LINE", "Our hasty sending. Something have you heard"), new XElement("LINE", "Of Hamlet's transformation; so call it,"), new XElement("LINE", "Sith nor the exterior nor the inward man"), new XElement("LINE", "Resembles that it was. What it should be,"), new XElement("LINE", "More than his father's death, that thus hath put him"), new XElement("LINE", "So much from the understanding of himself,"), new XElement("LINE", "I cannot dream of: I entreat you both,"), new XElement("LINE", "That, being of so young days brought up with him,"), new XElement("LINE", "And sith so neighbour'd to his youth and havior,"), new XElement("LINE", "That you vouchsafe your rest here in our court"), new XElement("LINE", "Some little time: so by your companies"), new XElement("LINE", "To draw him on to pleasures, and to gather,"), new XElement("LINE", "So much as from occasion you may glean,"), new XElement("LINE", "Whether aught, to us unknown, afflicts him thus,"), new XElement("LINE", "That, open'd, lies within our remedy.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Good gentlemen, he hath much talk'd of you;"), new XElement("LINE", "And sure I am two men there are not living"), new XElement("LINE", "To whom he more adheres. If it will please you"), new XElement("LINE", "To show us so much gentry and good will"), new XElement("LINE", "As to expend your time with us awhile,"), new XElement("LINE", "For the supply and profit of our hope,"), new XElement("LINE", "Your visitation shall receive such thanks"), new XElement("LINE", "As fits a king's remembrance.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Both your majesties"), new XElement("LINE", "Might, by the sovereign power you have of us,"), new XElement("LINE", "Put your dread pleasures more into command"), new XElement("LINE", "Than to entreaty.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "But we both obey,"), new XElement("LINE", "And here give up ourselves, in the full bent"), new XElement("LINE", "To lay our service freely at your feet,"), new XElement("LINE", "To be commanded.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Thanks, Rosencrantz and gentle Guildenstern.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Thanks, Guildenstern and gentle Rosencrantz:"), new XElement("LINE", "And I beseech you instantly to visit"), new XElement("LINE", "My too much changed son. Go, some of you,"), new XElement("LINE", "And bring these gentlemen where Hamlet is.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Heavens make our presence and our practises"), new XElement("LINE", "Pleasant and helpful to him!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Ay, amen!") ), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ, GUILDENSTERN, and some\n" + "Attendants" ), new XElement("STAGEDIR", "Enter POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "The ambassadors from Norway, my good lord,"), new XElement("LINE", "Are joyfully return'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Thou still hast been the father of good news.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Have I, my lord? I assure my good liege,"), new XElement("LINE", "I hold my duty, as I hold my soul,"), new XElement("LINE", "Both to my God and to my gracious king:"), new XElement("LINE", "And I do think, or else this brain of mine"), new XElement("LINE", "Hunts not the trail of policy so sure"), new XElement("LINE", "As it hath used to do, that I have found"), new XElement("LINE", "The very cause of Hamlet's lunacy.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O, speak of that; that do I long to hear.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Give first admittance to the ambassadors;"), new XElement("LINE", "My news shall be the fruit to that great feast.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Thyself do grace to them, and bring them in."), new XElement("STAGEDIR", "Exit POLONIUS"), new XElement("LINE", "He tells me, my dear Gertrude, he hath found"), new XElement("LINE", "The head and source of all your son's distemper.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "I doubt it is no other but the main;"), new XElement("LINE", "His father's death, and our o'erhasty marriage.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Well, we shall sift him."), new XElement("STAGEDIR", "Re-enter POLONIUS, with VOLTIMAND and CORNELIUS"), new XElement("LINE", "Welcome, my good friends!"), new XElement("LINE", "Say, Voltimand, what from our brother Norway?") ), new XElement("SPEECH", new XElement("SPEAKER", "VOLTIMAND"), new XElement("LINE", "Most fair return of greetings and desires."), new XElement("LINE", "Upon our first, he sent out to suppress"), new XElement("LINE", "His nephew's levies; which to him appear'd"), new XElement("LINE", "To be a preparation 'gainst the Polack;"), new XElement("LINE", "But, better look'd into, he truly found"), new XElement("LINE", "It was against your highness: whereat grieved,"), new XElement("LINE", "That so his sickness, age and impotence"), new XElement("LINE", "Was falsely borne in hand, sends out arrests"), new XElement("LINE", "On Fortinbras; which he, in brief, obeys;"), new XElement("LINE", "Receives rebuke from Norway, and in fine"), new XElement("LINE", "Makes vow before his uncle never more"), new XElement("LINE", "To give the assay of arms against your majesty."), new XElement("LINE", "Whereon old Norway, overcome with joy,"), new XElement("LINE", "Gives him three thousand crowns in annual fee,"), new XElement("LINE", "And his commission to employ those soldiers,"), new XElement("LINE", "So levied as before, against the Polack:"), new XElement("LINE", "With an entreaty, herein further shown,"), new XElement("STAGEDIR", "Giving a paper"), new XElement("LINE", "That it might please you to give quiet pass"), new XElement("LINE", "Through your dominions for this enterprise,"), new XElement("LINE", "On such regards of safety and allowance"), new XElement("LINE", "As therein are set down.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "It likes us well;"), new XElement("LINE", "And at our more consider'd time well read,"), new XElement("LINE", "Answer, and think upon this business."), new XElement("LINE", "Meantime we thank you for your well-took labour:"), new XElement("LINE", "Go to your rest; at night we'll feast together:"), new XElement("LINE", "Most welcome home!") ), new XElement("STAGEDIR", "Exeunt VOLTIMAND and CORNELIUS"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "This business is well ended."), new XElement("LINE", "My liege, and madam, to expostulate"), new XElement("LINE", "What majesty should be, what duty is,"), new XElement("LINE", "Why day is day, night night, and time is time,"), new XElement("LINE", "Were nothing but to waste night, day and time."), new XElement("LINE", "Therefore, since brevity is the soul of wit,"), new XElement("LINE", "And tediousness the limbs and outward flourishes,"), new XElement("LINE", "I will be brief: your noble son is mad:"), new XElement("LINE", "Mad call I it; for, to define true madness,"), new XElement("LINE", "What is't but to be nothing else but mad?"), new XElement("LINE", "But let that go.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "More matter, with less art.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Madam, I swear I use no art at all."), new XElement("LINE", "That he is mad, 'tis true: 'tis true 'tis pity;"), new XElement("LINE", "And pity 'tis 'tis true: a foolish figure;"), new XElement("LINE", "But farewell it, for I will use no art."), new XElement("LINE", "Mad let us grant him, then: and now remains"), new XElement("LINE", "That we find out the cause of this effect,"), new XElement("LINE", "Or rather say, the cause of this defect,"), new XElement("LINE", "For this effect defective comes by cause:"), new XElement("LINE", "Thus it remains, and the remainder thus. Perpend."), new XElement("LINE", "I have a daughter--have while she is mine--"), new XElement("LINE", "Who, in her duty and obedience, mark,"), new XElement("LINE", "Hath given me this: now gather, and surmise."), new XElement("STAGEDIR", "Reads"), new XElement("LINE", "'To the celestial and my soul's idol, the most"), new XElement("LINE", "beautified Ophelia,'--"), new XElement("LINE", "That's an ill phrase, a vile phrase; 'beautified' is"), new XElement("LINE", "a vile phrase: but you shall hear. Thus:"), new XElement("STAGEDIR", "Reads"), new XElement("LINE", "'In her excellent white bosom, these, &c.'") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Came this from Hamlet to her?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Good madam, stay awhile; I will be faithful."), new XElement("STAGEDIR", "Reads"), new XElement("LINE", "'Doubt thou the stars are fire;"), new XElement("LINE", "Doubt that the sun doth move;"), new XElement("LINE", "Doubt truth to be a liar;"), new XElement("LINE", "But never doubt I love."), new XElement("LINE", "'O dear Ophelia, I am ill at these numbers;"), new XElement("LINE", "I have not art to reckon my groans: but that"), new XElement("LINE", "I love thee best, O most best, believe it. Adieu."), new XElement("LINE", "'Thine evermore most dear lady, whilst"), new XElement("LINE", "this machine is to him, HAMLET.'"), new XElement("LINE", "This, in obedience, hath my daughter shown me,"), new XElement("LINE", "And more above, hath his solicitings,"), new XElement("LINE", "As they fell out by time, by means and place,"), new XElement("LINE", "All given to mine ear.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "But how hath she"), new XElement("LINE", "Received his love?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What do you think of me?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "As of a man faithful and honourable.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I would fain prove so. But what might you think,"), new XElement("LINE", "When I had seen this hot love on the wing--"), new XElement("LINE", "As I perceived it, I must tell you that,"), new XElement("LINE", "Before my daughter told me--what might you,"), new XElement("LINE", "Or my dear majesty your queen here, think,"), new XElement("LINE", "If I had play'd the desk or table-book,"), new XElement("LINE", "Or given my heart a winking, mute and dumb,"), new XElement("LINE", "Or look'd upon this love with idle sight;"), new XElement("LINE", "What might you think? No, I went round to work,"), new XElement("LINE", "And my young mistress thus I did bespeak:"), new XElement("LINE", "'Lord Hamlet is a prince, out of thy star;"), new XElement("LINE", "This must not be:' and then I precepts gave her,"), new XElement("LINE", "That she should lock herself from his resort,"), new XElement("LINE", "Admit no messengers, receive no tokens."), new XElement("LINE", "Which done, she took the fruits of my advice;"), new XElement("LINE", "And he, repulsed--a short tale to make--"), new XElement("LINE", "Fell into a sadness, then into a fast,"), new XElement("LINE", "Thence to a watch, thence into a weakness,"), new XElement("LINE", "Thence to a lightness, and, by this declension,"), new XElement("LINE", "Into the madness wherein now he raves,"), new XElement("LINE", "And all we mourn for.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Do you think 'tis this?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "It may be, very likely.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Hath there been such a time--I'd fain know that--"), new XElement("LINE", "That I have positively said 'Tis so,'"), new XElement("LINE", "When it proved otherwise?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Not that I know.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Pointing to his head and shoulder") ), new XElement("LINE", "Take this from this, if this be otherwise:"), new XElement("LINE", "If circumstances lead me, I will find"), new XElement("LINE", "Where truth is hid, though it were hid indeed"), new XElement("LINE", "Within the centre.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "How may we try it further?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "You know, sometimes he walks four hours together"), new XElement("LINE", "Here in the lobby.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "So he does indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "At such a time I'll loose my daughter to him:"), new XElement("LINE", "Be you and I behind an arras then;"), new XElement("LINE", "Mark the encounter: if he love her not"), new XElement("LINE", "And be not from his reason fall'n thereon,"), new XElement("LINE", "Let me be no assistant for a state,"), new XElement("LINE", "But keep a farm and carters.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "We will try it.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "But, look, where sadly the poor wretch comes reading.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Away, I do beseech you, both away:"), new XElement("LINE", "I'll board him presently."), new XElement("STAGEDIR", "Exeunt KING CLAUDIUS, QUEEN GERTRUDE, and\n" + "Attendants" ), new XElement("STAGEDIR", "Enter HAMLET, reading"), new XElement("LINE", "O, give me leave:"), new XElement("LINE", "How does my good Lord Hamlet?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Well, God-a-mercy.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Do you know me, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Excellent well; you are a fishmonger.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Not I, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then I would you were so honest a man.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Honest, my lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, sir; to be honest, as this world goes, is to be"), new XElement("LINE", "one man picked out of ten thousand.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "That's very true, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "For if the sun breed maggots in a dead dog, being a"), new XElement("LINE", "god kissing carrion,--Have you a daughter?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I have, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Let her not walk i' the sun: conception is a"), new XElement("LINE", "blessing: but not as your daughter may conceive."), new XElement("LINE", "Friend, look to 't.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " How say you by that? Still harping on my" ), new XElement("LINE", "daughter: yet he knew me not at first; he said I"), new XElement("LINE", "was a fishmonger: he is far gone, far gone: and"), new XElement("LINE", "truly in my youth I suffered much extremity for"), new XElement("LINE", "love; very near this. I'll speak to him again."), new XElement("LINE", "What do you read, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Words, words, words.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What is the matter, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Between who?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I mean, the matter that you read, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Slanders, sir: for the satirical rogue says here"), new XElement("LINE", "that old men have grey beards, that their faces are"), new XElement("LINE", "wrinkled, their eyes purging thick amber and"), new XElement("LINE", "plum-tree gum and that they have a plentiful lack of"), new XElement("LINE", "wit, together with most weak hams: all which, sir,"), new XElement("LINE", "though I most powerfully and potently believe, yet"), new XElement("LINE", "I hold it not honesty to have it thus set down, for"), new XElement("LINE", "yourself, sir, should be old as I am, if like a crab"), new XElement("LINE", "you could go backward.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " Though this be madness, yet there is method" ), new XElement("LINE", "in 't. Will you walk out of the air, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Into my grave.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Indeed, that is out o' the air."), new XElement("STAGEDIR", "Aside"), new XElement("LINE", "How pregnant sometimes his replies are! a happiness"), new XElement("LINE", "that often madness hits on, which reason and sanity"), new XElement("LINE", "could not so prosperously be delivered of. I will"), new XElement("LINE", "leave him, and suddenly contrive the means of"), new XElement("LINE", "meeting between him and my daughter.--My honourable"), new XElement("LINE", "lord, I will most humbly take my leave of you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "You cannot, sir, take from me any thing that I will"), new XElement("LINE", "more willingly part withal: except my life, except"), new XElement("LINE", "my life, except my life.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Fare you well, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "These tedious old fools!") ), new XElement("STAGEDIR", "Enter ROSENCRANTZ and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "You go to seek the Lord Hamlet; there he is.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", new XElement("STAGEDIR", "To POLONIUS"), " God save you, sir!" ) ), new XElement("STAGEDIR", "Exit POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "My honoured lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "My most dear lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "My excellent good friends! How dost thou,"), new XElement("LINE", "Guildenstern? Ah, Rosencrantz! Good lads, how do ye both?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "As the indifferent children of the earth.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Happy, in that we are not over-happy;"), new XElement("LINE", "On fortune's cap we are not the very button.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nor the soles of her shoe?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Neither, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then you live about her waist, or in the middle of"), new XElement("LINE", "her favours?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "'Faith, her privates we.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "In the secret parts of fortune? O, most true; she"), new XElement("LINE", "is a strumpet. What's the news?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "None, my lord, but that the world's grown honest.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then is doomsday near: but your news is not true."), new XElement("LINE", "Let me question more in particular: what have you,"), new XElement("LINE", "my good friends, deserved at the hands of fortune,"), new XElement("LINE", "that she sends you to prison hither?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Prison, my lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Denmark's a prison.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Then is the world one.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A goodly one; in which there are many confines,"), new XElement("LINE", "wards and dungeons, Denmark being one o' the worst.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "We think not so, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, then, 'tis none to you; for there is nothing"), new XElement("LINE", "either good or bad, but thinking makes it so: to me"), new XElement("LINE", "it is a prison.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Why then, your ambition makes it one; 'tis too"), new XElement("LINE", "narrow for your mind.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O God, I could be bounded in a nut shell and count"), new XElement("LINE", "myself a king of infinite space, were it not that I"), new XElement("LINE", "have bad dreams.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Which dreams indeed are ambition, for the very"), new XElement("LINE", "substance of the ambitious is merely the shadow of a dream.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A dream itself is but a shadow.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Truly, and I hold ambition of so airy and light a"), new XElement("LINE", "quality that it is but a shadow's shadow.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then are our beggars bodies, and our monarchs and"), new XElement("LINE", "outstretched heroes the beggars' shadows. Shall we"), new XElement("LINE", "to the court? for, by my fay, I cannot reason.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "We'll wait upon you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No such matter: I will not sort you with the rest"), new XElement("LINE", "of my servants, for, to speak to you like an honest"), new XElement("LINE", "man, I am most dreadfully attended. But, in the"), new XElement("LINE", "beaten way of friendship, what make you at Elsinore?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "To visit you, my lord; no other occasion.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Beggar that I am, I am even poor in thanks; but I"), new XElement("LINE", "thank you: and sure, dear friends, my thanks are"), new XElement("LINE", "too dear a halfpenny. Were you not sent for? Is it"), new XElement("LINE", "your own inclining? Is it a free visitation? Come,"), new XElement("LINE", "deal justly with me: come, come; nay, speak.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "What should we say, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, any thing, but to the purpose. You were sent"), new XElement("LINE", "for; and there is a kind of confession in your looks"), new XElement("LINE", "which your modesties have not craft enough to colour:"), new XElement("LINE", "I know the good king and queen have sent for you.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "To what end, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That you must teach me. But let me conjure you, by"), new XElement("LINE", "the rights of our fellowship, by the consonancy of"), new XElement("LINE", "our youth, by the obligation of our ever-preserved"), new XElement("LINE", "love, and by what more dear a better proposer could"), new XElement("LINE", "charge you withal, be even and direct with me,"), new XElement("LINE", "whether you were sent for, or no?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", new XElement("STAGEDIR", "Aside to GUILDENSTERN"), " What say you?" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " Nay, then, I have an eye of you.--If you" ), new XElement("LINE", "love me, hold not off.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "My lord, we were sent for.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I will tell you why; so shall my anticipation"), new XElement("LINE", "prevent your discovery, and your secrecy to the king"), new XElement("LINE", "and queen moult no feather. I have of late--but"), new XElement("LINE", "wherefore I know not--lost all my mirth, forgone all"), new XElement("LINE", "custom of exercises; and indeed it goes so heavily"), new XElement("LINE", "with my disposition that this goodly frame, the"), new XElement("LINE", "earth, seems to me a sterile promontory, this most"), new XElement("LINE", "excellent canopy, the air, look you, this brave"), new XElement("LINE", "o'erhanging firmament, this majestical roof fretted"), new XElement("LINE", "with golden fire, why, it appears no other thing to"), new XElement("LINE", "me than a foul and pestilent congregation of vapours."), new XElement("LINE", "What a piece of work is a man! how noble in reason!"), new XElement("LINE", "how infinite in faculty! in form and moving how"), new XElement("LINE", "express and admirable! in action how like an angel!"), new XElement("LINE", "in apprehension how like a god! the beauty of the"), new XElement("LINE", "world! the paragon of animals! And yet, to me,"), new XElement("LINE", "what is this quintessence of dust? man delights not"), new XElement("LINE", "me: no, nor woman neither, though by your smiling"), new XElement("LINE", "you seem to say so.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "My lord, there was no such stuff in my thoughts.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why did you laugh then, when I said 'man delights not me'?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "To think, my lord, if you delight not in man, what"), new XElement("LINE", "lenten entertainment the players shall receive from"), new XElement("LINE", "you: we coted them on the way; and hither are they"), new XElement("LINE", "coming, to offer you service.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "He that plays the king shall be welcome; his majesty"), new XElement("LINE", "shall have tribute of me; the adventurous knight"), new XElement("LINE", "shall use his foil and target; the lover shall not"), new XElement("LINE", "sigh gratis; the humourous man shall end his part"), new XElement("LINE", "in peace; the clown shall make those laugh whose"), new XElement("LINE", "lungs are tickled o' the sere; and the lady shall"), new XElement("LINE", "say her mind freely, or the blank verse shall halt"), new XElement("LINE", "for't. What players are they?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Even those you were wont to take delight in, the"), new XElement("LINE", "tragedians of the city.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How chances it they travel? their residence, both"), new XElement("LINE", "in reputation and profit, was better both ways.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "I think their inhibition comes by the means of the"), new XElement("LINE", "late innovation.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do they hold the same estimation they did when I was"), new XElement("LINE", "in the city? are they so followed?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "No, indeed, are they not.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How comes it? do they grow rusty?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Nay, their endeavour keeps in the wonted pace: but"), new XElement("LINE", "there is, sir, an aery of children, little eyases,"), new XElement("LINE", "that cry out on the top of question, and are most"), new XElement("LINE", "tyrannically clapped for't: these are now the"), new XElement("LINE", "fashion, and so berattle the common stages--so they"), new XElement("LINE", "call them--that many wearing rapiers are afraid of"), new XElement("LINE", "goose-quills and dare scarce come thither.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What, are they children? who maintains 'em? how are"), new XElement("LINE", "they escoted? Will they pursue the quality no"), new XElement("LINE", "longer than they can sing? will they not say"), new XElement("LINE", "afterwards, if they should grow themselves to common"), new XElement("LINE", "players--as it is most like, if their means are no"), new XElement("LINE", "better--their writers do them wrong, to make them"), new XElement("LINE", "exclaim against their own succession?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "'Faith, there has been much to do on both sides; and"), new XElement("LINE", "the nation holds it no sin to tarre them to"), new XElement("LINE", "controversy: there was, for a while, no money bid"), new XElement("LINE", "for argument, unless the poet and the player went to"), new XElement("LINE", "cuffs in the question.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Is't possible?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "O, there has been much throwing about of brains.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do the boys carry it away?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Ay, that they do, my lord; Hercules and his load too.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It is not very strange; for mine uncle is king of"), new XElement("LINE", "Denmark, and those that would make mows at him while"), new XElement("LINE", "my father lived, give twenty, forty, fifty, an"), new XElement("LINE", "hundred ducats a-piece for his picture in little."), new XElement("LINE", "'Sblood, there is something in this more than"), new XElement("LINE", "natural, if philosophy could find it out.") ), new XElement("STAGEDIR", "Flourish of trumpets within"), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "There are the players.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Gentlemen, you are welcome to Elsinore. Your hands,"), new XElement("LINE", "come then: the appurtenance of welcome is fashion"), new XElement("LINE", "and ceremony: let me comply with you in this garb,"), new XElement("LINE", "lest my extent to the players, which, I tell you,"), new XElement("LINE", "must show fairly outward, should more appear like"), new XElement("LINE", "entertainment than yours. You are welcome: but my"), new XElement("LINE", "uncle-father and aunt-mother are deceived.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "In what, my dear lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am but mad north-north-west: when the wind is"), new XElement("LINE", "southerly I know a hawk from a handsaw.") ), new XElement("STAGEDIR", "Enter POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Well be with you, gentlemen!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Hark you, Guildenstern; and you too: at each ear a"), new XElement("LINE", "hearer: that great baby you see there is not yet"), new XElement("LINE", "out of his swaddling-clouts.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Happily he's the second time come to them; for they"), new XElement("LINE", "say an old man is twice a child.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I will prophesy he comes to tell me of the players;"), new XElement("LINE", "mark it. You say right, sir: o' Monday morning;"), new XElement("LINE", "'twas so indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "My lord, I have news to tell you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "My lord, I have news to tell you."), new XElement("LINE", "When Roscius was an actor in Rome,--") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "The actors are come hither, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Buz, buz!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Upon mine honour,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then came each actor on his ass,--") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "The best actors in the world, either for tragedy,"), new XElement("LINE", "comedy, history, pastoral, pastoral-comical,"), new XElement("LINE", "historical-pastoral, tragical-historical, tragical-"), new XElement("LINE", "comical-historical-pastoral, scene individable, or"), new XElement("LINE", "poem unlimited: Seneca cannot be too heavy, nor"), new XElement("LINE", "Plautus too light. For the law of writ and the"), new XElement("LINE", "liberty, these are the only men.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O Jephthah, judge of Israel, what a treasure hadst thou!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What a treasure had he, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why,"), new XElement("LINE", "'One fair daughter and no more,"), new XElement("LINE", "The which he loved passing well.'") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " Still on my daughter." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Am I not i' the right, old Jephthah?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "If you call me Jephthah, my lord, I have a daughter"), new XElement("LINE", "that I love passing well.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, that follows not.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What follows, then, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why,"), new XElement("LINE", "'As by lot, God wot,'"), new XElement("LINE", "and then, you know,"), new XElement("LINE", "'It came to pass, as most like it was,'--"), new XElement("LINE", "the first row of the pious chanson will show you"), new XElement("LINE", "more; for look, where my abridgement comes."), new XElement("STAGEDIR", "Enter four or five Players"), new XElement("LINE", "You are welcome, masters; welcome, all. I am glad"), new XElement("LINE", "to see thee well. Welcome, good friends. O, my old"), new XElement("LINE", "friend! thy face is valenced since I saw thee last:"), new XElement("LINE", "comest thou to beard me in Denmark? What, my young"), new XElement("LINE", "lady and mistress! By'r lady, your ladyship is"), new XElement("LINE", "nearer to heaven than when I saw you last, by the"), new XElement("LINE", "altitude of a chopine. Pray God, your voice, like"), new XElement("LINE", "apiece of uncurrent gold, be not cracked within the"), new XElement("LINE", "ring. Masters, you are all welcome. We'll e'en"), new XElement("LINE", "to't like French falconers, fly at any thing we see:"), new XElement("LINE", "we'll have a speech straight: come, give us a taste"), new XElement("LINE", "of your quality; come, a passionate speech.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "What speech, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I heard thee speak me a speech once, but it was"), new XElement("LINE", "never acted; or, if it was, not above once; for the"), new XElement("LINE", "play, I remember, pleased not the million; 'twas"), new XElement("LINE", "caviare to the general: but it was--as I received"), new XElement("LINE", "it, and others, whose judgments in such matters"), new XElement("LINE", "cried in the top of mine--an excellent play, well"), new XElement("LINE", "digested in the scenes, set down with as much"), new XElement("LINE", "modesty as cunning. I remember, one said there"), new XElement("LINE", "were no sallets in the lines to make the matter"), new XElement("LINE", "savoury, nor no matter in the phrase that might"), new XElement("LINE", "indict the author of affectation; but called it an"), new XElement("LINE", "honest method, as wholesome as sweet, and by very"), new XElement("LINE", "much more handsome than fine. One speech in it I"), new XElement("LINE", "chiefly loved: 'twas Aeneas' tale to Dido; and"), new XElement("LINE", "thereabout of it especially, where he speaks of"), new XElement("LINE", "Priam's slaughter: if it live in your memory, begin"), new XElement("LINE", "at this line: let me see, let me see--"), new XElement("LINE", "'The rugged Pyrrhus, like the Hyrcanian beast,'--"), new XElement("LINE", "it is not so:--it begins with Pyrrhus:--"), new XElement("LINE", "'The rugged Pyrrhus, he whose sable arms,"), new XElement("LINE", "Black as his purpose, did the night resemble"), new XElement("LINE", "When he lay couched in the ominous horse,"), new XElement("LINE", "Hath now this dread and black complexion smear'd"), new XElement("LINE", "With heraldry more dismal; head to foot"), new XElement("LINE", "Now is he total gules; horridly trick'd"), new XElement("LINE", "With blood of fathers, mothers, daughters, sons,"), new XElement("LINE", "Baked and impasted with the parching streets,"), new XElement("LINE", "That lend a tyrannous and damned light"), new XElement("LINE", "To their lord's murder: roasted in wrath and fire,"), new XElement("LINE", "And thus o'er-sized with coagulate gore,"), new XElement("LINE", "With eyes like carbuncles, the hellish Pyrrhus"), new XElement("LINE", "Old grandsire Priam seeks.'"), new XElement("LINE", "So, proceed you.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "'Fore God, my lord, well spoken, with good accent and"), new XElement("LINE", "good discretion.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "'Anon he finds him"), new XElement("LINE", "Striking too short at Greeks; his antique sword,"), new XElement("LINE", "Rebellious to his arm, lies where it falls,"), new XElement("LINE", "Repugnant to command: unequal match'd,"), new XElement("LINE", "Pyrrhus at Priam drives; in rage strikes wide;"), new XElement("LINE", "But with the whiff and wind of his fell sword"), new XElement("LINE", "The unnerved father falls. Then senseless Ilium,"), new XElement("LINE", "Seeming to feel this blow, with flaming top"), new XElement("LINE", "Stoops to his base, and with a hideous crash"), new XElement("LINE", "Takes prisoner Pyrrhus' ear: for, lo! his sword,"), new XElement("LINE", "Which was declining on the milky head"), new XElement("LINE", "Of reverend Priam, seem'd i' the air to stick:"), new XElement("LINE", "So, as a painted tyrant, Pyrrhus stood,"), new XElement("LINE", "And like a neutral to his will and matter,"), new XElement("LINE", "Did nothing."), new XElement("LINE", "But, as we often see, against some storm,"), new XElement("LINE", "A silence in the heavens, the rack stand still,"), new XElement("LINE", "The bold winds speechless and the orb below"), new XElement("LINE", "As hush as death, anon the dreadful thunder"), new XElement("LINE", "Doth rend the region, so, after Pyrrhus' pause,"), new XElement("LINE", "Aroused vengeance sets him new a-work;"), new XElement("LINE", "And never did the Cyclops' hammers fall"), new XElement("LINE", "On Mars's armour forged for proof eterne"), new XElement("LINE", "With less remorse than Pyrrhus' bleeding sword"), new XElement("LINE", "Now falls on Priam."), new XElement("LINE", "Out, out, thou strumpet, Fortune! All you gods,"), new XElement("LINE", "In general synod 'take away her power;"), new XElement("LINE", "Break all the spokes and fellies from her wheel,"), new XElement("LINE", "And bowl the round nave down the hill of heaven,"), new XElement("LINE", "As low as to the fiends!'") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "This is too long.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It shall to the barber's, with your beard. Prithee,"), new XElement("LINE", "say on: he's for a jig or a tale of bawdry, or he"), new XElement("LINE", "sleeps: say on: come to Hecuba.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "'But who, O, who had seen the mobled queen--'") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'The mobled queen?'") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "That's good; 'mobled queen' is good.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "'Run barefoot up and down, threatening the flames"), new XElement("LINE", "With bisson rheum; a clout upon that head"), new XElement("LINE", "Where late the diadem stood, and for a robe,"), new XElement("LINE", "About her lank and all o'er-teemed loins,"), new XElement("LINE", "A blanket, in the alarm of fear caught up;"), new XElement("LINE", "Who this had seen, with tongue in venom steep'd,"), new XElement("LINE", "'Gainst Fortune's state would treason have"), new XElement("LINE", "pronounced:"), new XElement("LINE", "But if the gods themselves did see her then"), new XElement("LINE", "When she saw Pyrrhus make malicious sport"), new XElement("LINE", "In mincing with his sword her husband's limbs,"), new XElement("LINE", "The instant burst of clamour that she made,"), new XElement("LINE", "Unless things mortal move them not at all,"), new XElement("LINE", "Would have made milch the burning eyes of heaven,"), new XElement("LINE", "And passion in the gods.'") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Look, whether he has not turned his colour and has"), new XElement("LINE", "tears in's eyes. Pray you, no more.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Tis well: I'll have thee speak out the rest soon."), new XElement("LINE", "Good my lord, will you see the players well"), new XElement("LINE", "bestowed? Do you hear, let them be well used; for"), new XElement("LINE", "they are the abstract and brief chronicles of the"), new XElement("LINE", "time: after your death you were better have a bad"), new XElement("LINE", "epitaph than their ill report while you live.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "My lord, I will use them according to their desert.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "God's bodykins, man, much better: use every man"), new XElement("LINE", "after his desert, and who should 'scape whipping?"), new XElement("LINE", "Use them after your own honour and dignity: the less"), new XElement("LINE", "they deserve, the more merit is in your bounty."), new XElement("LINE", "Take them in.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Come, sirs.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Follow him, friends: we'll hear a play to-morrow."), new XElement("STAGEDIR", "Exit POLONIUS with all the Players but the First"), new XElement("LINE", "Dost thou hear me, old friend; can you play the"), new XElement("LINE", "Murder of Gonzago?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "Ay, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "We'll ha't to-morrow night. You could, for a need,"), new XElement("LINE", "study a speech of some dozen or sixteen lines, which"), new XElement("LINE", "I would set down and insert in't, could you not?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "Ay, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Very well. Follow that lord; and look you mock him"), new XElement("LINE", "not."), new XElement("STAGEDIR", "Exit First Player"), new XElement("LINE", "My good friends, I'll leave you till night: you are"), new XElement("LINE", "welcome to Elsinore.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Good my lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, so, God be wi' ye;"), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("LINE", "Now I am alone."), new XElement("LINE", "O, what a rogue and peasant slave am I!"), new XElement("LINE", "Is it not monstrous that this player here,"), new XElement("LINE", "But in a fiction, in a dream of passion,"), new XElement("LINE", "Could force his soul so to his own conceit"), new XElement("LINE", "That from her working all his visage wann'd,"), new XElement("LINE", "Tears in his eyes, distraction in's aspect,"), new XElement("LINE", "A broken voice, and his whole function suiting"), new XElement("LINE", "With forms to his conceit? and all for nothing!"), new XElement("LINE", "For Hecuba!"), new XElement("LINE", "What's Hecuba to him, or he to Hecuba,"), new XElement("LINE", "That he should weep for her? What would he do,"), new XElement("LINE", "Had he the motive and the cue for passion"), new XElement("LINE", "That I have? He would drown the stage with tears"), new XElement("LINE", "And cleave the general ear with horrid speech,"), new XElement("LINE", "Make mad the guilty and appal the free,"), new XElement("LINE", "Confound the ignorant, and amaze indeed"), new XElement("LINE", "The very faculties of eyes and ears. Yet I,"), new XElement("LINE", "A dull and muddy-mettled rascal, peak,"), new XElement("LINE", "Like John-a-dreams, unpregnant of my cause,"), new XElement("LINE", "And can say nothing; no, not for a king,"), new XElement("LINE", "Upon whose property and most dear life"), new XElement("LINE", "A damn'd defeat was made. Am I a coward?"), new XElement("LINE", "Who calls me villain? breaks my pate across?"), new XElement("LINE", "Plucks off my beard, and blows it in my face?"), new XElement("LINE", "Tweaks me by the nose? gives me the lie i' the throat,"), new XElement("LINE", "As deep as to the lungs? who does me this?"), new XElement("LINE", "Ha!"), new XElement("LINE", "'Swounds, I should take it: for it cannot be"), new XElement("LINE", "But I am pigeon-liver'd and lack gall"), new XElement("LINE", "To make oppression bitter, or ere this"), new XElement("LINE", "I should have fatted all the region kites"), new XElement("LINE", "With this slave's offal: bloody, bawdy villain!"), new XElement("LINE", "Remorseless, treacherous, lecherous, kindless villain!"), new XElement("LINE", "O, vengeance!"), new XElement("LINE", "Why, what an ass am I! This is most brave,"), new XElement("LINE", "That I, the son of a dear father murder'd,"), new XElement("LINE", "Prompted to my revenge by heaven and hell,"), new XElement("LINE", "Must, like a whore, unpack my heart with words,"), new XElement("LINE", "And fall a-cursing, like a very drab,"), new XElement("LINE", "A scullion!"), new XElement("LINE", "Fie upon't! foh! About, my brain! I have heard"), new XElement("LINE", "That guilty creatures sitting at a play"), new XElement("LINE", "Have by the very cunning of the scene"), new XElement("LINE", "Been struck so to the soul that presently"), new XElement("LINE", "They have proclaim'd their malefactions;"), new XElement("LINE", "For murder, though it have no tongue, will speak"), new XElement("LINE", "With most miraculous organ. I'll have these players"), new XElement("LINE", "Play something like the murder of my father"), new XElement("LINE", "Before mine uncle: I'll observe his looks;"), new XElement("LINE", "I'll tent him to the quick: if he but blench,"), new XElement("LINE", "I know my course. The spirit that I have seen"), new XElement("LINE", "May be the devil: and the devil hath power"), new XElement("LINE", "To assume a pleasing shape; yea, and perhaps"), new XElement("LINE", "Out of my weakness and my melancholy,"), new XElement("LINE", "As he is very potent with such spirits,"), new XElement("LINE", "Abuses me to damn me: I'll have grounds"), new XElement("LINE", "More relative than this: the play 's the thing"), new XElement("LINE", "Wherein I'll catch the conscience of the king.") ), new XElement("STAGEDIR", "Exit") ) ), new XElement("ACT", new XElement("TITLE", "ACT III"), new XElement("SCENE", new XElement("TITLE", "SCENE I. A room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, QUEEN GERTRUDE, POLONIUS,\n" + "OPHELIA, ROSENCRANTZ, and GUILDENSTERN" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "And can you, by no drift of circumstance,"), new XElement("LINE", "Get from him why he puts on this confusion,"), new XElement("LINE", "Grating so harshly all his days of quiet"), new XElement("LINE", "With turbulent and dangerous lunacy?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "He does confess he feels himself distracted;"), new XElement("LINE", "But from what cause he will by no means speak.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Nor do we find him forward to be sounded,"), new XElement("LINE", "But, with a crafty madness, keeps aloof,"), new XElement("LINE", "When we would bring him on to some confession"), new XElement("LINE", "Of his true state.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Did he receive you well?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Most like a gentleman.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "But with much forcing of his disposition.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Niggard of question; but, of our demands,"), new XElement("LINE", "Most free in his reply.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Did you assay him?"), new XElement("LINE", "To any pastime?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Madam, it so fell out, that certain players"), new XElement("LINE", "We o'er-raught on the way: of these we told him;"), new XElement("LINE", "And there did seem in him a kind of joy"), new XElement("LINE", "To hear of it: they are about the court,"), new XElement("LINE", "And, as I think, they have already order"), new XElement("LINE", "This night to play before him.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "'Tis most true:"), new XElement("LINE", "And he beseech'd me to entreat your majesties"), new XElement("LINE", "To hear and see the matter.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "With all my heart; and it doth much content me"), new XElement("LINE", "To hear him so inclined."), new XElement("LINE", "Good gentlemen, give him a further edge,"), new XElement("LINE", "And drive his purpose on to these delights.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "We shall, my lord.") ), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Sweet Gertrude, leave us too;"), new XElement("LINE", "For we have closely sent for Hamlet hither,"), new XElement("LINE", "That he, as 'twere by accident, may here"), new XElement("LINE", "Affront Ophelia:"), new XElement("LINE", "Her father and myself, lawful espials,"), new XElement("LINE", "Will so bestow ourselves that, seeing, unseen,"), new XElement("LINE", "We may of their encounter frankly judge,"), new XElement("LINE", "And gather by him, as he is behaved,"), new XElement("LINE", "If 't be the affliction of his love or no"), new XElement("LINE", "That thus he suffers for.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "I shall obey you."), new XElement("LINE", "And for your part, Ophelia, I do wish"), new XElement("LINE", "That your good beauties be the happy cause"), new XElement("LINE", "Of Hamlet's wildness: so shall I hope your virtues"), new XElement("LINE", "Will bring him to his wonted way again,"), new XElement("LINE", "To both your honours.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Madam, I wish it may.") ), new XElement("STAGEDIR", "Exit QUEEN GERTRUDE"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Ophelia, walk you here. Gracious, so please you,"), new XElement("LINE", "We will bestow ourselves."), new XElement("STAGEDIR", "To OPHELIA"), new XElement("LINE", "Read on this book;"), new XElement("LINE", "That show of such an exercise may colour"), new XElement("LINE", "Your loneliness. We are oft to blame in this,--"), new XElement("LINE", "'Tis too much proved--that with devotion's visage"), new XElement("LINE", "And pious action we do sugar o'er"), new XElement("LINE", "The devil himself.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " O, 'tis too true!" ), new XElement("LINE", "How smart a lash that speech doth give my conscience!"), new XElement("LINE", "The harlot's cheek, beautied with plastering art,"), new XElement("LINE", "Is not more ugly to the thing that helps it"), new XElement("LINE", "Than is my deed to my most painted word:"), new XElement("LINE", "O heavy burthen!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I hear him coming: let's withdraw, my lord.") ), new XElement("STAGEDIR", "Exeunt KING CLAUDIUS and POLONIUS"), new XElement("STAGEDIR", "Enter HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "To be, or not to be: that is the question:"), new XElement("LINE", "Whether 'tis nobler in the mind to suffer"), new XElement("LINE", "The slings and arrows of outrageous fortune,"), new XElement("LINE", "Or to take arms against a sea of troubles,"), new XElement("LINE", "And by opposing end them? To die: to sleep;"), new XElement("LINE", "No more; and by a sleep to say we end"), new XElement("LINE", "The heart-ache and the thousand natural shocks"), new XElement("LINE", "That flesh is heir to, 'tis a consummation"), new XElement("LINE", "Devoutly to be wish'd. To die, to sleep;"), new XElement("LINE", "To sleep: perchance to dream: ay, there's the rub;"), new XElement("LINE", "For in that sleep of death what dreams may come"), new XElement("LINE", "When we have shuffled off this mortal coil,"), new XElement("LINE", "Must give us pause: there's the respect"), new XElement("LINE", "That makes calamity of so long life;"), new XElement("LINE", "For who would bear the whips and scorns of time,"), new XElement("LINE", "The oppressor's wrong, the proud man's contumely,"), new XElement("LINE", "The pangs of despised love, the law's delay,"), new XElement("LINE", "The insolence of office and the spurns"), new XElement("LINE", "That patient merit of the unworthy takes,"), new XElement("LINE", "When he himself might his quietus make"), new XElement("LINE", "With a bare bodkin? who would fardels bear,"), new XElement("LINE", "To grunt and sweat under a weary life,"), new XElement("LINE", "But that the dread of something after death,"), new XElement("LINE", "The undiscover'd country from whose bourn"), new XElement("LINE", "No traveller returns, puzzles the will"), new XElement("LINE", "And makes us rather bear those ills we have"), new XElement("LINE", "Than fly to others that we know not of?"), new XElement("LINE", "Thus conscience does make cowards of us all;"), new XElement("LINE", "And thus the native hue of resolution"), new XElement("LINE", "Is sicklied o'er with the pale cast of thought,"), new XElement("LINE", "And enterprises of great pith and moment"), new XElement("LINE", "With this regard their currents turn awry,"), new XElement("LINE", "And lose the name of action.--Soft you now!"), new XElement("LINE", "The fair Ophelia! Nymph, in thy orisons"), new XElement("LINE", "Be all my sins remember'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Good my lord,"), new XElement("LINE", "How does your honour for this many a day?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I humbly thank you; well, well, well.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My lord, I have remembrances of yours,"), new XElement("LINE", "That I have longed long to re-deliver;"), new XElement("LINE", "I pray you, now receive them.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, not I;"), new XElement("LINE", "I never gave you aught.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My honour'd lord, you know right well you did;"), new XElement("LINE", "And, with them, words of so sweet breath composed"), new XElement("LINE", "As made the things more rich: their perfume lost,"), new XElement("LINE", "Take these again; for to the noble mind"), new XElement("LINE", "Rich gifts wax poor when givers prove unkind."), new XElement("LINE", "There, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ha, ha! are you honest?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Are you fair?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "What means your lordship?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That if you be honest and fair, your honesty should"), new XElement("LINE", "admit no discourse to your beauty.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Could beauty, my lord, have better commerce than"), new XElement("LINE", "with honesty?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, truly; for the power of beauty will sooner"), new XElement("LINE", "transform honesty from what it is to a bawd than the"), new XElement("LINE", "force of honesty can translate beauty into his"), new XElement("LINE", "likeness: this was sometime a paradox, but now the"), new XElement("LINE", "time gives it proof. I did love you once.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Indeed, my lord, you made me believe so.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "You should not have believed me; for virtue cannot"), new XElement("LINE", "so inoculate our old stock but we shall relish of"), new XElement("LINE", "it: I loved you not.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I was the more deceived.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Get thee to a nunnery: why wouldst thou be a"), new XElement("LINE", "breeder of sinners? I am myself indifferent honest;"), new XElement("LINE", "but yet I could accuse me of such things that it"), new XElement("LINE", "were better my mother had not borne me: I am very"), new XElement("LINE", "proud, revengeful, ambitious, with more offences at"), new XElement("LINE", "my beck than I have thoughts to put them in,"), new XElement("LINE", "imagination to give them shape, or time to act them"), new XElement("LINE", "in. What should such fellows as I do crawling"), new XElement("LINE", "between earth and heaven? We are arrant knaves,"), new XElement("LINE", "all; believe none of us. Go thy ways to a nunnery."), new XElement("LINE", "Where's your father?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "At home, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Let the doors be shut upon him, that he may play the"), new XElement("LINE", "fool no where but in's own house. Farewell.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "O, help him, you sweet heavens!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "If thou dost marry, I'll give thee this plague for"), new XElement("LINE", "thy dowry: be thou as chaste as ice, as pure as"), new XElement("LINE", "snow, thou shalt not escape calumny. Get thee to a"), new XElement("LINE", "nunnery, go: farewell. Or, if thou wilt needs"), new XElement("LINE", "marry, marry a fool; for wise men know well enough"), new XElement("LINE", "what monsters you make of them. To a nunnery, go,"), new XElement("LINE", "and quickly too. Farewell.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "O heavenly powers, restore him!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I have heard of your paintings too, well enough; God"), new XElement("LINE", "has given you one face, and you make yourselves"), new XElement("LINE", "another: you jig, you amble, and you lisp, and"), new XElement("LINE", "nick-name God's creatures, and make your wantonness"), new XElement("LINE", "your ignorance. Go to, I'll no more on't; it hath"), new XElement("LINE", "made me mad. I say, we will have no more marriages:"), new XElement("LINE", "those that are married already, all but one, shall"), new XElement("LINE", "live; the rest shall keep as they are. To a"), new XElement("LINE", "nunnery, go.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "O, what a noble mind is here o'erthrown!"), new XElement("LINE", "The courtier's, soldier's, scholar's, eye, tongue, sword;"), new XElement("LINE", "The expectancy and rose of the fair state,"), new XElement("LINE", "The glass of fashion and the mould of form,"), new XElement("LINE", "The observed of all observers, quite, quite down!"), new XElement("LINE", "And I, of ladies most deject and wretched,"), new XElement("LINE", "That suck'd the honey of his music vows,"), new XElement("LINE", "Now see that noble and most sovereign reason,"), new XElement("LINE", "Like sweet bells jangled, out of tune and harsh;"), new XElement("LINE", "That unmatch'd form and feature of blown youth"), new XElement("LINE", "Blasted with ecstasy: O, woe is me,"), new XElement("LINE", "To have seen what I have seen, see what I see!") ), new XElement("STAGEDIR", "Re-enter KING CLAUDIUS and POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Love! his affections do not that way tend;"), new XElement("LINE", "Nor what he spake, though it lack'd form a little,"), new XElement("LINE", "Was not like madness. There's something in his soul,"), new XElement("LINE", "O'er which his melancholy sits on brood;"), new XElement("LINE", "And I do doubt the hatch and the disclose"), new XElement("LINE", "Will be some danger: which for to prevent,"), new XElement("LINE", "I have in quick determination"), new XElement("LINE", "Thus set it down: he shall with speed to England,"), new XElement("LINE", "For the demand of our neglected tribute"), new XElement("LINE", "Haply the seas and countries different"), new XElement("LINE", "With variable objects shall expel"), new XElement("LINE", "This something-settled matter in his heart,"), new XElement("LINE", "Whereon his brains still beating puts him thus"), new XElement("LINE", "From fashion of himself. What think you on't?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "It shall do well: but yet do I believe"), new XElement("LINE", "The origin and commencement of his grief"), new XElement("LINE", "Sprung from neglected love. How now, Ophelia!"), new XElement("LINE", "You need not tell us what Lord Hamlet said;"), new XElement("LINE", "We heard it all. My lord, do as you please;"), new XElement("LINE", "But, if you hold it fit, after the play"), new XElement("LINE", "Let his queen mother all alone entreat him"), new XElement("LINE", "To show his grief: let her be round with him;"), new XElement("LINE", "And I'll be placed, so please you, in the ear"), new XElement("LINE", "Of all their conference. If she find him not,"), new XElement("LINE", "To England send him, or confine him where"), new XElement("LINE", "Your wisdom best shall think.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "It shall be so:"), new XElement("LINE", "Madness in great ones must not unwatch'd go.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE II. A hall in the castle."), new XElement("STAGEDIR", "Enter HAMLET and Players"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Speak the speech, I pray you, as I pronounced it to"), new XElement("LINE", "you, trippingly on the tongue: but if you mouth it,"), new XElement("LINE", "as many of your players do, I had as lief the"), new XElement("LINE", "town-crier spoke my lines. Nor do not saw the air"), new XElement("LINE", "too much with your hand, thus, but use all gently;"), new XElement("LINE", "for in the very torrent, tempest, and, as I may say,"), new XElement("LINE", "the whirlwind of passion, you must acquire and beget"), new XElement("LINE", "a temperance that may give it smoothness. O, it"), new XElement("LINE", "offends me to the soul to hear a robustious"), new XElement("LINE", "periwig-pated fellow tear a passion to tatters, to"), new XElement("LINE", "very rags, to split the ears of the groundlings, who"), new XElement("LINE", "for the most part are capable of nothing but"), new XElement("LINE", "inexplicable dumbshows and noise: I would have such"), new XElement("LINE", "a fellow whipped for o'erdoing Termagant; it"), new XElement("LINE", "out-herods Herod: pray you, avoid it.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "I warrant your honour.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Be not too tame neither, but let your own discretion"), new XElement("LINE", "be your tutor: suit the action to the word, the"), new XElement("LINE", "word to the action; with this special o'erstep not"), new XElement("LINE", "the modesty of nature: for any thing so overdone is"), new XElement("LINE", "from the purpose of playing, whose end, both at the"), new XElement("LINE", "first and now, was and is, to hold, as 'twere, the"), new XElement("LINE", "mirror up to nature; to show virtue her own feature,"), new XElement("LINE", "scorn her own image, and the very age and body of"), new XElement("LINE", "the time his form and pressure. Now this overdone,"), new XElement("LINE", "or come tardy off, though it make the unskilful"), new XElement("LINE", "laugh, cannot but make the judicious grieve; the"), new XElement("LINE", "censure of the which one must in your allowance"), new XElement("LINE", "o'erweigh a whole theatre of others. O, there be"), new XElement("LINE", "players that I have seen play, and heard others"), new XElement("LINE", "praise, and that highly, not to speak it profanely,"), new XElement("LINE", "that, neither having the accent of Christians nor"), new XElement("LINE", "the gait of Christian, pagan, nor man, have so"), new XElement("LINE", "strutted and bellowed that I have thought some of"), new XElement("LINE", "nature's journeymen had made men and not made them"), new XElement("LINE", "well, they imitated humanity so abominably.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "I hope we have reformed that indifferently with us,"), new XElement("LINE", "sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, reform it altogether. And let those that play"), new XElement("LINE", "your clowns speak no more than is set down for them;"), new XElement("LINE", "for there be of them that will themselves laugh, to"), new XElement("LINE", "set on some quantity of barren spectators to laugh"), new XElement("LINE", "too; though, in the mean time, some necessary"), new XElement("LINE", "question of the play be then to be considered:"), new XElement("LINE", "that's villanous, and shows a most pitiful ambition"), new XElement("LINE", "in the fool that uses it. Go, make you ready."), new XElement("STAGEDIR", "Exeunt Players"), new XElement("STAGEDIR", "Enter POLONIUS, ROSENCRANTZ, and GUILDENSTERN"), new XElement("LINE", "How now, my lord! I will the king hear this piece of work?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "And the queen too, and that presently.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Bid the players make haste."), new XElement("STAGEDIR", "Exit POLONIUS"), new XElement("LINE", "Will you two help to hasten them?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "We will, my lord.") ), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What ho! Horatio!") ), new XElement("STAGEDIR", "Enter HORATIO"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Here, sweet lord, at your service.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Horatio, thou art e'en as just a man"), new XElement("LINE", "As e'er my conversation coped withal.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "O, my dear lord,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, do not think I flatter;"), new XElement("LINE", "For what advancement may I hope from thee"), new XElement("LINE", "That no revenue hast but thy good spirits,"), new XElement("LINE", "To feed and clothe thee? Why should the poor be flatter'd?"), new XElement("LINE", "No, let the candied tongue lick absurd pomp,"), new XElement("LINE", "And crook the pregnant hinges of the knee"), new XElement("LINE", "Where thrift may follow fawning. Dost thou hear?"), new XElement("LINE", "Since my dear soul was mistress of her choice"), new XElement("LINE", "And could of men distinguish, her election"), new XElement("LINE", "Hath seal'd thee for herself; for thou hast been"), new XElement("LINE", "As one, in suffering all, that suffers nothing,"), new XElement("LINE", "A man that fortune's buffets and rewards"), new XElement("LINE", "Hast ta'en with equal thanks: and blest are those"), new XElement("LINE", "Whose blood and judgment are so well commingled,"), new XElement("LINE", "That they are not a pipe for fortune's finger"), new XElement("LINE", "To sound what stop she please. Give me that man"), new XElement("LINE", "That is not passion's slave, and I will wear him"), new XElement("LINE", "In my heart's core, ay, in my heart of heart,"), new XElement("LINE", "As I do thee.--Something too much of this.--"), new XElement("LINE", "There is a play to-night before the king;"), new XElement("LINE", "One scene of it comes near the circumstance"), new XElement("LINE", "Which I have told thee of my father's death:"), new XElement("LINE", "I prithee, when thou seest that act afoot,"), new XElement("LINE", "Even with the very comment of thy soul"), new XElement("LINE", "Observe mine uncle: if his occulted guilt"), new XElement("LINE", "Do not itself unkennel in one speech,"), new XElement("LINE", "It is a damned ghost that we have seen,"), new XElement("LINE", "And my imaginations are as foul"), new XElement("LINE", "As Vulcan's stithy. Give him heedful note;"), new XElement("LINE", "For I mine eyes will rivet to his face,"), new XElement("LINE", "And after we will both our judgments join"), new XElement("LINE", "In censure of his seeming.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Well, my lord:"), new XElement("LINE", "If he steal aught the whilst this play is playing,"), new XElement("LINE", "And 'scape detecting, I will pay the theft.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "They are coming to the play; I must be idle:"), new XElement("LINE", "Get you a place.") ), new XElement("STAGEDIR", "Danish march. A flourish. Enter KING CLAUDIUS,\n" + "QUEEN GERTRUDE, POLONIUS, OPHELIA, ROSENCRANTZ,\n" + "GUILDENSTERN, and others" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "How fares our cousin Hamlet?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Excellent, i' faith; of the chameleon's dish: I eat"), new XElement("LINE", "the air, promise-crammed: you cannot feed capons so.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I have nothing with this answer, Hamlet; these words"), new XElement("LINE", "are not mine.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, nor mine now."), new XElement("STAGEDIR", "To POLONIUS"), new XElement("LINE", "My lord, you played once i' the university, you say?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "That did I, my lord; and was accounted a good actor.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What did you enact?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I did enact Julius Caesar: I was killed i' the"), new XElement("LINE", "Capitol; Brutus killed me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It was a brute part of him to kill so capital a calf"), new XElement("LINE", "there. Be the players ready?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Ay, my lord; they stay upon your patience.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Come hither, my dear Hamlet, sit by me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, good mother, here's metal more attractive.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "To KING CLAUDIUS"), " O, ho! do you mark that?" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Lady, shall I lie in your lap?") ), new XElement("STAGEDIR", "Lying down at OPHELIA's feet"), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "No, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I mean, my head upon your lap?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Ay, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do you think I meant country matters?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I think nothing, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That's a fair thought to lie between maids' legs.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "What is, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nothing.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "You are merry, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Who, I?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Ay, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O God, your only jig-maker. What should a man do"), new XElement("LINE", "but be merry? for, look you, how cheerfully my"), new XElement("LINE", "mother looks, and my father died within these two hours.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Nay, 'tis twice two months, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "So long? Nay then, let the devil wear black, for"), new XElement("LINE", "I'll have a suit of sables. O heavens! die two"), new XElement("LINE", "months ago, and not forgotten yet? Then there's"), new XElement("LINE", "hope a great man's memory may outlive his life half"), new XElement("LINE", "a year: but, by'r lady, he must build churches,"), new XElement("LINE", "then; or else shall he suffer not thinking on, with"), new XElement("LINE", "the hobby-horse, whose epitaph is 'For, O, for, O,"), new XElement("LINE", "the hobby-horse is forgot.'"), new XElement("STAGEDIR", "Hautboys play. The dumb-show enters") ), new XElement("STAGEDIR", "Enter a King and a Queen very lovingly; the Queen\n" + "embracing him, and he her. She kneels, and makes\n" + "show of protestation unto him. He takes her up,\n" + "and declines his head upon her neck: lays him down\n" + "upon a bank of flowers: she, seeing him asleep,\n" + "leaves him. Anon comes in a fellow, takes off his\n" + "crown, kisses it, and pours poison in the King's\n" + "ears, and exit. The Queen returns; finds the King\n" + "dead, and makes passionate action. The Poisoner,\n" + "with some two or three Mutes, comes in again,\n" + "seeming to lament with her. The dead body is\n" + "carried away. The Poisoner wooes the Queen with\n" + "gifts: she seems loath and unwilling awhile, but\n" + "in the end accepts his love" ), new XElement("STAGEDIR", "Exeunt"), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "What means this, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Marry, this is miching mallecho; it means mischief.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Belike this show imports the argument of the play.") ), new XElement("STAGEDIR", "Enter Prologue"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "We shall know by this fellow: the players cannot"), new XElement("LINE", "keep counsel; they'll tell all.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Will he tell us what this show meant?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, or any show that you'll show him: be not you"), new XElement("LINE", "ashamed to show, he'll not shame to tell you what it means.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "You are naught, you are naught: I'll mark the play.") ), new XElement("SPEECH", new XElement("SPEAKER", "Prologue"), new XElement("LINE", "For us, and for our tragedy,"), new XElement("LINE", "Here stooping to your clemency,"), new XElement("LINE", "We beg your hearing patiently.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Is this a prologue, or the posy of a ring?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "'Tis brief, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "As woman's love.") ), new XElement("STAGEDIR", "Enter two Players, King and Queen"), new XElement("SPEECH", new XElement("SPEAKER", "Player King"), new XElement("LINE", "Full thirty times hath Phoebus' cart gone round"), new XElement("LINE", "Neptune's salt wash and Tellus' orbed ground,"), new XElement("LINE", "And thirty dozen moons with borrow'd sheen"), new XElement("LINE", "About the world have times twelve thirties been,"), new XElement("LINE", "Since love our hearts and Hymen did our hands"), new XElement("LINE", "Unite commutual in most sacred bands.") ), new XElement("SPEECH", new XElement("SPEAKER", "Player Queen"), new XElement("LINE", "So many journeys may the sun and moon"), new XElement("LINE", "Make us again count o'er ere love be done!"), new XElement("LINE", "But, woe is me, you are so sick of late,"), new XElement("LINE", "So far from cheer and from your former state,"), new XElement("LINE", "That I distrust you. Yet, though I distrust,"), new XElement("LINE", "Discomfort you, my lord, it nothing must:"), new XElement("LINE", "For women's fear and love holds quantity;"), new XElement("LINE", "In neither aught, or in extremity."), new XElement("LINE", "Now, what my love is, proof hath made you know;"), new XElement("LINE", "And as my love is sized, my fear is so:"), new XElement("LINE", "Where love is great, the littlest doubts are fear;"), new XElement("LINE", "Where little fears grow great, great love grows there.") ), new XElement("SPEECH", new XElement("SPEAKER", "Player King"), new XElement("LINE", "'Faith, I must leave thee, love, and shortly too;"), new XElement("LINE", "My operant powers their functions leave to do:"), new XElement("LINE", "And thou shalt live in this fair world behind,"), new XElement("LINE", "Honour'd, beloved; and haply one as kind"), new XElement("LINE", "For husband shalt thou--") ), new XElement("SPEECH", new XElement("SPEAKER", "Player Queen"), new XElement("LINE", "O, confound the rest!"), new XElement("LINE", "Such love must needs be treason in my breast:"), new XElement("LINE", "In second husband let me be accurst!"), new XElement("LINE", "None wed the second but who kill'd the first.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " Wormwood, wormwood." ) ), new XElement("SPEECH", new XElement("SPEAKER", "Player Queen"), new XElement("LINE", "The instances that second marriage move"), new XElement("LINE", "Are base respects of thrift, but none of love:"), new XElement("LINE", "A second time I kill my husband dead,"), new XElement("LINE", "When second husband kisses me in bed.") ), new XElement("SPEECH", new XElement("SPEAKER", "Player King"), new XElement("LINE", "I do believe you think what now you speak;"), new XElement("LINE", "But what we do determine oft we break."), new XElement("LINE", "Purpose is but the slave to memory,"), new XElement("LINE", "Of violent birth, but poor validity;"), new XElement("LINE", "Which now, like fruit unripe, sticks on the tree;"), new XElement("LINE", "But fall, unshaken, when they mellow be."), new XElement("LINE", "Most necessary 'tis that we forget"), new XElement("LINE", "To pay ourselves what to ourselves is debt:"), new XElement("LINE", "What to ourselves in passion we propose,"), new XElement("LINE", "The passion ending, doth the purpose lose."), new XElement("LINE", "The violence of either grief or joy"), new XElement("LINE", "Their own enactures with themselves destroy:"), new XElement("LINE", "Where joy most revels, grief doth most lament;"), new XElement("LINE", "Grief joys, joy grieves, on slender accident."), new XElement("LINE", "This world is not for aye, nor 'tis not strange"), new XElement("LINE", "That even our loves should with our fortunes change;"), new XElement("LINE", "For 'tis a question left us yet to prove,"), new XElement("LINE", "Whether love lead fortune, or else fortune love."), new XElement("LINE", "The great man down, you mark his favourite flies;"), new XElement("LINE", "The poor advanced makes friends of enemies."), new XElement("LINE", "And hitherto doth love on fortune tend;"), new XElement("LINE", "For who not needs shall never lack a friend,"), new XElement("LINE", "And who in want a hollow friend doth try,"), new XElement("LINE", "Directly seasons him his enemy."), new XElement("LINE", "But, orderly to end where I begun,"), new XElement("LINE", "Our wills and fates do so contrary run"), new XElement("LINE", "That our devices still are overthrown;"), new XElement("LINE", "Our thoughts are ours, their ends none of our own:"), new XElement("LINE", "So think thou wilt no second husband wed;"), new XElement("LINE", "But die thy thoughts when thy first lord is dead.") ), new XElement("SPEECH", new XElement("SPEAKER", "Player Queen"), new XElement("LINE", "Nor earth to me give food, nor heaven light!"), new XElement("LINE", "Sport and repose lock from me day and night!"), new XElement("LINE", "To desperation turn my trust and hope!"), new XElement("LINE", "An anchor's cheer in prison be my scope!"), new XElement("LINE", "Each opposite that blanks the face of joy"), new XElement("LINE", "Meet what I would have well and it destroy!"), new XElement("LINE", "Both here and hence pursue me lasting strife,"), new XElement("LINE", "If, once a widow, ever I be wife!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "If she should break it now!") ), new XElement("SPEECH", new XElement("SPEAKER", "Player King"), new XElement("LINE", "'Tis deeply sworn. Sweet, leave me here awhile;"), new XElement("LINE", "My spirits grow dull, and fain I would beguile"), new XElement("LINE", "The tedious day with sleep.") ), new XElement("STAGEDIR", "Sleeps"), new XElement("SPEECH", new XElement("SPEAKER", "Player Queen"), new XElement("LINE", "Sleep rock thy brain,"), new XElement("LINE", "And never come mischance between us twain!") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Madam, how like you this play?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "The lady protests too much, methinks.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, but she'll keep her word.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Have you heard the argument? Is there no offence in 't?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, no, they do but jest, poison in jest; no offence"), new XElement("LINE", "i' the world.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "What do you call the play?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The Mouse-trap. Marry, how? Tropically. This play"), new XElement("LINE", "is the image of a murder done in Vienna: Gonzago is"), new XElement("LINE", "the duke's name; his wife, Baptista: you shall see"), new XElement("LINE", "anon; 'tis a knavish piece of work: but what o'"), new XElement("LINE", "that? your majesty and we that have free souls, it"), new XElement("LINE", "touches us not: let the galled jade wince, our"), new XElement("LINE", "withers are unwrung."), new XElement("STAGEDIR", "Enter LUCIANUS"), new XElement("LINE", "This is one Lucianus, nephew to the king.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "You are as good as a chorus, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I could interpret between you and your love, if I"), new XElement("LINE", "could see the puppets dallying.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "You are keen, my lord, you are keen.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It would cost you a groaning to take off my edge.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Still better, and worse.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "So you must take your husbands. Begin, murderer;"), new XElement("LINE", "pox, leave thy damnable faces, and begin. Come:"), new XElement("LINE", "'the croaking raven doth bellow for revenge.'") ), new XElement("SPEECH", new XElement("SPEAKER", "LUCIANUS"), new XElement("LINE", "Thoughts black, hands apt, drugs fit, and time agreeing;"), new XElement("LINE", "Confederate season, else no creature seeing;"), new XElement("LINE", "Thou mixture rank, of midnight weeds collected,"), new XElement("LINE", "With Hecate's ban thrice blasted, thrice infected,"), new XElement("LINE", "Thy natural magic and dire property,"), new XElement("LINE", "On wholesome life usurp immediately.") ), new XElement("STAGEDIR", "Pours the poison into the sleeper's ears"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "He poisons him i' the garden for's estate. His"), new XElement("LINE", "name's Gonzago: the story is extant, and writ in"), new XElement("LINE", "choice Italian: you shall see anon how the murderer"), new XElement("LINE", "gets the love of Gonzago's wife.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "The king rises.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What, frighted with false fire!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "How fares my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Give o'er the play.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Give me some light: away!") ), new XElement("SPEECH", new XElement("SPEAKER", "All"), new XElement("LINE", "Lights, lights, lights!") ), new XElement("STAGEDIR", "Exeunt all but HAMLET and HORATIO"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, let the stricken deer go weep,"), new XElement("LINE", "The hart ungalled play;"), new XElement("LINE", "For some must watch, while some must sleep:"), new XElement("LINE", "So runs the world away."), new XElement("LINE", "Would not this, sir, and a forest of feathers-- if"), new XElement("LINE", "the rest of my fortunes turn Turk with me--with two"), new XElement("LINE", "Provincial roses on my razed shoes, get me a"), new XElement("LINE", "fellowship in a cry of players, sir?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Half a share.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A whole one, I."), new XElement("LINE", "For thou dost know, O Damon dear,"), new XElement("LINE", "This realm dismantled was"), new XElement("LINE", "Of Jove himself; and now reigns here"), new XElement("LINE", "A very, very--pajock.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "You might have rhymed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O good Horatio, I'll take the ghost's word for a"), new XElement("LINE", "thousand pound. Didst perceive?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Very well, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Upon the talk of the poisoning?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I did very well note him.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ah, ha! Come, some music! come, the recorders!"), new XElement("LINE", "For if the king like not the comedy,"), new XElement("LINE", "Why then, belike, he likes it not, perdy."), new XElement("LINE", "Come, some music!") ), new XElement("STAGEDIR", "Re-enter ROSENCRANTZ and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Good my lord, vouchsafe me a word with you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, a whole history.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "The king, sir,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, sir, what of him?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Is in his retirement marvellous distempered.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "With drink, sir?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "No, my lord, rather with choler.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Your wisdom should show itself more richer to"), new XElement("LINE", "signify this to his doctor; for, for me to put him"), new XElement("LINE", "to his purgation would perhaps plunge him into far"), new XElement("LINE", "more choler.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Good my lord, put your discourse into some frame and"), new XElement("LINE", "start not so wildly from my affair.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am tame, sir: pronounce.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "The queen, your mother, in most great affliction of"), new XElement("LINE", "spirit, hath sent me to you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "You are welcome.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Nay, good my lord, this courtesy is not of the right"), new XElement("LINE", "breed. If it shall please you to make me a"), new XElement("LINE", "wholesome answer, I will do your mother's"), new XElement("LINE", "commandment: if not, your pardon and my return"), new XElement("LINE", "shall be the end of my business.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, I cannot.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "What, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Make you a wholesome answer; my wit's diseased: but,"), new XElement("LINE", "sir, such answer as I can make, you shall command;"), new XElement("LINE", "or, rather, as you say, my mother: therefore no"), new XElement("LINE", "more, but to the matter: my mother, you say,--") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Then thus she says; your behavior hath struck her"), new XElement("LINE", "into amazement and admiration.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O wonderful son, that can so astonish a mother! But"), new XElement("LINE", "is there no sequel at the heels of this mother's"), new XElement("LINE", "admiration? Impart.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "She desires to speak with you in her closet, ere you"), new XElement("LINE", "go to bed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "We shall obey, were she ten times our mother. Have"), new XElement("LINE", "you any further trade with us?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "My lord, you once did love me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "So I do still, by these pickers and stealers.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Good my lord, what is your cause of distemper? you"), new XElement("LINE", "do, surely, bar the door upon your own liberty, if"), new XElement("LINE", "you deny your griefs to your friend.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, I lack advancement.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "How can that be, when you have the voice of the king"), new XElement("LINE", "himself for your succession in Denmark?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, but sir, 'While the grass grows,'--the proverb"), new XElement("LINE", "is something musty."), new XElement("STAGEDIR", "Re-enter Players with recorders"), new XElement("LINE", "O, the recorders! let me see one. To withdraw with"), new XElement("LINE", "you:--why do you go about to recover the wind of me,"), new XElement("LINE", "as if you would drive me into a toil?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "O, my lord, if my duty be too bold, my love is too"), new XElement("LINE", "unmannerly.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I do not well understand that. Will you play upon"), new XElement("LINE", "this pipe?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "My lord, I cannot.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I pray you.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Believe me, I cannot.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I do beseech you.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "I know no touch of it, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Tis as easy as lying: govern these ventages with"), new XElement("LINE", "your lingers and thumb, give it breath with your"), new XElement("LINE", "mouth, and it will discourse most eloquent music."), new XElement("LINE", "Look you, these are the stops.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "But these cannot I command to any utterance of"), new XElement("LINE", "harmony; I have not the skill.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, look you now, how unworthy a thing you make of"), new XElement("LINE", "me! You would play upon me; you would seem to know"), new XElement("LINE", "my stops; you would pluck out the heart of my"), new XElement("LINE", "mystery; you would sound me from my lowest note to"), new XElement("LINE", "the top of my compass: and there is much music,"), new XElement("LINE", "excellent voice, in this little organ; yet cannot"), new XElement("LINE", "you make it speak. 'Sblood, do you think I am"), new XElement("LINE", "easier to be played on than a pipe? Call me what"), new XElement("LINE", "instrument you will, though you can fret me, yet you"), new XElement("LINE", "cannot play upon me."), new XElement("STAGEDIR", "Enter POLONIUS"), new XElement("LINE", "God bless you, sir!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "My lord, the queen would speak with you, and"), new XElement("LINE", "presently.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do you see yonder cloud that's almost in shape of a camel?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "By the mass, and 'tis like a camel, indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Methinks it is like a weasel.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "It is backed like a weasel.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Or like a whale?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Very like a whale.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then I will come to my mother by and by. They fool"), new XElement("LINE", "me to the top of my bent. I will come by and by.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I will say so.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "By and by is easily said."), new XElement("STAGEDIR", "Exit POLONIUS"), new XElement("LINE", "Leave me, friends."), new XElement("STAGEDIR", "Exeunt all but HAMLET"), new XElement("LINE", "Tis now the very witching time of night,"), new XElement("LINE", "When churchyards yawn and hell itself breathes out"), new XElement("LINE", "Contagion to this world: now could I drink hot blood,"), new XElement("LINE", "And do such bitter business as the day"), new XElement("LINE", "Would quake to look on. Soft! now to my mother."), new XElement("LINE", "O heart, lose not thy nature; let not ever"), new XElement("LINE", "The soul of Nero enter this firm bosom:"), new XElement("LINE", "Let me be cruel, not unnatural:"), new XElement("LINE", "I will speak daggers to her, but use none;"), new XElement("LINE", "My tongue and soul in this be hypocrites;"), new XElement("LINE", "How in my words soever she be shent,"), new XElement("LINE", "To give them seals never, my soul, consent!") ), new XElement("STAGEDIR", "Exit") ), new XElement("SCENE", new XElement("TITLE", "SCENE III. A room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, ROSENCRANTZ, and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I like him not, nor stands it safe with us"), new XElement("LINE", "To let his madness range. Therefore prepare you;"), new XElement("LINE", "I your commission will forthwith dispatch,"), new XElement("LINE", "And he to England shall along with you:"), new XElement("LINE", "The terms of our estate may not endure"), new XElement("LINE", "Hazard so dangerous as doth hourly grow"), new XElement("LINE", "Out of his lunacies.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "We will ourselves provide:"), new XElement("LINE", "Most holy and religious fear it is"), new XElement("LINE", "To keep those many many bodies safe"), new XElement("LINE", "That live and feed upon your majesty.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "The single and peculiar life is bound,"), new XElement("LINE", "With all the strength and armour of the mind,"), new XElement("LINE", "To keep itself from noyance; but much more"), new XElement("LINE", "That spirit upon whose weal depend and rest"), new XElement("LINE", "The lives of many. The cease of majesty"), new XElement("LINE", "Dies not alone; but, like a gulf, doth draw"), new XElement("LINE", "What's near it with it: it is a massy wheel,"), new XElement("LINE", "Fix'd on the summit of the highest mount,"), new XElement("LINE", "To whose huge spokes ten thousand lesser things"), new XElement("LINE", "Are mortised and adjoin'd; which, when it falls,"), new XElement("LINE", "Each small annexment, petty consequence,"), new XElement("LINE", "Attends the boisterous ruin. Never alone"), new XElement("LINE", "Did the king sigh, but with a general groan.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Arm you, I pray you, to this speedy voyage;"), new XElement("LINE", "For we will fetters put upon this fear,"), new XElement("LINE", "Which now goes too free-footed.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "We will haste us.") ), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("STAGEDIR", "Enter POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "My lord, he's going to his mother's closet:"), new XElement("LINE", "Behind the arras I'll convey myself,"), new XElement("LINE", "To hear the process; and warrant she'll tax him home:"), new XElement("LINE", "And, as you said, and wisely was it said,"), new XElement("LINE", "'Tis meet that some more audience than a mother,"), new XElement("LINE", "Since nature makes them partial, should o'erhear"), new XElement("LINE", "The speech, of vantage. Fare you well, my liege:"), new XElement("LINE", "I'll call upon you ere you go to bed,"), new XElement("LINE", "And tell you what I know.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Thanks, dear my lord."), new XElement("STAGEDIR", "Exit POLONIUS"), new XElement("LINE", "O, my offence is rank it smells to heaven;"), new XElement("LINE", "It hath the primal eldest curse upon't,"), new XElement("LINE", "A brother's murder. Pray can I not,"), new XElement("LINE", "Though inclination be as sharp as will:"), new XElement("LINE", "My stronger guilt defeats my strong intent;"), new XElement("LINE", "And, like a man to double business bound,"), new XElement("LINE", "I stand in pause where I shall first begin,"), new XElement("LINE", "And both neglect. What if this cursed hand"), new XElement("LINE", "Were thicker than itself with brother's blood,"), new XElement("LINE", "Is there not rain enough in the sweet heavens"), new XElement("LINE", "To wash it white as snow? Whereto serves mercy"), new XElement("LINE", "But to confront the visage of offence?"), new XElement("LINE", "And what's in prayer but this two-fold force,"), new XElement("LINE", "To be forestalled ere we come to fall,"), new XElement("LINE", "Or pardon'd being down? Then I'll look up;"), new XElement("LINE", "My fault is past. But, O, what form of prayer"), new XElement("LINE", "Can serve my turn? 'Forgive me my foul murder'?"), new XElement("LINE", "That cannot be; since I am still possess'd"), new XElement("LINE", "Of those effects for which I did the murder,"), new XElement("LINE", "My crown, mine own ambition and my queen."), new XElement("LINE", "May one be pardon'd and retain the offence?"), new XElement("LINE", "In the corrupted currents of this world"), new XElement("LINE", "Offence's gilded hand may shove by justice,"), new XElement("LINE", "And oft 'tis seen the wicked prize itself"), new XElement("LINE", "Buys out the law: but 'tis not so above;"), new XElement("LINE", "There is no shuffling, there the action lies"), new XElement("LINE", "In his true nature; and we ourselves compell'd,"), new XElement("LINE", "Even to the teeth and forehead of our faults,"), new XElement("LINE", "To give in evidence. What then? what rests?"), new XElement("LINE", "Try what repentance can: what can it not?"), new XElement("LINE", "Yet what can it when one can not repent?"), new XElement("LINE", "O wretched state! O bosom black as death!"), new XElement("LINE", "O limed soul, that, struggling to be free,"), new XElement("LINE", "Art more engaged! Help, angels! Make assay!"), new XElement("LINE", "Bow, stubborn knees; and, heart with strings of steel,"), new XElement("LINE", "Be soft as sinews of the newborn babe!"), new XElement("LINE", "All may be well.") ), new XElement("STAGEDIR", "Retires and kneels"), new XElement("STAGEDIR", "Enter HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Now might I do it pat, now he is praying;"), new XElement("LINE", "And now I'll do't. And so he goes to heaven;"), new XElement("LINE", "And so am I revenged. That would be scann'd:"), new XElement("LINE", "A villain kills my father; and for that,"), new XElement("LINE", "I, his sole son, do this same villain send"), new XElement("LINE", "To heaven."), new XElement("LINE", "O, this is hire and salary, not revenge."), new XElement("LINE", "He took my father grossly, full of bread;"), new XElement("LINE", "With all his crimes broad blown, as flush as May;"), new XElement("LINE", "And how his audit stands who knows save heaven?"), new XElement("LINE", "But in our circumstance and course of thought,"), new XElement("LINE", "'Tis heavy with him: and am I then revenged,"), new XElement("LINE", "To take him in the purging of his soul,"), new XElement("LINE", "When he is fit and season'd for his passage?"), new XElement("LINE", "No!"), new XElement("LINE", "Up, sword; and know thou a more horrid hent:"), new XElement("LINE", "When he is drunk asleep, or in his rage,"), new XElement("LINE", "Or in the incestuous pleasure of his bed;"), new XElement("LINE", "At gaming, swearing, or about some act"), new XElement("LINE", "That has no relish of salvation in't;"), new XElement("LINE", "Then trip him, that his heels may kick at heaven,"), new XElement("LINE", "And that his soul may be as damn'd and black"), new XElement("LINE", "As hell, whereto it goes. My mother stays:"), new XElement("LINE", "This physic but prolongs thy sickly days.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", new XElement("STAGEDIR", "Rising"), " My words fly up, my thoughts remain below:" ), new XElement("LINE", "Words without thoughts never to heaven go.") ), new XElement("STAGEDIR", "Exit") ), new XElement("SCENE", new XElement("TITLE", "SCENE IV. The Queen's closet."), new XElement("STAGEDIR", "Enter QUEEN MARGARET and POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "He will come straight. Look you lay home to him:"), new XElement("LINE", "Tell him his pranks have been too broad to bear with,"), new XElement("LINE", "And that your grace hath screen'd and stood between"), new XElement("LINE", "Much heat and him. I'll sconce me even here."), new XElement("LINE", "Pray you, be round with him.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Mother, mother, mother!" ) ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "I'll warrant you,"), new XElement("LINE", "Fear me not: withdraw, I hear him coming.") ), new XElement("STAGEDIR", "POLONIUS hides behind the arras"), new XElement("STAGEDIR", "Enter HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Now, mother, what's the matter?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Hamlet, thou hast thy father much offended.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Mother, you have my father much offended.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Come, come, you answer with an idle tongue.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Go, go, you question with a wicked tongue.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Why, how now, Hamlet!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What's the matter now?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Have you forgot me?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, by the rood, not so:"), new XElement("LINE", "You are the queen, your husband's brother's wife;"), new XElement("LINE", "And--would it were not so!--you are my mother.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Nay, then, I'll set those to you that can speak.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Come, come, and sit you down; you shall not budge;"), new XElement("LINE", "You go not till I set you up a glass"), new XElement("LINE", "Where you may see the inmost part of you.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "What wilt thou do? thou wilt not murder me?"), new XElement("LINE", "Help, help, ho!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Behind"), " What, ho! help, help, help!" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Drawing"), " How now! a rat? Dead, for a ducat, dead!" ) ), new XElement("STAGEDIR", "Makes a pass through the arras"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Behind"), " O, I am slain!" ) ), new XElement("STAGEDIR", "Falls and dies"), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O me, what hast thou done?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, I know not:"), new XElement("LINE", "Is it the king?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O, what a rash and bloody deed is this!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A bloody deed! almost as bad, good mother,"), new XElement("LINE", "As kill a king, and marry with his brother.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "As kill a king!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, lady, 'twas my word."), new XElement("STAGEDIR", "Lifts up the array and discovers POLONIUS"), new XElement("LINE", "Thou wretched, rash, intruding fool, farewell!"), new XElement("LINE", "I took thee for thy better: take thy fortune;"), new XElement("LINE", "Thou find'st to be too busy is some danger."), new XElement("LINE", "Leave wringing of your hands: peace! sit you down,"), new XElement("LINE", "And let me wring your heart; for so I shall,"), new XElement("LINE", "If it be made of penetrable stuff,"), new XElement("LINE", "If damned custom have not brass'd it so"), new XElement("LINE", "That it is proof and bulwark against sense.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "What have I done, that thou darest wag thy tongue"), new XElement("LINE", "In noise so rude against me?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Such an act"), new XElement("LINE", "That blurs the grace and blush of modesty,"), new XElement("LINE", "Calls virtue hypocrite, takes off the rose"), new XElement("LINE", "From the fair forehead of an innocent love"), new XElement("LINE", "And sets a blister there, makes marriage-vows"), new XElement("LINE", "As false as dicers' oaths: O, such a deed"), new XElement("LINE", "As from the body of contraction plucks"), new XElement("LINE", "The very soul, and sweet religion makes"), new XElement("LINE", "A rhapsody of words: heaven's face doth glow:"), new XElement("LINE", "Yea, this solidity and compound mass,"), new XElement("LINE", "With tristful visage, as against the doom,"), new XElement("LINE", "Is thought-sick at the act.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Ay me, what act,"), new XElement("LINE", "That roars so loud, and thunders in the index?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Look here, upon this picture, and on this,"), new XElement("LINE", "The counterfeit presentment of two brothers."), new XElement("LINE", "See, what a grace was seated on this brow;"), new XElement("LINE", "Hyperion's curls; the front of Jove himself;"), new XElement("LINE", "An eye like Mars, to threaten and command;"), new XElement("LINE", "A station like the herald Mercury"), new XElement("LINE", "New-lighted on a heaven-kissing hill;"), new XElement("LINE", "A combination and a form indeed,"), new XElement("LINE", "Where every god did seem to set his seal,"), new XElement("LINE", "To give the world assurance of a man:"), new XElement("LINE", "This was your husband. Look you now, what follows:"), new XElement("LINE", "Here is your husband; like a mildew'd ear,"), new XElement("LINE", "Blasting his wholesome brother. Have you eyes?"), new XElement("LINE", "Could you on this fair mountain leave to feed,"), new XElement("LINE", "And batten on this moor? Ha! have you eyes?"), new XElement("LINE", "You cannot call it love; for at your age"), new XElement("LINE", "The hey-day in the blood is tame, it's humble,"), new XElement("LINE", "And waits upon the judgment: and what judgment"), new XElement("LINE", "Would step from this to this? Sense, sure, you have,"), new XElement("LINE", "Else could you not have motion; but sure, that sense"), new XElement("LINE", "Is apoplex'd; for madness would not err,"), new XElement("LINE", "Nor sense to ecstasy was ne'er so thrall'd"), new XElement("LINE", "But it reserved some quantity of choice,"), new XElement("LINE", "To serve in such a difference. What devil was't"), new XElement("LINE", "That thus hath cozen'd you at hoodman-blind?"), new XElement("LINE", "Eyes without feeling, feeling without sight,"), new XElement("LINE", "Ears without hands or eyes, smelling sans all,"), new XElement("LINE", "Or but a sickly part of one true sense"), new XElement("LINE", "Could not so mope."), new XElement("LINE", "O shame! where is thy blush? Rebellious hell,"), new XElement("LINE", "If thou canst mutine in a matron's bones,"), new XElement("LINE", "To flaming youth let virtue be as wax,"), new XElement("LINE", "And melt in her own fire: proclaim no shame"), new XElement("LINE", "When the compulsive ardour gives the charge,"), new XElement("LINE", "Since frost itself as actively doth burn"), new XElement("LINE", "And reason panders will.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O Hamlet, speak no more:"), new XElement("LINE", "Thou turn'st mine eyes into my very soul;"), new XElement("LINE", "And there I see such black and grained spots"), new XElement("LINE", "As will not leave their tinct.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, but to live"), new XElement("LINE", "In the rank sweat of an enseamed bed,"), new XElement("LINE", "Stew'd in corruption, honeying and making love"), new XElement("LINE", "Over the nasty sty,--") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O, speak to me no more;"), new XElement("LINE", "These words, like daggers, enter in mine ears;"), new XElement("LINE", "No more, sweet Hamlet!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A murderer and a villain;"), new XElement("LINE", "A slave that is not twentieth part the tithe"), new XElement("LINE", "Of your precedent lord; a vice of kings;"), new XElement("LINE", "A cutpurse of the empire and the rule,"), new XElement("LINE", "That from a shelf the precious diadem stole,"), new XElement("LINE", "And put it in his pocket!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "No more!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A king of shreds and patches,--"), new XElement("STAGEDIR", "Enter Ghost"), new XElement("LINE", "Save me, and hover o'er me with your wings,"), new XElement("LINE", "You heavenly guards! What would your gracious figure?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alas, he's mad!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do you not come your tardy son to chide,"), new XElement("LINE", "That, lapsed in time and passion, lets go by"), new XElement("LINE", "The important acting of your dread command? O, say!") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Do not forget: this visitation"), new XElement("LINE", "Is but to whet thy almost blunted purpose."), new XElement("LINE", "But, look, amazement on thy mother sits:"), new XElement("LINE", "O, step between her and her fighting soul:"), new XElement("LINE", "Conceit in weakest bodies strongest works:"), new XElement("LINE", "Speak to her, Hamlet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How is it with you, lady?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alas, how is't with you,"), new XElement("LINE", "That you do bend your eye on vacancy"), new XElement("LINE", "And with the incorporal air do hold discourse?"), new XElement("LINE", "Forth at your eyes your spirits wildly peep;"), new XElement("LINE", "And, as the sleeping soldiers in the alarm,"), new XElement("LINE", "Your bedded hair, like life in excrements,"), new XElement("LINE", "Starts up, and stands on end. O gentle son,"), new XElement("LINE", "Upon the heat and flame of thy distemper"), new XElement("LINE", "Sprinkle cool patience. Whereon do you look?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "On him, on him! Look you, how pale he glares!"), new XElement("LINE", "His form and cause conjoin'd, preaching to stones,"), new XElement("LINE", "Would make them capable. Do not look upon me;"), new XElement("LINE", "Lest with this piteous action you convert"), new XElement("LINE", "My stern effects: then what I have to do"), new XElement("LINE", "Will want true colour; tears perchance for blood.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "To whom do you speak this?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do you see nothing there?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Nothing at all; yet all that is I see.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nor did you nothing hear?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "No, nothing but ourselves.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, look you there! look, how it steals away!"), new XElement("LINE", "My father, in his habit as he lived!"), new XElement("LINE", "Look, where he goes, even now, out at the portal!") ), new XElement("STAGEDIR", "Exit Ghost"), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "This the very coinage of your brain:"), new XElement("LINE", "This bodiless creation ecstasy"), new XElement("LINE", "Is very cunning in.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ecstasy!"), new XElement("LINE", "My pulse, as yours, doth temperately keep time,"), new XElement("LINE", "And makes as healthful music: it is not madness"), new XElement("LINE", "That I have utter'd: bring me to the test,"), new XElement("LINE", "And I the matter will re-word; which madness"), new XElement("LINE", "Would gambol from. Mother, for love of grace,"), new XElement("LINE", "Lay not that mattering unction to your soul,"), new XElement("LINE", "That not your trespass, but my madness speaks:"), new XElement("LINE", "It will but skin and film the ulcerous place,"), new XElement("LINE", "Whilst rank corruption, mining all within,"), new XElement("LINE", "Infects unseen. Confess yourself to heaven;"), new XElement("LINE", "Repent what's past; avoid what is to come;"), new XElement("LINE", "And do not spread the compost on the weeds,"), new XElement("LINE", "To make them ranker. Forgive me this my virtue;"), new XElement("LINE", "For in the fatness of these pursy times"), new XElement("LINE", "Virtue itself of vice must pardon beg,"), new XElement("LINE", "Yea, curb and woo for leave to do him good.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O Hamlet, thou hast cleft my heart in twain.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, throw away the worser part of it,"), new XElement("LINE", "And live the purer with the other half."), new XElement("LINE", "Good night: but go not to mine uncle's bed;"), new XElement("LINE", "Assume a virtue, if you have it not."), new XElement("LINE", "That monster, custom, who all sense doth eat,"), new XElement("LINE", "Of habits devil, is angel yet in this,"), new XElement("LINE", "That to the use of actions fair and good"), new XElement("LINE", "He likewise gives a frock or livery,"), new XElement("LINE", "That aptly is put on. Refrain to-night,"), new XElement("LINE", "And that shall lend a kind of easiness"), new XElement("LINE", "To the next abstinence: the next more easy;"), new XElement("LINE", "For use almost can change the stamp of nature,"), new XElement("LINE", "And either ... the devil, or throw him out"), new XElement("LINE", "With wondrous potency. Once more, good night:"), new XElement("LINE", "And when you are desirous to be bless'd,"), new XElement("LINE", "I'll blessing beg of you. For this same lord,"), new XElement("STAGEDIR", "Pointing to POLONIUS"), new XElement("LINE", "I do repent: but heaven hath pleased it so,"), new XElement("LINE", "To punish me with this and this with me,"), new XElement("LINE", "That I must be their scourge and minister."), new XElement("LINE", "I will bestow him, and will answer well"), new XElement("LINE", "The death I gave him. So, again, good night."), new XElement("LINE", "I must be cruel, only to be kind:"), new XElement("LINE", "Thus bad begins and worse remains behind."), new XElement("LINE", "One word more, good lady.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "What shall I do?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Not this, by no means, that I bid you do:"), new XElement("LINE", "Let the bloat king tempt you again to bed;"), new XElement("LINE", "Pinch wanton on your cheek; call you his mouse;"), new XElement("LINE", "And let him, for a pair of reechy kisses,"), new XElement("LINE", "Or paddling in your neck with his damn'd fingers,"), new XElement("LINE", "Make you to ravel all this matter out,"), new XElement("LINE", "That I essentially am not in madness,"), new XElement("LINE", "But mad in craft. 'Twere good you let him know;"), new XElement("LINE", "For who, that's but a queen, fair, sober, wise,"), new XElement("LINE", "Would from a paddock, from a bat, a gib,"), new XElement("LINE", "Such dear concernings hide? who would do so?"), new XElement("LINE", "No, in despite of sense and secrecy,"), new XElement("LINE", "Unpeg the basket on the house's top."), new XElement("LINE", "Let the birds fly, and, like the famous ape,"), new XElement("LINE", "To try conclusions, in the basket creep,"), new XElement("LINE", "And break your own neck down.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Be thou assured, if words be made of breath,"), new XElement("LINE", "And breath of life, I have no life to breathe"), new XElement("LINE", "What thou hast said to me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I must to England; you know that?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alack,"), new XElement("LINE", "I had forgot: 'tis so concluded on.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "There's letters seal'd: and my two schoolfellows,"), new XElement("LINE", "Whom I will trust as I will adders fang'd,"), new XElement("LINE", "They bear the mandate; they must sweep my way,"), new XElement("LINE", "And marshal me to knavery. Let it work;"), new XElement("LINE", "For 'tis the sport to have the engineer"), new XElement("LINE", "Hoist with his own petard: and 't shall go hard"), new XElement("LINE", "But I will delve one yard below their mines,"), new XElement("LINE", "And blow them at the moon: O, 'tis most sweet,"), new XElement("LINE", "When in one line two crafts directly meet."), new XElement("LINE", "This man shall set me packing:"), new XElement("LINE", "I'll lug the guts into the neighbour room."), new XElement("LINE", "Mother, good night. Indeed this counsellor"), new XElement("LINE", "Is now most still, most secret and most grave,"), new XElement("LINE", "Who was in life a foolish prating knave."), new XElement("LINE", "Come, sir, to draw toward an end with you."), new XElement("LINE", "Good night, mother.") ), new XElement("STAGEDIR", "Exeunt severally; HAMLET dragging in POLONIUS") ) ), new XElement("ACT", new XElement("TITLE", "ACT IV"), new XElement("SCENE", new XElement("TITLE", "SCENE I. A room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, QUEEN GERTRUDE, ROSENCRANTZ,\n" + "and GUILDENSTERN" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "There's matter in these sighs, these profound heaves:"), new XElement("LINE", "You must translate: 'tis fit we understand them."), new XElement("LINE", "Where is your son?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Bestow this place on us a little while."), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("LINE", "Ah, my good lord, what have I seen to-night!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "What, Gertrude? How does Hamlet?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Mad as the sea and wind, when both contend"), new XElement("LINE", "Which is the mightier: in his lawless fit,"), new XElement("LINE", "Behind the arras hearing something stir,"), new XElement("LINE", "Whips out his rapier, cries, 'A rat, a rat!'"), new XElement("LINE", "And, in this brainish apprehension, kills"), new XElement("LINE", "The unseen good old man.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O heavy deed!"), new XElement("LINE", "It had been so with us, had we been there:"), new XElement("LINE", "His liberty is full of threats to all;"), new XElement("LINE", "To you yourself, to us, to every one."), new XElement("LINE", "Alas, how shall this bloody deed be answer'd?"), new XElement("LINE", "It will be laid to us, whose providence"), new XElement("LINE", "Should have kept short, restrain'd and out of haunt,"), new XElement("LINE", "This mad young man: but so much was our love,"), new XElement("LINE", "We would not understand what was most fit;"), new XElement("LINE", "But, like the owner of a foul disease,"), new XElement("LINE", "To keep it from divulging, let it feed"), new XElement("LINE", "Even on the pith of Life. Where is he gone?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "To draw apart the body he hath kill'd:"), new XElement("LINE", "O'er whom his very madness, like some ore"), new XElement("LINE", "Among a mineral of metals base,"), new XElement("LINE", "Shows itself pure; he weeps for what is done.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O Gertrude, come away!"), new XElement("LINE", "The sun no sooner shall the mountains touch,"), new XElement("LINE", "But we will ship him hence: and this vile deed"), new XElement("LINE", "We must, with all our majesty and skill,"), new XElement("LINE", "Both countenance and excuse. Ho, Guildenstern!"), new XElement("STAGEDIR", "Re-enter ROSENCRANTZ and GUILDENSTERN"), new XElement("LINE", "Friends both, go join you with some further aid:"), new XElement("LINE", "Hamlet in madness hath Polonius slain,"), new XElement("LINE", "And from his mother's closet hath he dragg'd him:"), new XElement("LINE", "Go seek him out; speak fair, and bring the body"), new XElement("LINE", "Into the chapel. I pray you, haste in this."), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("LINE", "Come, Gertrude, we'll call up our wisest friends;"), new XElement("LINE", "And let them know, both what we mean to do,"), new XElement("LINE", "And what's untimely done..."), new XElement("LINE", "Whose whisper o'er the world's diameter,"), new XElement("LINE", "As level as the cannon to his blank,"), new XElement("LINE", "Transports his poison'd shot, may miss our name,"), new XElement("LINE", "And hit the woundless air. O, come away!"), new XElement("LINE", "My soul is full of discord and dismay.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE II. Another room in the castle."), new XElement("STAGEDIR", "Enter HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Safely stowed.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Hamlet! Lord Hamlet!" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What noise? who calls on Hamlet?"), new XElement("LINE", "O, here they come.") ), new XElement("STAGEDIR", "Enter ROSENCRANTZ and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "What have you done, my lord, with the dead body?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Compounded it with dust, whereto 'tis kin.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Tell us where 'tis, that we may take it thence"), new XElement("LINE", "And bear it to the chapel.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do not believe it.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Believe what?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That I can keep your counsel and not mine own."), new XElement("LINE", "Besides, to be demanded of a sponge! what"), new XElement("LINE", "replication should be made by the son of a king?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Take you me for a sponge, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, sir, that soaks up the king's countenance, his"), new XElement("LINE", "rewards, his authorities. But such officers do the"), new XElement("LINE", "king best service in the end: he keeps them, like"), new XElement("LINE", "an ape, in the corner of his jaw; first mouthed, to"), new XElement("LINE", "be last swallowed: when he needs what you have"), new XElement("LINE", "gleaned, it is but squeezing you, and, sponge, you"), new XElement("LINE", "shall be dry again.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "I understand you not, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am glad of it: a knavish speech sleeps in a"), new XElement("LINE", "foolish ear.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "My lord, you must tell us where the body is, and go"), new XElement("LINE", "with us to the king.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The body is with the king, but the king is not with"), new XElement("LINE", "the body. The king is a thing--") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "A thing, my lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Of nothing: bring me to him. Hide fox, and all after.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE III. Another room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, attended"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I have sent to seek him, and to find the body."), new XElement("LINE", "How dangerous is it that this man goes loose!"), new XElement("LINE", "Yet must not we put the strong law on him:"), new XElement("LINE", "He's loved of the distracted multitude,"), new XElement("LINE", "Who like not in their judgment, but their eyes;"), new XElement("LINE", "And where tis so, the offender's scourge is weigh'd,"), new XElement("LINE", "But never the offence. To bear all smooth and even,"), new XElement("LINE", "This sudden sending him away must seem"), new XElement("LINE", "Deliberate pause: diseases desperate grown"), new XElement("LINE", "By desperate appliance are relieved,"), new XElement("LINE", "Or not at all."), new XElement("STAGEDIR", "Enter ROSENCRANTZ"), new XElement("LINE", "How now! what hath befall'n?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Where the dead body is bestow'd, my lord,"), new XElement("LINE", "We cannot get from him.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "But where is he?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Without, my lord; guarded, to know your pleasure.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Bring him before us.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Ho, Guildenstern! bring in my lord.") ), new XElement("STAGEDIR", "Enter HAMLET and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Now, Hamlet, where's Polonius?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "At supper.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "At supper! where?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Not where he eats, but where he is eaten: a certain"), new XElement("LINE", "convocation of politic worms are e'en at him. Your"), new XElement("LINE", "worm is your only emperor for diet: we fat all"), new XElement("LINE", "creatures else to fat us, and we fat ourselves for"), new XElement("LINE", "maggots: your fat king and your lean beggar is but"), new XElement("LINE", "variable service, two dishes, but to one table:"), new XElement("LINE", "that's the end.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Alas, alas!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A man may fish with the worm that hath eat of a"), new XElement("LINE", "king, and cat of the fish that hath fed of that worm.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "What dost you mean by this?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nothing but to show you how a king may go a"), new XElement("LINE", "progress through the guts of a beggar.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Where is Polonius?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "In heaven; send hither to see: if your messenger"), new XElement("LINE", "find him not there, seek him i' the other place"), new XElement("LINE", "yourself. But indeed, if you find him not within"), new XElement("LINE", "this month, you shall nose him as you go up the"), new XElement("LINE", "stairs into the lobby.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Go seek him there.") ), new XElement("STAGEDIR", "To some Attendants"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "He will stay till ye come.") ), new XElement("STAGEDIR", "Exeunt Attendants"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Hamlet, this deed, for thine especial safety,--"), new XElement("LINE", "Which we do tender, as we dearly grieve"), new XElement("LINE", "For that which thou hast done,--must send thee hence"), new XElement("LINE", "With fiery quickness: therefore prepare thyself;"), new XElement("LINE", "The bark is ready, and the wind at help,"), new XElement("LINE", "The associates tend, and every thing is bent"), new XElement("LINE", "For England.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "For England!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Ay, Hamlet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Good.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "So is it, if thou knew'st our purposes.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I see a cherub that sees them. But, come; for"), new XElement("LINE", "England! Farewell, dear mother.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Thy loving father, Hamlet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "My mother: father and mother is man and wife; man"), new XElement("LINE", "and wife is one flesh; and so, my mother. Come, for England!") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Follow him at foot; tempt him with speed aboard;"), new XElement("LINE", "Delay it not; I'll have him hence to-night:"), new XElement("LINE", "Away! for every thing is seal'd and done"), new XElement("LINE", "That else leans on the affair: pray you, make haste."), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("LINE", "And, England, if my love thou hold'st at aught--"), new XElement("LINE", "As my great power thereof may give thee sense,"), new XElement("LINE", "Since yet thy cicatrice looks raw and red"), new XElement("LINE", "After the Danish sword, and thy free awe"), new XElement("LINE", "Pays homage to us--thou mayst not coldly set"), new XElement("LINE", "Our sovereign process; which imports at full,"), new XElement("LINE", "By letters congruing to that effect,"), new XElement("LINE", "The present death of Hamlet. Do it, England;"), new XElement("LINE", "For like the hectic in my blood he rages,"), new XElement("LINE", "And thou must cure me: till I know 'tis done,"), new XElement("LINE", "Howe'er my haps, my joys were ne'er begun.") ), new XElement("STAGEDIR", "Exit") ), new XElement("SCENE", new XElement("TITLE", "SCENE IV. A plain in Denmark."), new XElement("STAGEDIR", "Enter FORTINBRAS, a Captain, and Soldiers, marching"), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "Go, captain, from me greet the Danish king;"), new XElement("LINE", "Tell him that, by his licence, Fortinbras"), new XElement("LINE", "Craves the conveyance of a promised march"), new XElement("LINE", "Over his kingdom. You know the rendezvous."), new XElement("LINE", "If that his majesty would aught with us,"), new XElement("LINE", "We shall express our duty in his eye;"), new XElement("LINE", "And let him know so.") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "I will do't, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "Go softly on.") ), new XElement("STAGEDIR", "Exeunt FORTINBRAS and Soldiers"), new XElement("STAGEDIR", "Enter HAMLET, ROSENCRANTZ, GUILDENSTERN, and others"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Good sir, whose powers are these?") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "They are of Norway, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How purposed, sir, I pray you?") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "Against some part of Poland.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Who commands them, sir?") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "The nephews to old Norway, Fortinbras.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Goes it against the main of Poland, sir,"), new XElement("LINE", "Or for some frontier?") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "Truly to speak, and with no addition,"), new XElement("LINE", "We go to gain a little patch of ground"), new XElement("LINE", "That hath in it no profit but the name."), new XElement("LINE", "To pay five ducats, five, I would not farm it;"), new XElement("LINE", "Nor will it yield to Norway or the Pole"), new XElement("LINE", "A ranker rate, should it be sold in fee.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, then the Polack never will defend it.") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "Yes, it is already garrison'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Two thousand souls and twenty thousand ducats"), new XElement("LINE", "Will not debate the question of this straw:"), new XElement("LINE", "This is the imposthume of much wealth and peace,"), new XElement("LINE", "That inward breaks, and shows no cause without"), new XElement("LINE", "Why the man dies. I humbly thank you, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "God be wi' you, sir.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Wilt please you go, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I'll be with you straight go a little before."), new XElement("STAGEDIR", "Exeunt all except HAMLET"), new XElement("LINE", "How all occasions do inform against me,"), new XElement("LINE", "And spur my dull revenge! What is a man,"), new XElement("LINE", "If his chief good and market of his time"), new XElement("LINE", "Be but to sleep and feed? a beast, no more."), new XElement("LINE", "Sure, he that made us with such large discourse,"), new XElement("LINE", "Looking before and after, gave us not"), new XElement("LINE", "That capability and god-like reason"), new XElement("LINE", "To fust in us unused. Now, whether it be"), new XElement("LINE", "Bestial oblivion, or some craven scruple"), new XElement("LINE", "Of thinking too precisely on the event,"), new XElement("LINE", "A thought which, quarter'd, hath but one part wisdom"), new XElement("LINE", "And ever three parts coward, I do not know"), new XElement("LINE", "Why yet I live to say 'This thing's to do;'"), new XElement("LINE", "Sith I have cause and will and strength and means"), new XElement("LINE", "To do't. Examples gross as earth exhort me:"), new XElement("LINE", "Witness this army of such mass and charge"), new XElement("LINE", "Led by a delicate and tender prince,"), new XElement("LINE", "Whose spirit with divine ambition puff'd"), new XElement("LINE", "Makes mouths at the invisible event,"), new XElement("LINE", "Exposing what is mortal and unsure"), new XElement("LINE", "To all that fortune, death and danger dare,"), new XElement("LINE", "Even for an egg-shell. Rightly to be great"), new XElement("LINE", "Is not to stir without great argument,"), new XElement("LINE", "But greatly to find quarrel in a straw"), new XElement("LINE", "When honour's at the stake. How stand I then,"), new XElement("LINE", "That have a father kill'd, a mother stain'd,"), new XElement("LINE", "Excitements of my reason and my blood,"), new XElement("LINE", "And let all sleep? while, to my shame, I see"), new XElement("LINE", "The imminent death of twenty thousand men,"), new XElement("LINE", "That, for a fantasy and trick of fame,"), new XElement("LINE", "Go to their graves like beds, fight for a plot"), new XElement("LINE", "Whereon the numbers cannot try the cause,"), new XElement("LINE", "Which is not tomb enough and continent"), new XElement("LINE", "To hide the slain? O, from this time forth,"), new XElement("LINE", "My thoughts be bloody, or be nothing worth!") ), new XElement("STAGEDIR", "Exit") ), new XElement("SCENE", new XElement("TITLE", "SCENE V. Elsinore. A room in the castle."), new XElement("STAGEDIR", "Enter QUEEN GERTRUDE, HORATIO, and a Gentleman"), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "I will not speak with her.") ), new XElement("SPEECH", new XElement("SPEAKER", "Gentleman"), new XElement("LINE", "She is importunate, indeed distract:"), new XElement("LINE", "Her mood will needs be pitied.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "What would she have?") ), new XElement("SPEECH", new XElement("SPEAKER", "Gentleman"), new XElement("LINE", "She speaks much of her father; says she hears"), new XElement("LINE", "There's tricks i' the world; and hems, and beats her heart;"), new XElement("LINE", "Spurns enviously at straws; speaks things in doubt,"), new XElement("LINE", "That carry but half sense: her speech is nothing,"), new XElement("LINE", "Yet the unshaped use of it doth move"), new XElement("LINE", "The hearers to collection; they aim at it,"), new XElement("LINE", "And botch the words up fit to their own thoughts;"), new XElement("LINE", "Which, as her winks, and nods, and gestures"), new XElement("LINE", "yield them,"), new XElement("LINE", "Indeed would make one think there might be thought,"), new XElement("LINE", "Though nothing sure, yet much unhappily.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "'Twere good she were spoken with; for she may strew"), new XElement("LINE", "Dangerous conjectures in ill-breeding minds.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Let her come in."), new XElement("STAGEDIR", "Exit HORATIO"), new XElement("LINE", "To my sick soul, as sin's true nature is,"), new XElement("LINE", "Each toy seems prologue to some great amiss:"), new XElement("LINE", "So full of artless jealousy is guilt,"), new XElement("LINE", "It spills itself in fearing to be spilt.") ), new XElement("STAGEDIR", "Re-enter HORATIO, with OPHELIA"), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Where is the beauteous majesty of Denmark?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "How now, Ophelia!") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "How should I your true love know"), new XElement("LINE", "From another one?"), new XElement("LINE", "By his cockle hat and staff,"), new XElement("LINE", "And his sandal shoon.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alas, sweet lady, what imports this song?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Say you? nay, pray you, mark."), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "He is dead and gone, lady,"), new XElement("LINE", "He is dead and gone;"), new XElement("LINE", "At his head a grass-green turf,"), new XElement("LINE", "At his heels a stone.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Nay, but, Ophelia,--") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Pray you, mark."), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "White his shroud as the mountain snow,--") ), new XElement("STAGEDIR", "Enter KING CLAUDIUS"), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alas, look here, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "Larded with sweet flowers"), new XElement("LINE", "Which bewept to the grave did go"), new XElement("LINE", "With true-love showers.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "How do you, pretty lady?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Well, God 'ild you! They say the owl was a baker's"), new XElement("LINE", "daughter. Lord, we know what we are, but know not"), new XElement("LINE", "what we may be. God be at your table!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Conceit upon her father.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Pray you, let's have no words of this; but when they"), new XElement("LINE", "ask you what it means, say you this:"), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "To-morrow is Saint Valentine's day,"), new XElement("LINE", "All in the morning betime,"), new XElement("LINE", "And I a maid at your window,"), new XElement("LINE", "To be your Valentine."), new XElement("LINE", "Then up he rose, and donn'd his clothes,"), new XElement("LINE", "And dupp'd the chamber-door;"), new XElement("LINE", "Let in the maid, that out a maid"), new XElement("LINE", "Never departed more.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Pretty Ophelia!") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Indeed, la, without an oath, I'll make an end on't:"), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "By Gis and by Saint Charity,"), new XElement("LINE", "Alack, and fie for shame!"), new XElement("LINE", "Young men will do't, if they come to't;"), new XElement("LINE", "By cock, they are to blame."), new XElement("LINE", "Quoth she, before you tumbled me,"), new XElement("LINE", "You promised me to wed."), new XElement("LINE", "So would I ha' done, by yonder sun,"), new XElement("LINE", "An thou hadst not come to my bed.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "How long hath she been thus?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I hope all will be well. We must be patient: but I"), new XElement("LINE", "cannot choose but weep, to think they should lay him"), new XElement("LINE", "i' the cold ground. My brother shall know of it:"), new XElement("LINE", "and so I thank you for your good counsel. Come, my"), new XElement("LINE", "coach! Good night, ladies; good night, sweet ladies;"), new XElement("LINE", "good night, good night.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Follow her close; give her good watch,"), new XElement("LINE", "I pray you."), new XElement("STAGEDIR", "Exit HORATIO"), new XElement("LINE", "O, this is the poison of deep grief; it springs"), new XElement("LINE", "All from her father's death. O Gertrude, Gertrude,"), new XElement("LINE", "When sorrows come, they come not single spies"), new XElement("LINE", "But in battalions. First, her father slain:"), new XElement("LINE", "Next, your son gone; and he most violent author"), new XElement("LINE", "Of his own just remove: the people muddied,"), new XElement("LINE", "Thick and unwholesome in their thoughts and whispers,"), new XElement("LINE", "For good Polonius' death; and we have done but greenly,"), new XElement("LINE", "In hugger-mugger to inter him: poor Ophelia"), new XElement("LINE", "Divided from herself and her fair judgment,"), new XElement("LINE", "Without the which we are pictures, or mere beasts:"), new XElement("LINE", "Last, and as much containing as all these,"), new XElement("LINE", "Her brother is in secret come from France;"), new XElement("LINE", "Feeds on his wonder, keeps himself in clouds,"), new XElement("LINE", "And wants not buzzers to infect his ear"), new XElement("LINE", "With pestilent speeches of his father's death;"), new XElement("LINE", "Wherein necessity, of matter beggar'd,"), new XElement("LINE", "Will nothing stick our person to arraign"), new XElement("LINE", "In ear and ear. O my dear Gertrude, this,"), new XElement("LINE", "Like to a murdering-piece, in many places"), new XElement("LINE", "Gives me superfluous death.") ), new XElement("STAGEDIR", "A noise within"), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alack, what noise is this?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Where are my Switzers? Let them guard the door."), new XElement("STAGEDIR", "Enter another Gentleman"), new XElement("LINE", "What is the matter?") ), new XElement("SPEECH", new XElement("SPEAKER", "Gentleman"), new XElement("LINE", "Save yourself, my lord:"), new XElement("LINE", "The ocean, overpeering of his list,"), new XElement("LINE", "Eats not the flats with more impetuous haste"), new XElement("LINE", "Than young Laertes, in a riotous head,"), new XElement("LINE", "O'erbears your officers. The rabble call him lord;"), new XElement("LINE", "And, as the world were now but to begin,"), new XElement("LINE", "Antiquity forgot, custom not known,"), new XElement("LINE", "The ratifiers and props of every word,"), new XElement("LINE", "They cry 'Choose we: Laertes shall be king:'"), new XElement("LINE", "Caps, hands, and tongues, applaud it to the clouds:"), new XElement("LINE", "'Laertes shall be king, Laertes king!'") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "How cheerfully on the false trail they cry!"), new XElement("LINE", "O, this is counter, you false Danish dogs!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "The doors are broke.") ), new XElement("STAGEDIR", "Noise within"), new XElement("STAGEDIR", "Enter LAERTES, armed; Danes following"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Where is this king? Sirs, stand you all without.") ), new XElement("SPEECH", new XElement("SPEAKER", "Danes"), new XElement("LINE", "No, let's come in.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I pray you, give me leave.") ), new XElement("SPEECH", new XElement("SPEAKER", "Danes"), new XElement("LINE", "We will, we will.") ), new XElement("STAGEDIR", "They retire without the door"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I thank you: keep the door. O thou vile king,"), new XElement("LINE", "Give me my father!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Calmly, good Laertes.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "That drop of blood that's calm proclaims me bastard,"), new XElement("LINE", "Cries cuckold to my father, brands the harlot"), new XElement("LINE", "Even here, between the chaste unsmirched brow"), new XElement("LINE", "Of my true mother.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "What is the cause, Laertes,"), new XElement("LINE", "That thy rebellion looks so giant-like?"), new XElement("LINE", "Let him go, Gertrude; do not fear our person:"), new XElement("LINE", "There's such divinity doth hedge a king,"), new XElement("LINE", "That treason can but peep to what it would,"), new XElement("LINE", "Acts little of his will. Tell me, Laertes,"), new XElement("LINE", "Why thou art thus incensed. Let him go, Gertrude."), new XElement("LINE", "Speak, man.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Where is my father?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Dead.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "But not by him.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Let him demand his fill.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "How came he dead? I'll not be juggled with:"), new XElement("LINE", "To hell, allegiance! vows, to the blackest devil!"), new XElement("LINE", "Conscience and grace, to the profoundest pit!"), new XElement("LINE", "I dare damnation. To this point I stand,"), new XElement("LINE", "That both the worlds I give to negligence,"), new XElement("LINE", "Let come what comes; only I'll be revenged"), new XElement("LINE", "Most thoroughly for my father.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Who shall stay you?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "My will, not all the world:"), new XElement("LINE", "And for my means, I'll husband them so well,"), new XElement("LINE", "They shall go far with little.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Good Laertes,"), new XElement("LINE", "If you desire to know the certainty"), new XElement("LINE", "Of your dear father's death, is't writ in your revenge,"), new XElement("LINE", "That, swoopstake, you will draw both friend and foe,"), new XElement("LINE", "Winner and loser?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "None but his enemies.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Will you know them then?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "To his good friends thus wide I'll ope my arms;"), new XElement("LINE", "And like the kind life-rendering pelican,"), new XElement("LINE", "Repast them with my blood.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Why, now you speak"), new XElement("LINE", "Like a good child and a true gentleman."), new XElement("LINE", "That I am guiltless of your father's death,"), new XElement("LINE", "And am most sensible in grief for it,"), new XElement("LINE", "It shall as level to your judgment pierce"), new XElement("LINE", "As day does to your eye.") ), new XElement("SPEECH", new XElement("SPEAKER", "Danes"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Let her come in." ) ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "How now! what noise is that?"), new XElement("STAGEDIR", "Re-enter OPHELIA"), new XElement("LINE", "O heat, dry up my brains! tears seven times salt,"), new XElement("LINE", "Burn out the sense and virtue of mine eye!"), new XElement("LINE", "By heaven, thy madness shall be paid by weight,"), new XElement("LINE", "Till our scale turn the beam. O rose of May!"), new XElement("LINE", "Dear maid, kind sister, sweet Ophelia!"), new XElement("LINE", "O heavens! is't possible, a young maid's wits"), new XElement("LINE", "Should be as moral as an old man's life?"), new XElement("LINE", "Nature is fine in love, and where 'tis fine,"), new XElement("LINE", "It sends some precious instance of itself"), new XElement("LINE", "After the thing it loves.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "They bore him barefaced on the bier;"), new XElement("LINE", "Hey non nonny, nonny, hey nonny;"), new XElement("LINE", "And in his grave rain'd many a tear:--"), new XElement("LINE", "Fare you well, my dove!") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Hadst thou thy wits, and didst persuade revenge,"), new XElement("LINE", "It could not move thus.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "You must sing a-down a-down,"), new XElement("LINE", "An you call him a-down-a."), new XElement("LINE", "O, how the wheel becomes it! It is the false"), new XElement("LINE", "steward, that stole his master's daughter.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "This nothing's more than matter.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "There's rosemary, that's for remembrance; pray,"), new XElement("LINE", "love, remember: and there is pansies. that's for thoughts.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "A document in madness, thoughts and remembrance fitted.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "There's fennel for you, and columbines: there's rue"), new XElement("LINE", "for you; and here's some for me: we may call it"), new XElement("LINE", "herb-grace o' Sundays: O you must wear your rue with"), new XElement("LINE", "a difference. There's a daisy: I would give you"), new XElement("LINE", "some violets, but they withered all when my father"), new XElement("LINE", "died: they say he made a good end,--"), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "For bonny sweet Robin is all my joy.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Thought and affliction, passion, hell itself,"), new XElement("LINE", "She turns to favour and to prettiness.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "And will he not come again?"), new XElement("LINE", "And will he not come again?"), new XElement("LINE", "No, no, he is dead:"), new XElement("LINE", "Go to thy death-bed:"), new XElement("LINE", "He never will come again."), new XElement("LINE", "His beard was as white as snow,"), new XElement("LINE", "All flaxen was his poll:"), new XElement("LINE", "He is gone, he is gone,"), new XElement("LINE", "And we cast away moan:"), new XElement("LINE", "God ha' mercy on his soul!"), new XElement("LINE", "And of all Christian souls, I pray God. God be wi' ye.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Do you see this, O God?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Laertes, I must commune with your grief,"), new XElement("LINE", "Or you deny me right. Go but apart,"), new XElement("LINE", "Make choice of whom your wisest friends you will."), new XElement("LINE", "And they shall hear and judge 'twixt you and me:"), new XElement("LINE", "If by direct or by collateral hand"), new XElement("LINE", "They find us touch'd, we will our kingdom give,"), new XElement("LINE", "Our crown, our life, and all that we can ours,"), new XElement("LINE", "To you in satisfaction; but if not,"), new XElement("LINE", "Be you content to lend your patience to us,"), new XElement("LINE", "And we shall jointly labour with your soul"), new XElement("LINE", "To give it due content.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Let this be so;"), new XElement("LINE", "His means of death, his obscure funeral--"), new XElement("LINE", "No trophy, sword, nor hatchment o'er his bones,"), new XElement("LINE", "No noble rite nor formal ostentation--"), new XElement("LINE", "Cry to be heard, as 'twere from heaven to earth,"), new XElement("LINE", "That I must call't in question.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "So you shall;"), new XElement("LINE", "And where the offence is let the great axe fall."), new XElement("LINE", "I pray you, go with me.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE VI. Another room in the castle."), new XElement("STAGEDIR", "Enter HORATIO and a Servant"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What are they that would speak with me?") ), new XElement("SPEECH", new XElement("SPEAKER", "Servant"), new XElement("LINE", "Sailors, sir: they say they have letters for you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Let them come in."), new XElement("STAGEDIR", "Exit Servant"), new XElement("LINE", "I do not know from what part of the world"), new XElement("LINE", "I should be greeted, if not from Lord Hamlet.") ), new XElement("STAGEDIR", "Enter Sailors"), new XElement("SPEECH", new XElement("SPEAKER", "First Sailor"), new XElement("LINE", "God bless you, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Let him bless thee too.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Sailor"), new XElement("LINE", "He shall, sir, an't please him. There's a letter for"), new XElement("LINE", "you, sir; it comes from the ambassador that was"), new XElement("LINE", "bound for England; if your name be Horatio, as I am"), new XElement("LINE", "let to know it is.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", new XElement("STAGEDIR", "Reads"), " 'Horatio, when thou shalt have overlooked" ), new XElement("LINE", "this, give these fellows some means to the king:"), new XElement("LINE", "they have letters for him. Ere we were two days old"), new XElement("LINE", "at sea, a pirate of very warlike appointment gave us"), new XElement("LINE", "chase. Finding ourselves too slow of sail, we put on"), new XElement("LINE", "a compelled valour, and in the grapple I boarded"), new XElement("LINE", "them: on the instant they got clear of our ship; so"), new XElement("LINE", "I alone became their prisoner. They have dealt with"), new XElement("LINE", "me like thieves of mercy: but they knew what they"), new XElement("LINE", "did; I am to do a good turn for them. Let the king"), new XElement("LINE", "have the letters I have sent; and repair thou to me"), new XElement("LINE", "with as much speed as thou wouldst fly death. I"), new XElement("LINE", "have words to speak in thine ear will make thee"), new XElement("LINE", "dumb; yet are they much too light for the bore of"), new XElement("LINE", "the matter. These good fellows will bring thee"), new XElement("LINE", "where I am. Rosencrantz and Guildenstern hold their"), new XElement("LINE", "course for England: of them I have much to tell"), new XElement("LINE", "thee. Farewell."), new XElement("LINE", "'He that thou knowest thine, HAMLET.'"), new XElement("LINE", "Come, I will make you way for these your letters;"), new XElement("LINE", "And do't the speedier, that you may direct me"), new XElement("LINE", "To him from whom you brought them.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE VII. Another room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS and LAERTES"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Now must your conscience my acquaintance seal,"), new XElement("LINE", "And you must put me in your heart for friend,"), new XElement("LINE", "Sith you have heard, and with a knowing ear,"), new XElement("LINE", "That he which hath your noble father slain"), new XElement("LINE", "Pursued my life.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "It well appears: but tell me"), new XElement("LINE", "Why you proceeded not against these feats,"), new XElement("LINE", "So crimeful and so capital in nature,"), new XElement("LINE", "As by your safety, wisdom, all things else,"), new XElement("LINE", "You mainly were stirr'd up.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O, for two special reasons;"), new XElement("LINE", "Which may to you, perhaps, seem much unsinew'd,"), new XElement("LINE", "But yet to me they are strong. The queen his mother"), new XElement("LINE", "Lives almost by his looks; and for myself--"), new XElement("LINE", "My virtue or my plague, be it either which--"), new XElement("LINE", "She's so conjunctive to my life and soul,"), new XElement("LINE", "That, as the star moves not but in his sphere,"), new XElement("LINE", "I could not but by her. The other motive,"), new XElement("LINE", "Why to a public count I might not go,"), new XElement("LINE", "Is the great love the general gender bear him;"), new XElement("LINE", "Who, dipping all his faults in their affection,"), new XElement("LINE", "Would, like the spring that turneth wood to stone,"), new XElement("LINE", "Convert his gyves to graces; so that my arrows,"), new XElement("LINE", "Too slightly timber'd for so loud a wind,"), new XElement("LINE", "Would have reverted to my bow again,"), new XElement("LINE", "And not where I had aim'd them.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "And so have I a noble father lost;"), new XElement("LINE", "A sister driven into desperate terms,"), new XElement("LINE", "Whose worth, if praises may go back again,"), new XElement("LINE", "Stood challenger on mount of all the age"), new XElement("LINE", "For her perfections: but my revenge will come.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Break not your sleeps for that: you must not think"), new XElement("LINE", "That we are made of stuff so flat and dull"), new XElement("LINE", "That we can let our beard be shook with danger"), new XElement("LINE", "And think it pastime. You shortly shall hear more:"), new XElement("LINE", "I loved your father, and we love ourself;"), new XElement("LINE", "And that, I hope, will teach you to imagine--"), new XElement("STAGEDIR", "Enter a Messenger"), new XElement("LINE", "How now! what news?") ), new XElement("SPEECH", new XElement("SPEAKER", "Messenger"), new XElement("LINE", "Letters, my lord, from Hamlet:"), new XElement("LINE", "This to your majesty; this to the queen.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "From Hamlet! who brought them?") ), new XElement("SPEECH", new XElement("SPEAKER", "Messenger"), new XElement("LINE", "Sailors, my lord, they say; I saw them not:"), new XElement("LINE", "They were given me by Claudio; he received them"), new XElement("LINE", "Of him that brought them.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Laertes, you shall hear them. Leave us."), new XElement("STAGEDIR", "Exit Messenger"), new XElement("STAGEDIR", "Reads"), new XElement("LINE", "'High and mighty, You shall know I am set naked on"), new XElement("LINE", "your kingdom. To-morrow shall I beg leave to see"), new XElement("LINE", "your kingly eyes: when I shall, first asking your"), new XElement("LINE", "pardon thereunto, recount the occasion of my sudden"), new XElement("LINE", "and more strange return. 'HAMLET.'"), new XElement("LINE", "What should this mean? Are all the rest come back?"), new XElement("LINE", "Or is it some abuse, and no such thing?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Know you the hand?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "'Tis Hamlets character. 'Naked!"), new XElement("LINE", "And in a postscript here, he says 'alone.'"), new XElement("LINE", "Can you advise me?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I'm lost in it, my lord. But let him come;"), new XElement("LINE", "It warms the very sickness in my heart,"), new XElement("LINE", "That I shall live and tell him to his teeth,"), new XElement("LINE", "'Thus didest thou.'") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "If it be so, Laertes--"), new XElement("LINE", "As how should it be so? how otherwise?--"), new XElement("LINE", "Will you be ruled by me?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Ay, my lord;"), new XElement("LINE", "So you will not o'errule me to a peace.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "To thine own peace. If he be now return'd,"), new XElement("LINE", "As checking at his voyage, and that he means"), new XElement("LINE", "No more to undertake it, I will work him"), new XElement("LINE", "To an exploit, now ripe in my device,"), new XElement("LINE", "Under the which he shall not choose but fall:"), new XElement("LINE", "And for his death no wind of blame shall breathe,"), new XElement("LINE", "But even his mother shall uncharge the practise"), new XElement("LINE", "And call it accident.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "My lord, I will be ruled;"), new XElement("LINE", "The rather, if you could devise it so"), new XElement("LINE", "That I might be the organ.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "It falls right."), new XElement("LINE", "You have been talk'd of since your travel much,"), new XElement("LINE", "And that in Hamlet's hearing, for a quality"), new XElement("LINE", "Wherein, they say, you shine: your sum of parts"), new XElement("LINE", "Did not together pluck such envy from him"), new XElement("LINE", "As did that one, and that, in my regard,"), new XElement("LINE", "Of the unworthiest siege.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "What part is that, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "A very riband in the cap of youth,"), new XElement("LINE", "Yet needful too; for youth no less becomes"), new XElement("LINE", "The light and careless livery that it wears"), new XElement("LINE", "Than settled age his sables and his weeds,"), new XElement("LINE", "Importing health and graveness. Two months since,"), new XElement("LINE", "Here was a gentleman of Normandy:--"), new XElement("LINE", "I've seen myself, and served against, the French,"), new XElement("LINE", "And they can well on horseback: but this gallant"), new XElement("LINE", "Had witchcraft in't; he grew unto his seat;"), new XElement("LINE", "And to such wondrous doing brought his horse,"), new XElement("LINE", "As he had been incorpsed and demi-natured"), new XElement("LINE", "With the brave beast: so far he topp'd my thought,"), new XElement("LINE", "That I, in forgery of shapes and tricks,"), new XElement("LINE", "Come short of what he did.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "A Norman was't?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "A Norman.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Upon my life, Lamond.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "The very same.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I know him well: he is the brooch indeed"), new XElement("LINE", "And gem of all the nation.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "He made confession of you,"), new XElement("LINE", "And gave you such a masterly report"), new XElement("LINE", "For art and exercise in your defence"), new XElement("LINE", "And for your rapier most especially,"), new XElement("LINE", "That he cried out, 'twould be a sight indeed,"), new XElement("LINE", "If one could match you: the scrimers of their nation,"), new XElement("LINE", "He swore, had had neither motion, guard, nor eye,"), new XElement("LINE", "If you opposed them. Sir, this report of his"), new XElement("LINE", "Did Hamlet so envenom with his envy"), new XElement("LINE", "That he could nothing do but wish and beg"), new XElement("LINE", "Your sudden coming o'er, to play with him."), new XElement("LINE", "Now, out of this,--") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "What out of this, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Laertes, was your father dear to you?"), new XElement("LINE", "Or are you like the painting of a sorrow,"), new XElement("LINE", "A face without a heart?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Why ask you this?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Not that I think you did not love your father;"), new XElement("LINE", "But that I know love is begun by time;"), new XElement("LINE", "And that I see, in passages of proof,"), new XElement("LINE", "Time qualifies the spark and fire of it."), new XElement("LINE", "There lives within the very flame of love"), new XElement("LINE", "A kind of wick or snuff that will abate it;"), new XElement("LINE", "And nothing is at a like goodness still;"), new XElement("LINE", "For goodness, growing to a plurisy,"), new XElement("LINE", "Dies in his own too much: that we would do"), new XElement("LINE", "We should do when we would; for this 'would' changes"), new XElement("LINE", "And hath abatements and delays as many"), new XElement("LINE", "As there are tongues, are hands, are accidents;"), new XElement("LINE", "And then this 'should' is like a spendthrift sigh,"), new XElement("LINE", "That hurts by easing. But, to the quick o' the ulcer:--"), new XElement("LINE", "Hamlet comes back: what would you undertake,"), new XElement("LINE", "To show yourself your father's son in deed"), new XElement("LINE", "More than in words?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "To cut his throat i' the church.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "No place, indeed, should murder sanctuarize;"), new XElement("LINE", "Revenge should have no bounds. But, good Laertes,"), new XElement("LINE", "Will you do this, keep close within your chamber."), new XElement("LINE", "Hamlet return'd shall know you are come home:"), new XElement("LINE", "We'll put on those shall praise your excellence"), new XElement("LINE", "And set a double varnish on the fame"), new XElement("LINE", "The Frenchman gave you, bring you in fine together"), new XElement("LINE", "And wager on your heads: he, being remiss,"), new XElement("LINE", "Most generous and free from all contriving,"), new XElement("LINE", "Will not peruse the foils; so that, with ease,"), new XElement("LINE", "Or with a little shuffling, you may choose"), new XElement("LINE", "A sword unbated, and in a pass of practise"), new XElement("LINE", "Requite him for your father.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I will do't:"), new XElement("LINE", "And, for that purpose, I'll anoint my sword."), new XElement("LINE", "I bought an unction of a mountebank,"), new XElement("LINE", "So mortal that, but dip a knife in it,"), new XElement("LINE", "Where it draws blood no cataplasm so rare,"), new XElement("LINE", "Collected from all simples that have virtue"), new XElement("LINE", "Under the moon, can save the thing from death"), new XElement("LINE", "That is but scratch'd withal: I'll touch my point"), new XElement("LINE", "With this contagion, that, if I gall him slightly,"), new XElement("LINE", "It may be death.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Let's further think of this;"), new XElement("LINE", "Weigh what convenience both of time and means"), new XElement("LINE", "May fit us to our shape: if this should fail,"), new XElement("LINE", "And that our drift look through our bad performance,"), new XElement("LINE", "'Twere better not assay'd: therefore this project"), new XElement("LINE", "Should have a back or second, that might hold,"), new XElement("LINE", "If this should blast in proof. Soft! let me see:"), new XElement("LINE", "We'll make a solemn wager on your cunnings: I ha't."), new XElement("LINE", "When in your motion you are hot and dry--"), new XElement("LINE", "As make your bouts more violent to that end--"), new XElement("LINE", "And that he calls for drink, I'll have prepared him"), new XElement("LINE", "A chalice for the nonce, whereon but sipping,"), new XElement("LINE", "If he by chance escape your venom'd stuck,"), new XElement("LINE", "Our purpose may hold there."), new XElement("STAGEDIR", "Enter QUEEN GERTRUDE"), new XElement("LINE", "How now, sweet queen!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "One woe doth tread upon another's heel,"), new XElement("LINE", "So fast they follow; your sister's drown'd, Laertes.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Drown'd! O, where?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "There is a willow grows aslant a brook,"), new XElement("LINE", "That shows his hoar leaves in the glassy stream;"), new XElement("LINE", "There with fantastic garlands did she come"), new XElement("LINE", "Of crow-flowers, nettles, daisies, and long purples"), new XElement("LINE", "That liberal shepherds give a grosser name,"), new XElement("LINE", "But our cold maids do dead men's fingers call them:"), new XElement("LINE", "There, on the pendent boughs her coronet weeds"), new XElement("LINE", "Clambering to hang, an envious sliver broke;"), new XElement("LINE", "When down her weedy trophies and herself"), new XElement("LINE", "Fell in the weeping brook. Her clothes spread wide;"), new XElement("LINE", "And, mermaid-like, awhile they bore her up:"), new XElement("LINE", "Which time she chanted snatches of old tunes;"), new XElement("LINE", "As one incapable of her own distress,"), new XElement("LINE", "Or like a creature native and indued"), new XElement("LINE", "Unto that element: but long it could not be"), new XElement("LINE", "Till that her garments, heavy with their drink,"), new XElement("LINE", "Pull'd the poor wretch from her melodious lay"), new XElement("LINE", "To muddy death.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Alas, then, she is drown'd?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Drown'd, drown'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Too much of water hast thou, poor Ophelia,"), new XElement("LINE", "And therefore I forbid my tears: but yet"), new XElement("LINE", "It is our trick; nature her custom holds,"), new XElement("LINE", "Let shame say what it will: when these are gone,"), new XElement("LINE", "The woman will be out. Adieu, my lord:"), new XElement("LINE", "I have a speech of fire, that fain would blaze,"), new XElement("LINE", "But that this folly douts it.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Let's follow, Gertrude:"), new XElement("LINE", "How much I had to do to calm his rage!"), new XElement("LINE", "Now fear I this will give it start again;"), new XElement("LINE", "Therefore let's follow.") ), new XElement("STAGEDIR", "Exeunt") ) ), new XElement("ACT", new XElement("TITLE", "ACT V"), new XElement("SCENE", new XElement("TITLE", "SCENE I. A churchyard."), new XElement("STAGEDIR", "Enter two Clowns, with spades, &c"), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Is she to be buried in Christian burial that"), new XElement("LINE", "wilfully seeks her own salvation?") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "I tell thee she is: and therefore make her grave"), new XElement("LINE", "straight: the crowner hath sat on her, and finds it"), new XElement("LINE", "Christian burial.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "How can that be, unless she drowned herself in her"), new XElement("LINE", "own defence?") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Why, 'tis found so.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "It must be 'se offendendo;' it cannot be else. For"), new XElement("LINE", "here lies the point: if I drown myself wittingly,"), new XElement("LINE", "it argues an act: and an act hath three branches: it"), new XElement("LINE", "is, to act, to do, to perform: argal, she drowned"), new XElement("LINE", "herself wittingly.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Nay, but hear you, goodman delver,--") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Give me leave. Here lies the water; good: here"), new XElement("LINE", "stands the man; good; if the man go to this water,"), new XElement("LINE", "and drown himself, it is, will he, nill he, he"), new XElement("LINE", "goes,--mark you that; but if the water come to him"), new XElement("LINE", "and drown him, he drowns not himself: argal, he"), new XElement("LINE", "that is not guilty of his own death shortens not his own life.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "But is this law?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Ay, marry, is't; crowner's quest law.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Will you ha' the truth on't? If this had not been"), new XElement("LINE", "a gentlewoman, she should have been buried out o'"), new XElement("LINE", "Christian burial.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Why, there thou say'st: and the more pity that"), new XElement("LINE", "great folk should have countenance in this world to"), new XElement("LINE", "drown or hang themselves, more than their even"), new XElement("LINE", "Christian. Come, my spade. There is no ancient"), new XElement("LINE", "gentleman but gardeners, ditchers, and grave-makers:"), new XElement("LINE", "they hold up Adam's profession.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Was he a gentleman?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "He was the first that ever bore arms.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Why, he had none.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "What, art a heathen? How dost thou understand the"), new XElement("LINE", "Scripture? The Scripture says 'Adam digged:'"), new XElement("LINE", "could he dig without arms? I'll put another"), new XElement("LINE", "question to thee: if thou answerest me not to the"), new XElement("LINE", "purpose, confess thyself--") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Go to.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "What is he that builds stronger than either the"), new XElement("LINE", "mason, the shipwright, or the carpenter?") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "The gallows-maker; for that frame outlives a"), new XElement("LINE", "thousand tenants.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "I like thy wit well, in good faith: the gallows"), new XElement("LINE", "does well; but how does it well? it does well to"), new XElement("LINE", "those that do in: now thou dost ill to say the"), new XElement("LINE", "gallows is built stronger than the church: argal,"), new XElement("LINE", "the gallows may do well to thee. To't again, come.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "'Who builds stronger than a mason, a shipwright, or"), new XElement("LINE", "a carpenter?'") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Ay, tell me that, and unyoke.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Marry, now I can tell.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "To't.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Mass, I cannot tell.") ), new XElement("STAGEDIR", "Enter HAMLET and HORATIO, at a distance"), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Cudgel thy brains no more about it, for your dull"), new XElement("LINE", "ass will not mend his pace with beating; and, when"), new XElement("LINE", "you are asked this question next, say 'a"), new XElement("LINE", "grave-maker: 'the houses that he makes last till"), new XElement("LINE", "doomsday. Go, get thee to Yaughan: fetch me a"), new XElement("LINE", "stoup of liquor."), new XElement("STAGEDIR", "Exit Second Clown"), new XElement("STAGEDIR", "He digs and sings"), new XElement("LINE", "In youth, when I did love, did love,"), new XElement("LINE", "Methought it was very sweet,"), new XElement("LINE", "To contract, O, the time, for, ah, my behove,"), new XElement("LINE", "O, methought, there was nothing meet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Has this fellow no feeling of his business, that he"), new XElement("LINE", "sings at grave-making?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Custom hath made it in him a property of easiness.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Tis e'en so: the hand of little employment hath"), new XElement("LINE", "the daintier sense.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "But age, with his stealing steps,"), new XElement("LINE", "Hath claw'd me in his clutch,"), new XElement("LINE", "And hath shipped me intil the land,"), new XElement("LINE", "As if I had never been such.") ), new XElement("STAGEDIR", "Throws up a skull"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That skull had a tongue in it, and could sing once:"), new XElement("LINE", "how the knave jowls it to the ground, as if it were"), new XElement("LINE", "Cain's jaw-bone, that did the first murder! It"), new XElement("LINE", "might be the pate of a politician, which this ass"), new XElement("LINE", "now o'er-reaches; one that would circumvent God,"), new XElement("LINE", "might it not?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It might, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Or of a courtier; which could say 'Good morrow,"), new XElement("LINE", "sweet lord! How dost thou, good lord?' This might"), new XElement("LINE", "be my lord such-a-one, that praised my lord"), new XElement("LINE", "such-a-one's horse, when he meant to beg it; might it not?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Ay, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, e'en so: and now my Lady Worm's; chapless, and"), new XElement("LINE", "knocked about the mazzard with a sexton's spade:"), new XElement("LINE", "here's fine revolution, an we had the trick to"), new XElement("LINE", "see't. Did these bones cost no more the breeding,"), new XElement("LINE", "but to play at loggats with 'em? mine ache to think on't.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "A pick-axe, and a spade, a spade,"), new XElement("LINE", "For and a shrouding sheet:"), new XElement("LINE", "O, a pit of clay for to be made"), new XElement("LINE", "For such a guest is meet.") ), new XElement("STAGEDIR", "Throws up another skull"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "There's another: why may not that be the skull of a"), new XElement("LINE", "lawyer? Where be his quiddities now, his quillets,"), new XElement("LINE", "his cases, his tenures, and his tricks? why does he"), new XElement("LINE", "suffer this rude knave now to knock him about the"), new XElement("LINE", "sconce with a dirty shovel, and will not tell him of"), new XElement("LINE", "his action of battery? Hum! This fellow might be"), new XElement("LINE", "in's time a great buyer of land, with his statutes,"), new XElement("LINE", "his recognizances, his fines, his double vouchers,"), new XElement("LINE", "his recoveries: is this the fine of his fines, and"), new XElement("LINE", "the recovery of his recoveries, to have his fine"), new XElement("LINE", "pate full of fine dirt? will his vouchers vouch him"), new XElement("LINE", "no more of his purchases, and double ones too, than"), new XElement("LINE", "the length and breadth of a pair of indentures? The"), new XElement("LINE", "very conveyances of his lands will hardly lie in"), new XElement("LINE", "this box; and must the inheritor himself have no more, ha?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Not a jot more, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Is not parchment made of sheepskins?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Ay, my lord, and of calf-skins too.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "They are sheep and calves which seek out assurance"), new XElement("LINE", "in that. I will speak to this fellow. Whose"), new XElement("LINE", "grave's this, sirrah?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Mine, sir."), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "O, a pit of clay for to be made"), new XElement("LINE", "For such a guest is meet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I think it be thine, indeed; for thou liest in't.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "You lie out on't, sir, and therefore it is not"), new XElement("LINE", "yours: for my part, I do not lie in't, and yet it is mine.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Thou dost lie in't, to be in't and say it is thine:"), new XElement("LINE", "'tis for the dead, not for the quick; therefore thou liest.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "'Tis a quick lie, sir; 'twill away gain, from me to"), new XElement("LINE", "you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What man dost thou dig it for?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "For no man, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What woman, then?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "For none, neither.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Who is to be buried in't?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "One that was a woman, sir; but, rest her soul, she's dead.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How absolute the knave is! we must speak by the"), new XElement("LINE", "card, or equivocation will undo us. By the Lord,"), new XElement("LINE", "Horatio, these three years I have taken a note of"), new XElement("LINE", "it; the age is grown so picked that the toe of the"), new XElement("LINE", "peasant comes so near the heel of the courtier, he"), new XElement("LINE", "gaffs his kibe. How long hast thou been a"), new XElement("LINE", "grave-maker?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Of all the days i' the year, I came to't that day"), new XElement("LINE", "that our last king Hamlet overcame Fortinbras.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How long is that since?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Cannot you tell that? every fool can tell that: it"), new XElement("LINE", "was the very day that young Hamlet was born; he that"), new XElement("LINE", "is mad, and sent into England.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, marry, why was he sent into England?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Why, because he was mad: he shall recover his wits"), new XElement("LINE", "there; or, if he do not, it's no great matter there.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "'Twill, a not be seen in him there; there the men"), new XElement("LINE", "are as mad as he.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How came he mad?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Very strangely, they say.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How strangely?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Faith, e'en with losing his wits.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Upon what ground?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Why, here in Denmark: I have been sexton here, man"), new XElement("LINE", "and boy, thirty years.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How long will a man lie i' the earth ere he rot?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "I' faith, if he be not rotten before he die--as we"), new XElement("LINE", "have many pocky corses now-a-days, that will scarce"), new XElement("LINE", "hold the laying in--he will last you some eight year"), new XElement("LINE", "or nine year: a tanner will last you nine year.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why he more than another?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Why, sir, his hide is so tanned with his trade, that"), new XElement("LINE", "he will keep out water a great while; and your water"), new XElement("LINE", "is a sore decayer of your whoreson dead body."), new XElement("LINE", "Here's a skull now; this skull has lain in the earth"), new XElement("LINE", "three and twenty years.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Whose was it?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "A whoreson mad fellow's it was: whose do you think it was?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, I know not.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "A pestilence on him for a mad rogue! a' poured a"), new XElement("LINE", "flagon of Rhenish on my head once. This same skull,"), new XElement("LINE", "sir, was Yorick's skull, the king's jester.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "This?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "E'en that.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Let me see."), new XElement("STAGEDIR", "Takes the skull"), new XElement("LINE", "Alas, poor Yorick! I knew him, Horatio: a fellow"), new XElement("LINE", "of infinite jest, of most excellent fancy: he hath"), new XElement("LINE", "borne me on his back a thousand times; and now, how"), new XElement("LINE", "abhorred in my imagination it is! my gorge rims at"), new XElement("LINE", "it. Here hung those lips that I have kissed I know"), new XElement("LINE", "not how oft. Where be your gibes now? your"), new XElement("LINE", "gambols? your songs? your flashes of merriment,"), new XElement("LINE", "that were wont to set the table on a roar? Not one"), new XElement("LINE", "now, to mock your own grinning? quite chap-fallen?"), new XElement("LINE", "Now get you to my lady's chamber, and tell her, let"), new XElement("LINE", "her paint an inch thick, to this favour she must"), new XElement("LINE", "come; make her laugh at that. Prithee, Horatio, tell"), new XElement("LINE", "me one thing.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What's that, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Dost thou think Alexander looked o' this fashion i'"), new XElement("LINE", "the earth?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "E'en so.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "And smelt so? pah!") ), new XElement("STAGEDIR", "Puts down the skull"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "E'en so, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "To what base uses we may return, Horatio! Why may"), new XElement("LINE", "not imagination trace the noble dust of Alexander,"), new XElement("LINE", "till he find it stopping a bung-hole?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "'Twere to consider too curiously, to consider so.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, faith, not a jot; but to follow him thither with"), new XElement("LINE", "modesty enough, and likelihood to lead it: as"), new XElement("LINE", "thus: Alexander died, Alexander was buried,"), new XElement("LINE", "Alexander returneth into dust; the dust is earth; of"), new XElement("LINE", "earth we make loam; and why of that loam, whereto he"), new XElement("LINE", "was converted, might they not stop a beer-barrel?"), new XElement("LINE", "Imperious Caesar, dead and turn'd to clay,"), new XElement("LINE", "Might stop a hole to keep the wind away:"), new XElement("LINE", "O, that that earth, which kept the world in awe,"), new XElement("LINE", "Should patch a wall to expel the winter flaw!"), new XElement("LINE", "But soft! but soft! aside: here comes the king."), new XElement("STAGEDIR", "Enter Priest, &c. in procession; the Corpse of\n" + "OPHELIA, LAERTES and Mourners following; KING\n" + "CLAUDIUS, QUEEN GERTRUDE, their trains, &c" ), new XElement("LINE", "The queen, the courtiers: who is this they follow?"), new XElement("LINE", "And with such maimed rites? This doth betoken"), new XElement("LINE", "The corse they follow did with desperate hand"), new XElement("LINE", "Fordo its own life: 'twas of some estate."), new XElement("LINE", "Couch we awhile, and mark.") ), new XElement("STAGEDIR", "Retiring with HORATIO"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "What ceremony else?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That is Laertes,"), new XElement("LINE", "A very noble youth: mark.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "What ceremony else?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Priest"), new XElement("LINE", "Her obsequies have been as far enlarged"), new XElement("LINE", "As we have warrantise: her death was doubtful;"), new XElement("LINE", "And, but that great command o'ersways the order,"), new XElement("LINE", "She should in ground unsanctified have lodged"), new XElement("LINE", "Till the last trumpet: for charitable prayers,"), new XElement("LINE", "Shards, flints and pebbles should be thrown on her;"), new XElement("LINE", "Yet here she is allow'd her virgin crants,"), new XElement("LINE", "Her maiden strewments and the bringing home"), new XElement("LINE", "Of bell and burial.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Must there no more be done?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Priest"), new XElement("LINE", "No more be done:"), new XElement("LINE", "We should profane the service of the dead"), new XElement("LINE", "To sing a requiem and such rest to her"), new XElement("LINE", "As to peace-parted souls.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Lay her i' the earth:"), new XElement("LINE", "And from her fair and unpolluted flesh"), new XElement("LINE", "May violets spring! I tell thee, churlish priest,"), new XElement("LINE", "A ministering angel shall my sister be,"), new XElement("LINE", "When thou liest howling.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What, the fair Ophelia!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Sweets to the sweet: farewell!"), new XElement("STAGEDIR", "Scattering flowers"), new XElement("LINE", "I hoped thou shouldst have been my Hamlet's wife;"), new XElement("LINE", "I thought thy bride-bed to have deck'd, sweet maid,"), new XElement("LINE", "And not have strew'd thy grave.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "O, treble woe"), new XElement("LINE", "Fall ten times treble on that cursed head,"), new XElement("LINE", "Whose wicked deed thy most ingenious sense"), new XElement("LINE", "Deprived thee of! Hold off the earth awhile,"), new XElement("LINE", "Till I have caught her once more in mine arms:"), new XElement("STAGEDIR", "Leaps into the grave"), new XElement("LINE", "Now pile your dust upon the quick and dead,"), new XElement("LINE", "Till of this flat a mountain you have made,"), new XElement("LINE", "To o'ertop old Pelion, or the skyish head"), new XElement("LINE", "Of blue Olympus.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Advancing"), " What is he whose grief" ), new XElement("LINE", "Bears such an emphasis? whose phrase of sorrow"), new XElement("LINE", "Conjures the wandering stars, and makes them stand"), new XElement("LINE", "Like wonder-wounded hearers? This is I,"), new XElement("LINE", "Hamlet the Dane.") ), new XElement("STAGEDIR", "Leaps into the grave"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "The devil take thy soul!") ), new XElement("STAGEDIR", "Grappling with him"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Thou pray'st not well."), new XElement("LINE", "I prithee, take thy fingers from my throat;"), new XElement("LINE", "For, though I am not splenitive and rash,"), new XElement("LINE", "Yet have I something in me dangerous,"), new XElement("LINE", "Which let thy wiseness fear: hold off thy hand.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Pluck them asunder.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Hamlet, Hamlet!") ), new XElement("SPEECH", new XElement("SPEAKER", "All"), new XElement("LINE", "Gentlemen,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Good my lord, be quiet.") ), new XElement("STAGEDIR", "The Attendants part them, and they come out of the grave"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why I will fight with him upon this theme"), new XElement("LINE", "Until my eyelids will no longer wag.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O my son, what theme?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I loved Ophelia: forty thousand brothers"), new XElement("LINE", "Could not, with all their quantity of love,"), new XElement("LINE", "Make up my sum. What wilt thou do for her?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O, he is mad, Laertes.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "For love of God, forbear him.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Swounds, show me what thou'lt do:"), new XElement("LINE", "Woo't weep? woo't fight? woo't fast? woo't tear thyself?"), new XElement("LINE", "Woo't drink up eisel? eat a crocodile?"), new XElement("LINE", "I'll do't. Dost thou come here to whine?"), new XElement("LINE", "To outface me with leaping in her grave?"), new XElement("LINE", "Be buried quick with her, and so will I:"), new XElement("LINE", "And, if thou prate of mountains, let them throw"), new XElement("LINE", "Millions of acres on us, till our ground,"), new XElement("LINE", "Singeing his pate against the burning zone,"), new XElement("LINE", "Make Ossa like a wart! Nay, an thou'lt mouth,"), new XElement("LINE", "I'll rant as well as thou.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "This is mere madness:"), new XElement("LINE", "And thus awhile the fit will work on him;"), new XElement("LINE", "Anon, as patient as the female dove,"), new XElement("LINE", "When that her golden couplets are disclosed,"), new XElement("LINE", "His silence will sit drooping.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Hear you, sir;"), new XElement("LINE", "What is the reason that you use me thus?"), new XElement("LINE", "I loved you ever: but it is no matter;"), new XElement("LINE", "Let Hercules himself do what he may,"), new XElement("LINE", "The cat will mew and dog will have his day.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I pray you, good Horatio, wait upon him."), new XElement("STAGEDIR", "Exit HORATIO"), new XElement("STAGEDIR", "To LAERTES"), new XElement("LINE", "Strengthen your patience in our last night's speech;"), new XElement("LINE", "We'll put the matter to the present push."), new XElement("LINE", "Good Gertrude, set some watch over your son."), new XElement("LINE", "This grave shall have a living monument:"), new XElement("LINE", "An hour of quiet shortly shall we see;"), new XElement("LINE", "Till then, in patience our proceeding be.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE II. A hall in the castle."), new XElement("STAGEDIR", "Enter HAMLET and HORATIO"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "So much for this, sir: now shall you see the other;"), new XElement("LINE", "You do remember all the circumstance?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Remember it, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, in my heart there was a kind of fighting,"), new XElement("LINE", "That would not let me sleep: methought I lay"), new XElement("LINE", "Worse than the mutines in the bilboes. Rashly,"), new XElement("LINE", "And praised be rashness for it, let us know,"), new XElement("LINE", "Our indiscretion sometimes serves us well,"), new XElement("LINE", "When our deep plots do pall: and that should teach us"), new XElement("LINE", "There's a divinity that shapes our ends,"), new XElement("LINE", "Rough-hew them how we will,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "That is most certain.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Up from my cabin,"), new XElement("LINE", "My sea-gown scarf'd about me, in the dark"), new XElement("LINE", "Groped I to find out them; had my desire."), new XElement("LINE", "Finger'd their packet, and in fine withdrew"), new XElement("LINE", "To mine own room again; making so bold,"), new XElement("LINE", "My fears forgetting manners, to unseal"), new XElement("LINE", "Their grand commission; where I found, Horatio,--"), new XElement("LINE", "O royal knavery!--an exact command,"), new XElement("LINE", "Larded with many several sorts of reasons"), new XElement("LINE", "Importing Denmark's health and England's too,"), new XElement("LINE", "With, ho! such bugs and goblins in my life,"), new XElement("LINE", "That, on the supervise, no leisure bated,"), new XElement("LINE", "No, not to stay the grinding of the axe,"), new XElement("LINE", "My head should be struck off.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Is't possible?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Here's the commission: read it at more leisure."), new XElement("LINE", "But wilt thou hear me how I did proceed?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I beseech you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Being thus be-netted round with villanies,--"), new XElement("LINE", "Ere I could make a prologue to my brains,"), new XElement("LINE", "They had begun the play--I sat me down,"), new XElement("LINE", "Devised a new commission, wrote it fair:"), new XElement("LINE", "I once did hold it, as our statists do,"), new XElement("LINE", "A baseness to write fair and labour'd much"), new XElement("LINE", "How to forget that learning, but, sir, now"), new XElement("LINE", "It did me yeoman's service: wilt thou know"), new XElement("LINE", "The effect of what I wrote?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Ay, good my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "An earnest conjuration from the king,"), new XElement("LINE", "As England was his faithful tributary,"), new XElement("LINE", "As love between them like the palm might flourish,"), new XElement("LINE", "As peace should stiff her wheaten garland wear"), new XElement("LINE", "And stand a comma 'tween their amities,"), new XElement("LINE", "And many such-like 'As'es of great charge,"), new XElement("LINE", "That, on the view and knowing of these contents,"), new XElement("LINE", "Without debatement further, more or less,"), new XElement("LINE", "He should the bearers put to sudden death,"), new XElement("LINE", "Not shriving-time allow'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "How was this seal'd?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, even in that was heaven ordinant."), new XElement("LINE", "I had my father's signet in my purse,"), new XElement("LINE", "Which was the model of that Danish seal;"), new XElement("LINE", "Folded the writ up in form of the other,"), new XElement("LINE", "Subscribed it, gave't the impression, placed it safely,"), new XElement("LINE", "The changeling never known. Now, the next day"), new XElement("LINE", "Was our sea-fight; and what to this was sequent"), new XElement("LINE", "Thou know'st already.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "So Guildenstern and Rosencrantz go to't.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, man, they did make love to this employment;"), new XElement("LINE", "They are not near my conscience; their defeat"), new XElement("LINE", "Does by their own insinuation grow:"), new XElement("LINE", "'Tis dangerous when the baser nature comes"), new XElement("LINE", "Between the pass and fell incensed points"), new XElement("LINE", "Of mighty opposites.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Why, what a king is this!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Does it not, think'st thee, stand me now upon--"), new XElement("LINE", "He that hath kill'd my king and whored my mother,"), new XElement("LINE", "Popp'd in between the election and my hopes,"), new XElement("LINE", "Thrown out his angle for my proper life,"), new XElement("LINE", "And with such cozenage--is't not perfect conscience,"), new XElement("LINE", "To quit him with this arm? and is't not to be damn'd,"), new XElement("LINE", "To let this canker of our nature come"), new XElement("LINE", "In further evil?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It must be shortly known to him from England"), new XElement("LINE", "What is the issue of the business there.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It will be short: the interim is mine;"), new XElement("LINE", "And a man's life's no more than to say 'One.'"), new XElement("LINE", "But I am very sorry, good Horatio,"), new XElement("LINE", "That to Laertes I forgot myself;"), new XElement("LINE", "For, by the image of my cause, I see"), new XElement("LINE", "The portraiture of his: I'll court his favours."), new XElement("LINE", "But, sure, the bravery of his grief did put me"), new XElement("LINE", "Into a towering passion.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Peace! who comes here?") ), new XElement("STAGEDIR", "Enter OSRIC"), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Your lordship is right welcome back to Denmark.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I humbly thank you, sir. Dost know this water-fly?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "No, my good lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Thy state is the more gracious; for 'tis a vice to"), new XElement("LINE", "know him. He hath much land, and fertile: let a"), new XElement("LINE", "beast be lord of beasts, and his crib shall stand at"), new XElement("LINE", "the king's mess: 'tis a chough; but, as I say,"), new XElement("LINE", "spacious in the possession of dirt.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Sweet lord, if your lordship were at leisure, I"), new XElement("LINE", "should impart a thing to you from his majesty.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I will receive it, sir, with all diligence of"), new XElement("LINE", "spirit. Put your bonnet to his right use; 'tis for the head.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "I thank your lordship, it is very hot.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, believe me, 'tis very cold; the wind is"), new XElement("LINE", "northerly.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "It is indifferent cold, my lord, indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "But yet methinks it is very sultry and hot for my"), new XElement("LINE", "complexion.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Exceedingly, my lord; it is very sultry,--as"), new XElement("LINE", "'twere,--I cannot tell how. But, my lord, his"), new XElement("LINE", "majesty bade me signify to you that he has laid a"), new XElement("LINE", "great wager on your head: sir, this is the matter,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I beseech you, remember--") ), new XElement("STAGEDIR", "HAMLET moves him to put on his hat"), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Nay, good my lord; for mine ease, in good faith."), new XElement("LINE", "Sir, here is newly come to court Laertes; believe"), new XElement("LINE", "me, an absolute gentleman, full of most excellent"), new XElement("LINE", "differences, of very soft society and great showing:"), new XElement("LINE", "indeed, to speak feelingly of him, he is the card or"), new XElement("LINE", "calendar of gentry, for you shall find in him the"), new XElement("LINE", "continent of what part a gentleman would see.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, his definement suffers no perdition in you;"), new XElement("LINE", "though, I know, to divide him inventorially would"), new XElement("LINE", "dizzy the arithmetic of memory, and yet but yaw"), new XElement("LINE", "neither, in respect of his quick sail. But, in the"), new XElement("LINE", "verity of extolment, I take him to be a soul of"), new XElement("LINE", "great article; and his infusion of such dearth and"), new XElement("LINE", "rareness, as, to make true diction of him, his"), new XElement("LINE", "semblable is his mirror; and who else would trace"), new XElement("LINE", "him, his umbrage, nothing more.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Your lordship speaks most infallibly of him.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The concernancy, sir? why do we wrap the gentleman"), new XElement("LINE", "in our more rawer breath?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Sir?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Is't not possible to understand in another tongue?"), new XElement("LINE", "You will do't, sir, really.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What imports the nomination of this gentleman?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Of Laertes?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "His purse is empty already; all's golden words are spent.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Of him, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "I know you are not ignorant--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I would you did, sir; yet, in faith, if you did,"), new XElement("LINE", "it would not much approve me. Well, sir?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "You are not ignorant of what excellence Laertes is--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I dare not confess that, lest I should compare with"), new XElement("LINE", "him in excellence; but, to know a man well, were to"), new XElement("LINE", "know himself.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "I mean, sir, for his weapon; but in the imputation"), new XElement("LINE", "laid on him by them, in his meed he's unfellowed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What's his weapon?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Rapier and dagger.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That's two of his weapons: but, well.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "The king, sir, hath wagered with him six Barbary"), new XElement("LINE", "horses: against the which he has imponed, as I take"), new XElement("LINE", "it, six French rapiers and poniards, with their"), new XElement("LINE", "assigns, as girdle, hangers, and so: three of the"), new XElement("LINE", "carriages, in faith, are very dear to fancy, very"), new XElement("LINE", "responsive to the hilts, most delicate carriages,"), new XElement("LINE", "and of very liberal conceit.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What call you the carriages?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I knew you must be edified by the margent ere you had done.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "The carriages, sir, are the hangers.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The phrase would be more german to the matter, if we"), new XElement("LINE", "could carry cannon by our sides: I would it might"), new XElement("LINE", "be hangers till then. But, on: six Barbary horses"), new XElement("LINE", "against six French swords, their assigns, and three"), new XElement("LINE", "liberal-conceited carriages; that's the French bet"), new XElement("LINE", "against the Danish. Why is this 'imponed,' as you call it?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "The king, sir, hath laid, that in a dozen passes"), new XElement("LINE", "between yourself and him, he shall not exceed you"), new XElement("LINE", "three hits: he hath laid on twelve for nine; and it"), new XElement("LINE", "would come to immediate trial, if your lordship"), new XElement("LINE", "would vouchsafe the answer.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How if I answer 'no'?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "I mean, my lord, the opposition of your person in trial.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, I will walk here in the hall: if it please his"), new XElement("LINE", "majesty, 'tis the breathing time of day with me; let"), new XElement("LINE", "the foils be brought, the gentleman willing, and the"), new XElement("LINE", "king hold his purpose, I will win for him an I can;"), new XElement("LINE", "if not, I will gain nothing but my shame and the odd hits.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Shall I re-deliver you e'en so?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "To this effect, sir; after what flourish your nature will.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "I commend my duty to your lordship.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Yours, yours."), new XElement("STAGEDIR", "Exit OSRIC"), new XElement("LINE", "He does well to commend it himself; there are no"), new XElement("LINE", "tongues else for's turn.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "This lapwing runs away with the shell on his head.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "He did comply with his dug, before he sucked it."), new XElement("LINE", "Thus has he--and many more of the same bevy that I"), new XElement("LINE", "know the dressy age dotes on--only got the tune of"), new XElement("LINE", "the time and outward habit of encounter; a kind of"), new XElement("LINE", "yesty collection, which carries them through and"), new XElement("LINE", "through the most fond and winnowed opinions; and do"), new XElement("LINE", "but blow them to their trial, the bubbles are out.") ), new XElement("STAGEDIR", "Enter a Lord"), new XElement("SPEECH", new XElement("SPEAKER", "Lord"), new XElement("LINE", "My lord, his majesty commended him to you by young"), new XElement("LINE", "Osric, who brings back to him that you attend him in"), new XElement("LINE", "the hall: he sends to know if your pleasure hold to"), new XElement("LINE", "play with Laertes, or that you will take longer time.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am constant to my purpose; they follow the king's"), new XElement("LINE", "pleasure: if his fitness speaks, mine is ready; now"), new XElement("LINE", "or whensoever, provided I be so able as now.") ), new XElement("SPEECH", new XElement("SPEAKER", "Lord"), new XElement("LINE", "The king and queen and all are coming down.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "In happy time.") ), new XElement("SPEECH", new XElement("SPEAKER", "Lord"), new XElement("LINE", "The queen desires you to use some gentle"), new XElement("LINE", "entertainment to Laertes before you fall to play.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "She well instructs me.") ), new XElement("STAGEDIR", "Exit Lord"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "You will lose this wager, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I do not think so: since he went into France, I"), new XElement("LINE", "have been in continual practise: I shall win at the"), new XElement("LINE", "odds. But thou wouldst not think how ill all's here"), new XElement("LINE", "about my heart: but it is no matter.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Nay, good my lord,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It is but foolery; but it is such a kind of"), new XElement("LINE", "gain-giving, as would perhaps trouble a woman.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "If your mind dislike any thing, obey it: I will"), new XElement("LINE", "forestall their repair hither, and say you are not"), new XElement("LINE", "fit.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Not a whit, we defy augury: there's a special"), new XElement("LINE", "providence in the fall of a sparrow. If it be now,"), new XElement("LINE", "'tis not to come; if it be not to come, it will be"), new XElement("LINE", "now; if it be not now, yet it will come: the"), new XElement("LINE", "readiness is all: since no man has aught of what he"), new XElement("LINE", "leaves, what is't to leave betimes?") ), new XElement("STAGEDIR", "Enter KING CLAUDIUS, QUEEN GERTRUDE, LAERTES,\n" + "Lords, OSRIC, and Attendants with foils, &c" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Come, Hamlet, come, and take this hand from me.") ), new XElement("STAGEDIR", "KING CLAUDIUS puts LAERTES' hand into HAMLET's"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Give me your pardon, sir: I've done you wrong;"), new XElement("LINE", "But pardon't, as you are a gentleman."), new XElement("LINE", "This presence knows,"), new XElement("LINE", "And you must needs have heard, how I am punish'd"), new XElement("LINE", "With sore distraction. What I have done,"), new XElement("LINE", "That might your nature, honour and exception"), new XElement("LINE", "Roughly awake, I here proclaim was madness."), new XElement("LINE", "Was't Hamlet wrong'd Laertes? Never Hamlet:"), new XElement("LINE", "If Hamlet from himself be ta'en away,"), new XElement("LINE", "And when he's not himself does wrong Laertes,"), new XElement("LINE", "Then Hamlet does it not, Hamlet denies it."), new XElement("LINE", "Who does it, then? His madness: if't be so,"), new XElement("LINE", "Hamlet is of the faction that is wrong'd;"), new XElement("LINE", "His madness is poor Hamlet's enemy."), new XElement("LINE", "Sir, in this audience,"), new XElement("LINE", "Let my disclaiming from a purposed evil"), new XElement("LINE", "Free me so far in your most generous thoughts,"), new XElement("LINE", "That I have shot mine arrow o'er the house,"), new XElement("LINE", "And hurt my brother.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I am satisfied in nature,"), new XElement("LINE", "Whose motive, in this case, should stir me most"), new XElement("LINE", "To my revenge: but in my terms of honour"), new XElement("LINE", "I stand aloof; and will no reconcilement,"), new XElement("LINE", "Till by some elder masters, of known honour,"), new XElement("LINE", "I have a voice and precedent of peace,"), new XElement("LINE", "To keep my name ungored. But till that time,"), new XElement("LINE", "I do receive your offer'd love like love,"), new XElement("LINE", "And will not wrong it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I embrace it freely;"), new XElement("LINE", "And will this brother's wager frankly play."), new XElement("LINE", "Give us the foils. Come on.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Come, one for me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I'll be your foil, Laertes: in mine ignorance"), new XElement("LINE", "Your skill shall, like a star i' the darkest night,"), new XElement("LINE", "Stick fiery off indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "You mock me, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, by this hand.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Give them the foils, young Osric. Cousin Hamlet,"), new XElement("LINE", "You know the wager?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Very well, my lord"), new XElement("LINE", "Your grace hath laid the odds o' the weaker side.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I do not fear it; I have seen you both:"), new XElement("LINE", "But since he is better'd, we have therefore odds.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "This is too heavy, let me see another.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "This likes me well. These foils have all a length?") ), new XElement("STAGEDIR", "They prepare to play"), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Ay, my good lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Set me the stoops of wine upon that table."), new XElement("LINE", "If Hamlet give the first or second hit,"), new XElement("LINE", "Or quit in answer of the third exchange,"), new XElement("LINE", "Let all the battlements their ordnance fire:"), new XElement("LINE", "The king shall drink to Hamlet's better breath;"), new XElement("LINE", "And in the cup an union shall he throw,"), new XElement("LINE", "Richer than that which four successive kings"), new XElement("LINE", "In Denmark's crown have worn. Give me the cups;"), new XElement("LINE", "And let the kettle to the trumpet speak,"), new XElement("LINE", "The trumpet to the cannoneer without,"), new XElement("LINE", "The cannons to the heavens, the heavens to earth,"), new XElement("LINE", "'Now the king dunks to Hamlet.' Come, begin:"), new XElement("LINE", "And you, the judges, bear a wary eye.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Come on, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Come, my lord.") ), new XElement("STAGEDIR", "They play"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "One.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "No.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Judgment.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "A hit, a very palpable hit.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Well; again.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Stay; give me drink. Hamlet, this pearl is thine;"), new XElement("LINE", "Here's to thy health."), new XElement("STAGEDIR", "Trumpets sound, and cannon shot off within"), new XElement("LINE", "Give him the cup.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I'll play this bout first; set it by awhile. Come."), new XElement("STAGEDIR", "They play"), new XElement("LINE", "Another hit; what say you?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "A touch, a touch, I do confess.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Our son shall win.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "He's fat, and scant of breath."), new XElement("LINE", "Here, Hamlet, take my napkin, rub thy brows;"), new XElement("LINE", "The queen carouses to thy fortune, Hamlet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Good madam!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Gertrude, do not drink.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "I will, my lord; I pray you, pardon me.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " It is the poison'd cup: it is too late." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I dare not drink yet, madam; by and by.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Come, let me wipe thy face.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "My lord, I'll hit him now.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I do not think't.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " And yet 'tis almost 'gainst my conscience." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Come, for the third, Laertes: you but dally;"), new XElement("LINE", "I pray you, pass with your best violence;"), new XElement("LINE", "I am afeard you make a wanton of me.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Say you so? come on.") ), new XElement("STAGEDIR", "They play"), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Nothing, neither way.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Have at you now!") ), new XElement("STAGEDIR", "LAERTES wounds HAMLET; then in scuffling, they\n" + "change rapiers, and HAMLET wounds LAERTES" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Part them; they are incensed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, come, again.") ), new XElement("STAGEDIR", "QUEEN GERTRUDE falls"), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Look to the queen there, ho!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "They bleed on both sides. How is it, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "How is't, Laertes?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Why, as a woodcock to mine own springe, Osric;"), new XElement("LINE", "I am justly kill'd with mine own treachery.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How does the queen?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "She swounds to see them bleed.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "No, no, the drink, the drink,--O my dear Hamlet,--"), new XElement("LINE", "The drink, the drink! I am poison'd.") ), new XElement("STAGEDIR", "Dies"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O villany! Ho! let the door be lock'd:"), new XElement("LINE", "Treachery! Seek it out.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "It is here, Hamlet: Hamlet, thou art slain;"), new XElement("LINE", "No medicine in the world can do thee good;"), new XElement("LINE", "In thee there is not half an hour of life;"), new XElement("LINE", "The treacherous instrument is in thy hand,"), new XElement("LINE", "Unbated and envenom'd: the foul practise"), new XElement("LINE", "Hath turn'd itself on me lo, here I lie,"), new XElement("LINE", "Never to rise again: thy mother's poison'd:"), new XElement("LINE", "I can no more: the king, the king's to blame.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The point!--envenom'd too!"), new XElement("LINE", "Then, venom, to thy work.") ), new XElement("STAGEDIR", "Stabs KING CLAUDIUS"), new XElement("SPEECH", new XElement("SPEAKER", "All"), new XElement("LINE", "Treason! treason!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O, yet defend me, friends; I am but hurt.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Here, thou incestuous, murderous, damned Dane,"), new XElement("LINE", "Drink off this potion. Is thy union here?"), new XElement("LINE", "Follow my mother.") ), new XElement("STAGEDIR", "KING CLAUDIUS dies"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "He is justly served;"), new XElement("LINE", "It is a poison temper'd by himself."), new XElement("LINE", "Exchange forgiveness with me, noble Hamlet:"), new XElement("LINE", "Mine and my father's death come not upon thee,"), new XElement("LINE", "Nor thine on me.") ), new XElement("STAGEDIR", "Dies"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Heaven make thee free of it! I follow thee."), new XElement("LINE", "I am dead, Horatio. Wretched queen, adieu!"), new XElement("LINE", "You that look pale and tremble at this chance,"), new XElement("LINE", "That are but mutes or audience to this act,"), new XElement("LINE", "Had I but time--as this fell sergeant, death,"), new XElement("LINE", "Is strict in his arrest--O, I could tell you--"), new XElement("LINE", "But let it be. Horatio, I am dead;"), new XElement("LINE", "Thou livest; report me and my cause aright"), new XElement("LINE", "To the unsatisfied.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Never believe it:"), new XElement("LINE", "I am more an antique Roman than a Dane:"), new XElement("LINE", "Here's yet some liquor left.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "As thou'rt a man,"), new XElement("LINE", "Give me the cup: let go; by heaven, I'll have't."), new XElement("LINE", "O good Horatio, what a wounded name,"), new XElement("LINE", "Things standing thus unknown, shall live behind me!"), new XElement("LINE", "If thou didst ever hold me in thy heart"), new XElement("LINE", "Absent thee from felicity awhile,"), new XElement("LINE", "And in this harsh world draw thy breath in pain,"), new XElement("LINE", "To tell my story."), new XElement("STAGEDIR", "March afar off, and shot within"), new XElement("LINE", "What warlike noise is this?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Young Fortinbras, with conquest come from Poland,"), new XElement("LINE", "To the ambassadors of England gives"), new XElement("LINE", "This warlike volley.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, I die, Horatio;"), new XElement("LINE", "The potent poison quite o'er-crows my spirit:"), new XElement("LINE", "I cannot live to hear the news from England;"), new XElement("LINE", "But I do prophesy the election lights"), new XElement("LINE", "On Fortinbras: he has my dying voice;"), new XElement("LINE", "So tell him, with the occurrents, more and less,"), new XElement("LINE", "Which have solicited. The rest is silence.") ), new XElement("STAGEDIR", "Dies"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Now cracks a noble heart. Good night sweet prince:"), new XElement("LINE", "And flights of angels sing thee to thy rest!"), new XElement("LINE", "Why does the drum come hither?") ), new XElement("STAGEDIR", "March within"), new XElement("STAGEDIR", "Enter FORTINBRAS, the English Ambassadors,\n" + "and others" ), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "Where is this sight?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What is it ye would see?"), new XElement("LINE", "If aught of woe or wonder, cease your search.") ), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "This quarry cries on havoc. O proud death,"), new XElement("LINE", "What feast is toward in thine eternal cell,"), new XElement("LINE", "That thou so many princes at a shot"), new XElement("LINE", "So bloodily hast struck?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Ambassador"), new XElement("LINE", "The sight is dismal;"), new XElement("LINE", "And our affairs from England come too late:"), new XElement("LINE", "The ears are senseless that should give us hearing,"), new XElement("LINE", "To tell him his commandment is fulfill'd,"), new XElement("LINE", "That Rosencrantz and Guildenstern are dead:"), new XElement("LINE", "Where should we have our thanks?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Not from his mouth,"), new XElement("LINE", "Had it the ability of life to thank you:"), new XElement("LINE", "He never gave commandment for their death."), new XElement("LINE", "But since, so jump upon this bloody question,"), new XElement("LINE", "You from the Polack wars, and you from England,"), new XElement("LINE", "Are here arrived give order that these bodies"), new XElement("LINE", "High on a stage be placed to the view;"), new XElement("LINE", "And let me speak to the yet unknowing world"), new XElement("LINE", "How these things came about: so shall you hear"), new XElement("LINE", "Of carnal, bloody, and unnatural acts,"), new XElement("LINE", "Of accidental judgments, casual slaughters,"), new XElement("LINE", "Of deaths put on by cunning and forced cause,"), new XElement("LINE", "And, in this upshot, purposes mistook"), new XElement("LINE", "Fall'n on the inventors' reads: all this can I"), new XElement("LINE", "Truly deliver.") ), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "Let us haste to hear it,"), new XElement("LINE", "And call the noblest to the audience."), new XElement("LINE", "For me, with sorrow I embrace my fortune:"), new XElement("LINE", "I have some rights of memory in this kingdom,"), new XElement("LINE", "Which now to claim my vantage doth invite me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Of that I shall have also cause to speak,"), new XElement("LINE", "And from his mouth whose voice will draw on more;"), new XElement("LINE", "But let this same be presently perform'd,"), new XElement("LINE", "Even while men's minds are wild; lest more mischance"), new XElement("LINE", "On plots and errors, happen.") ), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "Let four captains"), new XElement("LINE", "Bear Hamlet, like a soldier, to the stage;"), new XElement("LINE", "For he was likely, had he been put on,"), new XElement("LINE", "To have proved most royally: and, for his passage,"), new XElement("LINE", "The soldiers' music and the rites of war"), new XElement("LINE", "Speak loudly for him."), new XElement("LINE", "Take up the bodies: such a sight as this"), new XElement("LINE", "Becomes the field, but here shows much amiss."), new XElement("LINE", "Go, bid the soldiers shoot.") ), new XElement("STAGEDIR", "A dead march. Exeunt, bearing off the dead\n" + "bodies; after which a peal of ordnance is shot off") ) ) ) ); xmlDoc = XDocument.Parse(xDoc.ToString(SaveOptions.DisableFormatting)); } } }
// 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 System.Linq; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.Linq; using XmlCoreTest.Common; namespace CoreXml.Test.XLinq { // used in DOMXmlFiles public enum DocumentStatus { valid, invalid, notWellFormed, all } ////////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Class for input generation used by all tests /// </summary> ////////////////////////////////////////////////////////////////////////////////////////////////////// public static class InputSpace { // loads either the file for DMLCreate public static void Load(object loadObject, ref XDocument xDoc, ref XDocument xmlDoc) { Load(loadObject as string, ref xDoc, ref xmlDoc); } // Creates XDocument and XmlDocument from a input file public static void Load(string fileName, ref XDocument xDoc, ref XDocument xmlDoc) { XmlReaderSettings rs = new XmlReaderSettings(); rs.IgnoreWhitespace = true; rs.DtdProcessing = DtdProcessing.Ignore; string filePath = Path.Combine("TestData", "XLinq", fileName); using (XmlReader r1 = XmlReader.Create(FilePathUtil.getStream(filePath), rs)) xDoc = XDocument.Load(r1); using (XmlReader r2 = XmlReader.Create(FilePathUtil.getStream(filePath), rs)) { xmlDoc = XDocument.Load(r2); } } // List of input xml files used in DOM Control files public static IEnumerable<string> DOMXmlFiles(DocumentStatus docStatus) { string status, file, filePath; XNamespace ns = "WebData/TestSpec"; // look in each one of the DOM test control files for xml files used foreach (string controlFile in DOMControlFiles()) { XDocument xDoc = null; XmlReaderSettings rs = new XmlReaderSettings(); rs.IgnoreWhitespace = true; using (XmlReader reader = XmlReader.Create(FilePathUtil.getStream(controlFile), rs)) { xDoc = XDocument.Load(reader); } // get the filePath from the control file filePath = (string)xDoc.Descendants(ns + "global").Attributes("filePath").FirstOrDefault(); if (filePath.StartsWith(@"$(DataPath)\StandardTests\")) { filePath = Path.Combine(XLinqTestCase.StandardPath, filePath.Substring(@"$(DataPath)\StandardTests\".Length)); } // get xml file used in each variation foreach (XElement e in xDoc.Descendants(ns + "variation").Where(x => x.Attribute("implemented").Value == "true")) { file = e.Descendants(ns + "xml").FirstOrDefault().Value.Trim(); file = Path.Combine(filePath, file); // check if the file exists, if not then continue try { if (FilePathUtil.getStream(file) == null) continue; } catch (Exception) { continue; } // if there are more than one "result" nodes then find the one that is used for System.Xml IEnumerable<XElement> resultNodes = e.Descendants(ns + "result"); IEnumerable<XElement> systemXml = e.Descendants(ns + "System.Xml"); if (resultNodes.Count() > 1 && systemXml.Count() > 0) { string resultID = (string)systemXml.Select(x => x.Element(ns + "expectedResult")).Attributes("id").FirstOrDefault(); status = (string)resultNodes.Where(x => x.Attribute("id").Value == resultID).Attributes("expected").FirstOrDefault(); } else status = (string)resultNodes.Attributes("expected").FirstOrDefault(); switch (docStatus) { case DocumentStatus.valid: if ("valid".Equals(status)) yield return file; break; case DocumentStatus.invalid: if ("invalid".Equals(status)) yield return file; break; case DocumentStatus.notWellFormed: if ("not-wf".Equals(status)) yield return file; break; default: yield return file; break; } } } } // List of control files used in DOM tests public static IEnumerable<string> DOMControlFiles() { XDocument xDoc = null; XmlReaderSettings rs = new XmlReaderSettings(); rs.IgnoreWhitespace = true; string masterControlFile = @"xlinq_master_xml.xml"; using (XmlReader reader = XmlReader.Create(FilePathUtil.getStream(masterControlFile), rs)) { xDoc = XDocument.Load(reader); } // Get test specific control files foreach (XElement x in xDoc.Descendants("testCase")) { yield return ((string)x.Attribute("uri")); } } public static XElement GetElement(int elementCount, int childElementCount) { XElement root = new XElement("root"); for (int l = 0; l < elementCount; l++) { XElement nl = new XElement("e" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); root.Add(nl); for (int e = 0; e < childElementCount; e++) { XElement child = new XElement("e" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); nl.Add(child); } } return root; } public static XElement GetAttributeElement(int elementCount, int attributeCount) { XElement root = new XElement("root"); for (int l = 0; l < elementCount; l++) { XElement nl = new XElement("e" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); for (int a = 0; a < attributeCount; a++) { XAttribute attribute = new XAttribute("a" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); nl.Add(attribute); } root.Add(nl); } return root; } public static XElement GetNamespaceElement(int namespaceCount, int elementCount, int childElementCount) { XElement root = new XElement("root"); Random random = new Random(unchecked((int)DateTime.Now.Ticks)); Guid[] namespaces = new Guid[namespaceCount]; for (int n = 0; n < namespaceCount; n++) namespaces[n] = Guid.NewGuid(); for (int l = 0; l < elementCount; l++) { XElement nl = new XElement("{n" + namespaces[random.Next(namespaceCount)] + "}p" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); root.Add(nl); for (int e = 0; e < childElementCount; e++) { XElement child = new XElement("{n" + namespaces[random.Next(namespaceCount)] + "}c" + Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); nl.Add(child); } } return root; } public static void RootElement(ref XDocument xDoc, ref XDocument xmlDoc) { xDoc = XDocument.Parse("<root/>"); xmlDoc = XDocument.Parse(xDoc.ToString(SaveOptions.DisableFormatting)); } public static void TextNodes(ref XDocument xDoc, ref XDocument xmlDoc) { xDoc = XDocument.Parse("<root>some text</root>"); xmlDoc = XDocument.Parse(xDoc.ToString(SaveOptions.DisableFormatting)); } public static void Contacts(ref XDocument xDoc, ref XDocument xmlDoc) { xDoc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XProcessingInstruction("AppName", "Processing Instruction Data"), new XComment("Personal Contacts"), new XElement("contacts", new XAttribute("category", "friends"), new XAttribute("gender", "male"), new XElement("contact", new XAttribute("netWorth", "100"), new XElement("name", "John Hopkins"), new XElement("phone", new XAttribute("type", "home"), "214-459-8907"), new XElement("phone", new XAttribute("type", "work"), "817-283-9670")), new XElement("contact", new XAttribute("netWorth", "10"), new XElement("name", "Patrick Hines"), new XElement("phone", new XAttribute("type", "home"), "206-555-0144"), new XElement("phone", new XAttribute("type", "work"), "425-555-0145")))); xmlDoc = XDocument.Parse(xDoc.ToString(SaveOptions.DisableFormatting)); } public static void Teams(ref XDocument xDoc, ref XDocument xmlDoc) { XNamespace sp = "http://www.sportsleagues.com/"; XNamespace nba = "http://www.nba.com/"; xDoc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XProcessingInstruction("AppName", "Processing Instruction Data"), new XComment("Sport Leaques"), new XElement(sp + "SportLeagues", new XAttribute(XNamespace.Xmlns + "sp", sp), new XElement("League", new XAttribute("type", "Basketball"), new XAttribute("name", "National Basketball Association"), new XAttribute("id", "NBA"), new XAttribute(XNamespace.Xmlns + "nba", nba), new XElement("commissioner", "David Stern"), new XElement(nba + "Conference", new XAttribute(nba + "name", "Eastern"), new XElement(nba + "Division", new XAttribute(nba + "name", "Central") ), new XElement(nba + "Division", new XAttribute(nba + "name", "SouthEast") ), new XElement(nba + "Division", new XAttribute(nba + "name", "Atlantic"), new XElement(nba + "Teams", new XElement(nba + "Team", new XAttribute(nba + "name", "New Jersy Nets"), new XElement(nba + "Players", new XElement(nba + "Player", new XComment(" The best player on the team "), "\n" + " Or Is he the best player on the team?\n" + " ", new XElement(nba + "Name", "Richard Jefferson"), "<>,;:.@#$%^&*()?/`~+-", new XProcessingInstruction("Player", "processing instruction") ), new XElement(nba + "Player") ) ), new XElement(nba + "Team") ) ) ), new XElement(nba + "Conference", new XAttribute(nba + "name", "Western"), new XElement(nba + "Division", new XAttribute("name", "NorthWest") ), new XElement(nba + "Division", new XAttribute(nba + "name", "SouthWest") ), new XElement(nba + "Division", new XAttribute(nba + "name", "Pacific") ) ) ), new XElement("League", new XAttribute("type", "Football"), new XAttribute("name", "National Football League"), new XAttribute("id", "NFL"), new XAttribute(XNamespace.Xmlns + "nfl", "http://www.nfl.com"), new XElement("commissioner", "Paul Taglibu"), new XElement("Conference", new XAttribute("name", "NFC"), new XElement("Division", new XAttribute("name", "East"), new XElement("Teams", new XElement("Team", new XAttribute("name", "Dallas Cowboys"), new XComment(" The best team in the division "), "\n" + " Or Is it the best team in the division?\n" + " ", new XElement("Coach", "Bill Parcells"), "<>,;:.@#$%^&*()?/`~+-", new XProcessingInstruction("Cowboys", "processing instruction"), new XElement("Players") ), new XElement("Team", new XAttribute("name", "New Your Giants"), new XComment(" The second best team in the division "), "\n" + " Or Is it the second best team in the division?\n" + " ", new XElement("Coach", "Tom Coughlin"), "<>,;:.@#$%^&*()?/`~+-", new XProcessingInstruction("Giants", "processing instruction"), new XElement("Players") ), new XElement("Team"), new XElement("Team") ) ), new XElement("Division", new XAttribute("name", "West"), new XElement("Teams", new XElement("Team", new XAttribute("name", "Seattle Seahawks"), new XComment(" The best team in the division "), "\n" + " Or Is it the best team in the division?\n" + " ", new XElement("Coach", "Mike Holmgren"), "This should be a text node", new XProcessingInstruction("Seakhwaks", "processing instruction"), new XElement("Players") ), new XElement("Team", new XAttribute("name", "Arizona Cardinals"), new XComment(" The second best team in the division "), "\n" + " Or Is it the second best team in the division?\n" + " ", new XElement("Coach", "Dennis Green"), "<>,;:.@#$%^&*()?/`~+-", new XProcessingInstruction("Cardinals", "processing instruction"), new XElement("Players") ), new XElement("Team"), new XElement("Team") ) ), new XElement("Division", new XAttribute("name", "North"), new XElement("Teams") ), new XElement("Division", new XAttribute("name", "South"), new XElement("Teams") ) ), new XElement("Conference", new XAttribute("name", "AFC"), new XElement("Division", new XAttribute("name", "East"), new XElement("Teams") ), new XElement("Division", new XAttribute("name", "West"), new XElement("Teams") ), new XElement("Division", new XAttribute("name", "North"), new XElement("Teams") ), new XElement("Division", new XAttribute("name", "South"), new XElement("Teams") ) ) ), new XElement("League", new XAttribute("type", "Baseball"), new XAttribute("name", "Major League Baseball"), new XAttribute("id", "MLB"), new XAttribute(XNamespace.Xmlns + "mlb", "http://www.mlb.com") ), new XElement("League", new XAttribute("type", "Hockey"), new XAttribute("name", "National Hockey League"), new XAttribute("id", "NHL"), new XAttribute(XNamespace.Xmlns + "nhl", "http://www.nhl.com") ) ) ); xmlDoc = XDocument.Parse(xDoc.ToString(SaveOptions.DisableFormatting)); } public static void Hamlet(ref XDocument xDoc, ref XDocument xmlDoc) { xDoc = new XDocument( new XElement("PLAY", new XElement("TITLE", "The Tragedy of Hamlet, Prince of Denmark"), new XElement("fm", new XElement("p", "Text placed in the public domain by Moby Lexical Tools, 1992."), new XElement("p", "SGML markup by Jon Bosak, 1992-1994."), new XElement("p", "XML version by Jon Bosak, 1996-1997."), new XElement("p", "This work may be freely copied and distributed worldwide.") ), new XElement("PERSONAE", new XElement("TITLE", "Dramatis Personae"), new XElement("PERSONA", "CLAUDIUS, king of Denmark. "), new XElement("PERSONA", "HAMLET, son to the late, and nephew to the present king."), new XElement("PERSONA", "POLONIUS, lord chamberlain. "), new XElement("PERSONA", "HORATIO, friend to Hamlet."), new XElement("PERSONA", "LAERTES, son to Polonius."), new XElement("PERSONA", "LUCIANUS, nephew to the king."), new XElement("PGROUP", new XElement("PERSONA", "VOLTIMAND"), new XElement("PERSONA", "CORNELIUS"), new XElement("PERSONA", "ROSENCRANTZ"), new XElement("PERSONA", "GUILDENSTERN"), new XElement("PERSONA", "OSRIC"), new XElement("GRPDESCR", "courtiers.") ), new XElement("PERSONA", "A Gentleman"), new XElement("PERSONA", "A Priest. "), new XElement("PGROUP", new XElement("PERSONA", "MARCELLUS"), new XElement("PERSONA", "BERNARDO"), new XElement("GRPDESCR", "officers.") ), new XElement("PERSONA", "FRANCISCO, a soldier."), new XElement("PERSONA", "REYNALDO, servant to Polonius."), new XElement("PERSONA", "Players."), new XElement("PERSONA", "Two Clowns, grave-diggers."), new XElement("PERSONA", "FORTINBRAS, prince of Norway. "), new XElement("PERSONA", "A Captain."), new XElement("PERSONA", "English Ambassadors. "), new XElement("PERSONA", "GERTRUDE, queen of Denmark, and mother to Hamlet. "), new XElement("PERSONA", "OPHELIA, daughter to Polonius."), new XElement("PERSONA", "Lords, Ladies, Officers, Soldiers, Sailors, Messengers, and other Attendants."), new XElement("PERSONA", "Ghost of Hamlet's Father. ") ), new XElement("SCNDESCR", "SCENE Denmark."), new XElement("PLAYSUBT", "HAMLET"), new XElement("ACT", new XElement("TITLE", "ACT I"), new XElement("SCENE", new XElement("TITLE", "SCENE I. Elsinore. A platform before the castle."), new XElement("STAGEDIR", "FRANCISCO at his post. Enter to him BERNARDO"), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Who's there?") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "Nay, answer me: stand, and unfold yourself.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Long live the king!") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "Bernardo?") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "He.") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "You come most carefully upon your hour.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "'Tis now struck twelve; get thee to bed, Francisco.") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "For this relief much thanks: 'tis bitter cold,"), new XElement("LINE", "And I am sick at heart.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Have you had quiet guard?") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "Not a mouse stirring.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Well, good night."), new XElement("LINE", "If you do meet Horatio and Marcellus,"), new XElement("LINE", "The rivals of my watch, bid them make haste.") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "I think I hear them. Stand, ho! Who's there?") ), new XElement("STAGEDIR", "Enter HORATIO and MARCELLUS"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Friends to this ground.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "And liegemen to the Dane.") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "Give you good night.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "O, farewell, honest soldier:"), new XElement("LINE", "Who hath relieved you?") ), new XElement("SPEECH", new XElement("SPEAKER", "FRANCISCO"), new XElement("LINE", "Bernardo has my place."), new XElement("LINE", "Give you good night.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Holla! Bernardo!") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Say,"), new XElement("LINE", "What, is Horatio there?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "A piece of him.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Welcome, Horatio: welcome, good Marcellus.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "What, has this thing appear'd again to-night?") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "I have seen nothing.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Horatio says 'tis but our fantasy,"), new XElement("LINE", "And will not let belief take hold of him"), new XElement("LINE", "Touching this dreaded sight, twice seen of us:"), new XElement("LINE", "Therefore I have entreated him along"), new XElement("LINE", "With us to watch the minutes of this night;"), new XElement("LINE", "That if again this apparition come,"), new XElement("LINE", "He may approve our eyes and speak to it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Tush, tush, 'twill not appear.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Sit down awhile;"), new XElement("LINE", "And let us once again assail your ears,"), new XElement("LINE", "That are so fortified against our story"), new XElement("LINE", "What we have two nights seen.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Well, sit we down,"), new XElement("LINE", "And let us hear Bernardo speak of this.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Last night of all,"), new XElement("LINE", "When yond same star that's westward from the pole"), new XElement("LINE", "Had made his course to illume that part of heaven"), new XElement("LINE", "Where now it burns, Marcellus and myself,"), new XElement("LINE", "The bell then beating one,--") ), new XElement("STAGEDIR", "Enter Ghost"), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Peace, break thee off; look, where it comes again!") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "In the same figure, like the king that's dead.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Thou art a scholar; speak to it, Horatio.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Looks it not like the king? mark it, Horatio.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Most like: it harrows me with fear and wonder.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "It would be spoke to.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Question it, Horatio.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What art thou that usurp'st this time of night,"), new XElement("LINE", "Together with that fair and warlike form"), new XElement("LINE", "In which the majesty of buried Denmark"), new XElement("LINE", "Did sometimes march? by heaven I charge thee, speak!") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "It is offended.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "See, it stalks away!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Stay! speak, speak! I charge thee, speak!") ), new XElement("STAGEDIR", "Exit Ghost"), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "'Tis gone, and will not answer.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "How now, Horatio! you tremble and look pale:"), new XElement("LINE", "Is not this something more than fantasy?"), new XElement("LINE", "What think you on't?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Before my God, I might not this believe"), new XElement("LINE", "Without the sensible and true avouch"), new XElement("LINE", "Of mine own eyes.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Is it not like the king?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "As thou art to thyself:"), new XElement("LINE", "Such was the very armour he had on"), new XElement("LINE", "When he the ambitious Norway combated;"), new XElement("LINE", "So frown'd he once, when, in an angry parle,"), new XElement("LINE", "He smote the sledded Polacks on the ice."), new XElement("LINE", "'Tis strange.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Thus twice before, and jump at this dead hour,"), new XElement("LINE", "With martial stalk hath he gone by our watch.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "In what particular thought to work I know not;"), new XElement("LINE", "But in the gross and scope of my opinion,"), new XElement("LINE", "This bodes some strange eruption to our state.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Good now, sit down, and tell me, he that knows,"), new XElement("LINE", "Why this same strict and most observant watch"), new XElement("LINE", "So nightly toils the subject of the land,"), new XElement("LINE", "And why such daily cast of brazen cannon,"), new XElement("LINE", "And foreign mart for implements of war;"), new XElement("LINE", "Why such impress of shipwrights, whose sore task"), new XElement("LINE", "Does not divide the Sunday from the week;"), new XElement("LINE", "What might be toward, that this sweaty haste"), new XElement("LINE", "Doth make the night joint-labourer with the day:"), new XElement("LINE", "Who is't that can inform me?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "That can I;"), new XElement("LINE", "At least, the whisper goes so. Our last king,"), new XElement("LINE", "Whose image even but now appear'd to us,"), new XElement("LINE", "Was, as you know, by Fortinbras of Norway,"), new XElement("LINE", "Thereto prick'd on by a most emulate pride,"), new XElement("LINE", "Dared to the combat; in which our valiant Hamlet--"), new XElement("LINE", "For so this side of our known world esteem'd him--"), new XElement("LINE", "Did slay this Fortinbras; who by a seal'd compact,"), new XElement("LINE", "Well ratified by law and heraldry,"), new XElement("LINE", "Did forfeit, with his life, all those his lands"), new XElement("LINE", "Which he stood seized of, to the conqueror:"), new XElement("LINE", "Against the which, a moiety competent"), new XElement("LINE", "Was gaged by our king; which had return'd"), new XElement("LINE", "To the inheritance of Fortinbras,"), new XElement("LINE", "Had he been vanquisher; as, by the same covenant,"), new XElement("LINE", "And carriage of the article design'd,"), new XElement("LINE", "His fell to Hamlet. Now, sir, young Fortinbras,"), new XElement("LINE", "Of unimproved mettle hot and full,"), new XElement("LINE", "Hath in the skirts of Norway here and there"), new XElement("LINE", "Shark'd up a list of lawless resolutes,"), new XElement("LINE", "For food and diet, to some enterprise"), new XElement("LINE", "That hath a stomach in't; which is no other--"), new XElement("LINE", "As it doth well appear unto our state--"), new XElement("LINE", "But to recover of us, by strong hand"), new XElement("LINE", "And terms compulsatory, those foresaid lands"), new XElement("LINE", "So by his father lost: and this, I take it,"), new XElement("LINE", "Is the main motive of our preparations,"), new XElement("LINE", "The source of this our watch and the chief head"), new XElement("LINE", "Of this post-haste and romage in the land.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "I think it be no other but e'en so:"), new XElement("LINE", "Well may it sort that this portentous figure"), new XElement("LINE", "Comes armed through our watch; so like the king"), new XElement("LINE", "That was and is the question of these wars.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "A mote it is to trouble the mind's eye."), new XElement("LINE", "In the most high and palmy state of Rome,"), new XElement("LINE", "A little ere the mightiest Julius fell,"), new XElement("LINE", "The graves stood tenantless and the sheeted dead"), new XElement("LINE", "Did squeak and gibber in the Roman streets:"), new XElement("LINE", "As stars with trains of fire and dews of blood,"), new XElement("LINE", "Disasters in the sun; and the moist star"), new XElement("LINE", "Upon whose influence Neptune's empire stands"), new XElement("LINE", "Was sick almost to doomsday with eclipse:"), new XElement("LINE", "And even the like precurse of fierce events,"), new XElement("LINE", "As harbingers preceding still the fates"), new XElement("LINE", "And prologue to the omen coming on,"), new XElement("LINE", "Have heaven and earth together demonstrated"), new XElement("LINE", "Unto our climatures and countrymen.--"), new XElement("LINE", "But soft, behold! lo, where it comes again!"), new XElement("STAGEDIR", "Re-enter Ghost"), new XElement("LINE", "I'll cross it, though it blast me. Stay, illusion!"), new XElement("LINE", "If thou hast any sound, or use of voice,"), new XElement("LINE", "Speak to me:"), new XElement("LINE", "If there be any good thing to be done,"), new XElement("LINE", "That may to thee do ease and grace to me,"), new XElement("LINE", "Speak to me:"), new XElement("STAGEDIR", "Cock crows"), new XElement("LINE", "If thou art privy to thy country's fate,"), new XElement("LINE", "Which, happily, foreknowing may avoid, O, speak!"), new XElement("LINE", "Or if thou hast uphoarded in thy life"), new XElement("LINE", "Extorted treasure in the womb of earth,"), new XElement("LINE", "For which, they say, you spirits oft walk in death,"), new XElement("LINE", "Speak of it: stay, and speak! Stop it, Marcellus.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Shall I strike at it with my partisan?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Do, if it will not stand.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "'Tis here!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "'Tis here!") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "'Tis gone!"), new XElement("STAGEDIR", "Exit Ghost"), new XElement("LINE", "We do it wrong, being so majestical,"), new XElement("LINE", "To offer it the show of violence;"), new XElement("LINE", "For it is, as the air, invulnerable,"), new XElement("LINE", "And our vain blows malicious mockery.") ), new XElement("SPEECH", new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "It was about to speak, when the cock crew.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "And then it started like a guilty thing"), new XElement("LINE", "Upon a fearful summons. I have heard,"), new XElement("LINE", "The cock, that is the trumpet to the morn,"), new XElement("LINE", "Doth with his lofty and shrill-sounding throat"), new XElement("LINE", "Awake the god of day; and, at his warning,"), new XElement("LINE", "Whether in sea or fire, in earth or air,"), new XElement("LINE", "The extravagant and erring spirit hies"), new XElement("LINE", "To his confine: and of the truth herein"), new XElement("LINE", "This present object made probation.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "It faded on the crowing of the cock."), new XElement("LINE", "Some say that ever 'gainst that season comes"), new XElement("LINE", "Wherein our Saviour's birth is celebrated,"), new XElement("LINE", "The bird of dawning singeth all night long:"), new XElement("LINE", "And then, they say, no spirit dares stir abroad;"), new XElement("LINE", "The nights are wholesome; then no planets strike,"), new XElement("LINE", "No fairy takes, nor witch hath power to charm,"), new XElement("LINE", "So hallow'd and so gracious is the time.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "So have I heard and do in part believe it."), new XElement("LINE", "But, look, the morn, in russet mantle clad,"), new XElement("LINE", "Walks o'er the dew of yon high eastward hill:"), new XElement("LINE", "Break we our watch up; and by my advice,"), new XElement("LINE", "Let us impart what we have seen to-night"), new XElement("LINE", "Unto young Hamlet; for, upon my life,"), new XElement("LINE", "This spirit, dumb to us, will speak to him."), new XElement("LINE", "Do you consent we shall acquaint him with it,"), new XElement("LINE", "As needful in our loves, fitting our duty?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Let's do't, I pray; and I this morning know"), new XElement("LINE", "Where we shall find him most conveniently.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE II. A room of state in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, QUEEN GERTRUDE, HAMLET,\n" + "POLONIUS, LAERTES, VOLTIMAND, CORNELIUS, Lords,\n" + "and Attendants" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Though yet of Hamlet our dear brother's death"), new XElement("LINE", "The memory be green, and that it us befitted"), new XElement("LINE", "To bear our hearts in grief and our whole kingdom"), new XElement("LINE", "To be contracted in one brow of woe,"), new XElement("LINE", "Yet so far hath discretion fought with nature"), new XElement("LINE", "That we with wisest sorrow think on him,"), new XElement("LINE", "Together with remembrance of ourselves."), new XElement("LINE", "Therefore our sometime sister, now our queen,"), new XElement("LINE", "The imperial jointress to this warlike state,"), new XElement("LINE", "Have we, as 'twere with a defeated joy,--"), new XElement("LINE", "With an auspicious and a dropping eye,"), new XElement("LINE", "With mirth in funeral and with dirge in marriage,"), new XElement("LINE", "In equal scale weighing delight and dole,--"), new XElement("LINE", "Taken to wife: nor have we herein barr'd"), new XElement("LINE", "Your better wisdoms, which have freely gone"), new XElement("LINE", "With this affair along. For all, our thanks."), new XElement("LINE", "Now follows, that you know, young Fortinbras,"), new XElement("LINE", "Holding a weak supposal of our worth,"), new XElement("LINE", "Or thinking by our late dear brother's death"), new XElement("LINE", "Our state to be disjoint and out of frame,"), new XElement("LINE", "Colleagued with the dream of his advantage,"), new XElement("LINE", "He hath not fail'd to pester us with message,"), new XElement("LINE", "Importing the surrender of those lands"), new XElement("LINE", "Lost by his father, with all bonds of law,"), new XElement("LINE", "To our most valiant brother. So much for him."), new XElement("LINE", "Now for ourself and for this time of meeting:"), new XElement("LINE", "Thus much the business is: we have here writ"), new XElement("LINE", "To Norway, uncle of young Fortinbras,--"), new XElement("LINE", "Who, impotent and bed-rid, scarcely hears"), new XElement("LINE", "Of this his nephew's purpose,--to suppress"), new XElement("LINE", "His further gait herein; in that the levies,"), new XElement("LINE", "The lists and full proportions, are all made"), new XElement("LINE", "Out of his subject: and we here dispatch"), new XElement("LINE", "You, good Cornelius, and you, Voltimand,"), new XElement("LINE", "For bearers of this greeting to old Norway;"), new XElement("LINE", "Giving to you no further personal power"), new XElement("LINE", "To business with the king, more than the scope"), new XElement("LINE", "Of these delated articles allow."), new XElement("LINE", "Farewell, and let your haste commend your duty.") ), new XElement("SPEECH", new XElement("SPEAKER", "CORNELIUS"), new XElement("SPEAKER", "VOLTIMAND"), new XElement("LINE", "In that and all things will we show our duty.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "We doubt it nothing: heartily farewell."), new XElement("STAGEDIR", "Exeunt VOLTIMAND and CORNELIUS"), new XElement("LINE", "And now, Laertes, what's the news with you?"), new XElement("LINE", "You told us of some suit; what is't, Laertes?"), new XElement("LINE", "You cannot speak of reason to the Dane,"), new XElement("LINE", "And loose your voice: what wouldst thou beg, Laertes,"), new XElement("LINE", "That shall not be my offer, not thy asking?"), new XElement("LINE", "The head is not more native to the heart,"), new XElement("LINE", "The hand more instrumental to the mouth,"), new XElement("LINE", "Than is the throne of Denmark to thy father."), new XElement("LINE", "What wouldst thou have, Laertes?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "My dread lord,"), new XElement("LINE", "Your leave and favour to return to France;"), new XElement("LINE", "From whence though willingly I came to Denmark,"), new XElement("LINE", "To show my duty in your coronation,"), new XElement("LINE", "Yet now, I must confess, that duty done,"), new XElement("LINE", "My thoughts and wishes bend again toward France"), new XElement("LINE", "And bow them to your gracious leave and pardon.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Have you your father's leave? What says Polonius?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "He hath, my lord, wrung from me my slow leave"), new XElement("LINE", "By laboursome petition, and at last"), new XElement("LINE", "Upon his will I seal'd my hard consent:"), new XElement("LINE", "I do beseech you, give him leave to go.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Take thy fair hour, Laertes; time be thine,"), new XElement("LINE", "And thy best graces spend it at thy will!"), new XElement("LINE", "But now, my cousin Hamlet, and my son,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " A little more than kin, and less than kind." ) ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "How is it that the clouds still hang on you?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Not so, my lord; I am too much i' the sun.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Good Hamlet, cast thy nighted colour off,"), new XElement("LINE", "And let thine eye look like a friend on Denmark."), new XElement("LINE", "Do not for ever with thy vailed lids"), new XElement("LINE", "Seek for thy noble father in the dust:"), new XElement("LINE", "Thou know'st 'tis common; all that lives must die,"), new XElement("LINE", "Passing through nature to eternity.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, madam, it is common.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "If it be,"), new XElement("LINE", "Why seems it so particular with thee?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Seems, madam! nay it is; I know not 'seems.'"), new XElement("LINE", "'Tis not alone my inky cloak, good mother,"), new XElement("LINE", "Nor customary suits of solemn black,"), new XElement("LINE", "Nor windy suspiration of forced breath,"), new XElement("LINE", "No, nor the fruitful river in the eye,"), new XElement("LINE", "Nor the dejected 'havior of the visage,"), new XElement("LINE", "Together with all forms, moods, shapes of grief,"), new XElement("LINE", "That can denote me truly: these indeed seem,"), new XElement("LINE", "For they are actions that a man might play:"), new XElement("LINE", "But I have that within which passeth show;"), new XElement("LINE", "These but the trappings and the suits of woe.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "'Tis sweet and commendable in your nature, Hamlet,"), new XElement("LINE", "To give these mourning duties to your father:"), new XElement("LINE", "But, you must know, your father lost a father;"), new XElement("LINE", "That father lost, lost his, and the survivor bound"), new XElement("LINE", "In filial obligation for some term"), new XElement("LINE", "To do obsequious sorrow: but to persever"), new XElement("LINE", "In obstinate condolement is a course"), new XElement("LINE", "Of impious stubbornness; 'tis unmanly grief;"), new XElement("LINE", "It shows a will most incorrect to heaven,"), new XElement("LINE", "A heart unfortified, a mind impatient,"), new XElement("LINE", "An understanding simple and unschool'd:"), new XElement("LINE", "For what we know must be and is as common"), new XElement("LINE", "As any the most vulgar thing to sense,"), new XElement("LINE", "Why should we in our peevish opposition"), new XElement("LINE", "Take it to heart? Fie! 'tis a fault to heaven,"), new XElement("LINE", "A fault against the dead, a fault to nature,"), new XElement("LINE", "To reason most absurd: whose common theme"), new XElement("LINE", "Is death of fathers, and who still hath cried,"), new XElement("LINE", "From the first corse till he that died to-day,"), new XElement("LINE", "'This must be so.' We pray you, throw to earth"), new XElement("LINE", "This unprevailing woe, and think of us"), new XElement("LINE", "As of a father: for let the world take note,"), new XElement("LINE", "You are the most immediate to our throne;"), new XElement("LINE", "And with no less nobility of love"), new XElement("LINE", "Than that which dearest father bears his son,"), new XElement("LINE", "Do I impart toward you. For your intent"), new XElement("LINE", "In going back to school in Wittenberg,"), new XElement("LINE", "It is most retrograde to our desire:"), new XElement("LINE", "And we beseech you, bend you to remain"), new XElement("LINE", "Here, in the cheer and comfort of our eye,"), new XElement("LINE", "Our chiefest courtier, cousin, and our son.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Let not thy mother lose her prayers, Hamlet:"), new XElement("LINE", "I pray thee, stay with us; go not to Wittenberg.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I shall in all my best obey you, madam.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Why, 'tis a loving and a fair reply:"), new XElement("LINE", "Be as ourself in Denmark. Madam, come;"), new XElement("LINE", "This gentle and unforced accord of Hamlet"), new XElement("LINE", "Sits smiling to my heart: in grace whereof,"), new XElement("LINE", "No jocund health that Denmark drinks to-day,"), new XElement("LINE", "But the great cannon to the clouds shall tell,"), new XElement("LINE", "And the king's rouse the heavens all bruit again,"), new XElement("LINE", "Re-speaking earthly thunder. Come away.") ), new XElement("STAGEDIR", "Exeunt all but HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, that this too too solid flesh would melt"), new XElement("LINE", "Thaw and resolve itself into a dew!"), new XElement("LINE", "Or that the Everlasting had not fix'd"), new XElement("LINE", "His canon 'gainst self-slaughter! O God! God!"), new XElement("LINE", "How weary, stale, flat and unprofitable,"), new XElement("LINE", "Seem to me all the uses of this world!"), new XElement("LINE", "Fie on't! ah fie! 'tis an unweeded garden,"), new XElement("LINE", "That grows to seed; things rank and gross in nature"), new XElement("LINE", "Possess it merely. That it should come to this!"), new XElement("LINE", "But two months dead: nay, not so much, not two:"), new XElement("LINE", "So excellent a king; that was, to this,"), new XElement("LINE", "Hyperion to a satyr; so loving to my mother"), new XElement("LINE", "That he might not beteem the winds of heaven"), new XElement("LINE", "Visit her face too roughly. Heaven and earth!"), new XElement("LINE", "Must I remember? why, she would hang on him,"), new XElement("LINE", "As if increase of appetite had grown"), new XElement("LINE", "By what it fed on: and yet, within a month--"), new XElement("LINE", "Let me not think on't--Frailty, thy name is woman!--"), new XElement("LINE", "A little month, or ere those shoes were old"), new XElement("LINE", "With which she follow'd my poor father's body,"), new XElement("LINE", "Like Niobe, all tears:--why she, even she--"), new XElement("LINE", "O, God! a beast, that wants discourse of reason,"), new XElement("LINE", "Would have mourn'd longer--married with my uncle,"), new XElement("LINE", "My father's brother, but no more like my father"), new XElement("LINE", "Than I to Hercules: within a month:"), new XElement("LINE", "Ere yet the salt of most unrighteous tears"), new XElement("LINE", "Had left the flushing in her galled eyes,"), new XElement("LINE", "She married. O, most wicked speed, to post"), new XElement("LINE", "With such dexterity to incestuous sheets!"), new XElement("LINE", "It is not nor it cannot come to good:"), new XElement("LINE", "But break, my heart; for I must hold my tongue.") ), new XElement("STAGEDIR", "Enter HORATIO, MARCELLUS, and BERNARDO"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Hail to your lordship!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am glad to see you well:"), new XElement("LINE", "Horatio,--or I do forget myself.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "The same, my lord, and your poor servant ever.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, my good friend; I'll change that name with you:"), new XElement("LINE", "And what make you from Wittenberg, Horatio? Marcellus?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "My good lord--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am very glad to see you. Good even, sir."), new XElement("LINE", "But what, in faith, make you from Wittenberg?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "A truant disposition, good my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I would not hear your enemy say so,"), new XElement("LINE", "Nor shall you do mine ear that violence,"), new XElement("LINE", "To make it truster of your own report"), new XElement("LINE", "Against yourself: I know you are no truant."), new XElement("LINE", "But what is your affair in Elsinore?"), new XElement("LINE", "We'll teach you to drink deep ere you depart.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "My lord, I came to see your father's funeral.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I pray thee, do not mock me, fellow-student;"), new XElement("LINE", "I think it was to see my mother's wedding.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Indeed, my lord, it follow'd hard upon.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Thrift, thrift, Horatio! the funeral baked meats"), new XElement("LINE", "Did coldly furnish forth the marriage tables."), new XElement("LINE", "Would I had met my dearest foe in heaven"), new XElement("LINE", "Or ever I had seen that day, Horatio!"), new XElement("LINE", "My father!--methinks I see my father.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Where, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "In my mind's eye, Horatio.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I saw him once; he was a goodly king.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "He was a man, take him for all in all,"), new XElement("LINE", "I shall not look upon his like again.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "My lord, I think I saw him yesternight.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Saw? who?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "My lord, the king your father.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The king my father!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Season your admiration for awhile"), new XElement("LINE", "With an attent ear, till I may deliver,"), new XElement("LINE", "Upon the witness of these gentlemen,"), new XElement("LINE", "This marvel to you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "For God's love, let me hear.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Two nights together had these gentlemen,"), new XElement("LINE", "Marcellus and Bernardo, on their watch,"), new XElement("LINE", "In the dead vast and middle of the night,"), new XElement("LINE", "Been thus encounter'd. A figure like your father,"), new XElement("LINE", "Armed at point exactly, cap-a-pe,"), new XElement("LINE", "Appears before them, and with solemn march"), new XElement("LINE", "Goes slow and stately by them: thrice he walk'd"), new XElement("LINE", "By their oppress'd and fear-surprised eyes,"), new XElement("LINE", "Within his truncheon's length; whilst they, distilled"), new XElement("LINE", "Almost to jelly with the act of fear,"), new XElement("LINE", "Stand dumb and speak not to him. This to me"), new XElement("LINE", "In dreadful secrecy impart they did;"), new XElement("LINE", "And I with them the third night kept the watch;"), new XElement("LINE", "Where, as they had deliver'd, both in time,"), new XElement("LINE", "Form of the thing, each word made true and good,"), new XElement("LINE", "The apparition comes: I knew your father;"), new XElement("LINE", "These hands are not more like.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "But where was this?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "My lord, upon the platform where we watch'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Did you not speak to it?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "My lord, I did;"), new XElement("LINE", "But answer made it none: yet once methought"), new XElement("LINE", "It lifted up its head and did address"), new XElement("LINE", "Itself to motion, like as it would speak;"), new XElement("LINE", "But even then the morning cock crew loud,"), new XElement("LINE", "And at the sound it shrunk in haste away,"), new XElement("LINE", "And vanish'd from our sight.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Tis very strange.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "As I do live, my honour'd lord, 'tis true;"), new XElement("LINE", "And we did think it writ down in our duty"), new XElement("LINE", "To let you know of it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Indeed, indeed, sirs, but this troubles me."), new XElement("LINE", "Hold you the watch to-night?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "We do, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Arm'd, say you?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Arm'd, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "From top to toe?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "My lord, from head to foot.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then saw you not his face?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "O, yes, my lord; he wore his beaver up.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What, look'd he frowningly?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "A countenance more in sorrow than in anger.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Pale or red?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Nay, very pale.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "And fix'd his eyes upon you?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Most constantly.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I would I had been there.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It would have much amazed you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Very like, very like. Stay'd it long?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "While one with moderate haste might tell a hundred.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("SPEAKER", "BERNARDO"), new XElement("LINE", "Longer, longer.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Not when I saw't.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "His beard was grizzled--no?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It was, as I have seen it in his life,"), new XElement("LINE", "A sable silver'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I will watch to-night;"), new XElement("LINE", "Perchance 'twill walk again.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I warrant it will.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "If it assume my noble father's person,"), new XElement("LINE", "I'll speak to it, though hell itself should gape"), new XElement("LINE", "And bid me hold my peace. I pray you all,"), new XElement("LINE", "If you have hitherto conceal'd this sight,"), new XElement("LINE", "Let it be tenable in your silence still;"), new XElement("LINE", "And whatsoever else shall hap to-night,"), new XElement("LINE", "Give it an understanding, but no tongue:"), new XElement("LINE", "I will requite your loves. So, fare you well:"), new XElement("LINE", "Upon the platform, 'twixt eleven and twelve,"), new XElement("LINE", "I'll visit you.") ), new XElement("SPEECH", new XElement("SPEAKER", "All"), new XElement("LINE", "Our duty to your honour.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Your loves, as mine to you: farewell."), new XElement("STAGEDIR", "Exeunt all but HAMLET"), new XElement("LINE", "My father's spirit in arms! all is not well;"), new XElement("LINE", "I doubt some foul play: would the night were come!"), new XElement("LINE", "Till then sit still, my soul: foul deeds will rise,"), new XElement("LINE", "Though all the earth o'erwhelm them, to men's eyes.") ), new XElement("STAGEDIR", "Exit") ), new XElement("SCENE", new XElement("TITLE", "SCENE III. A room in Polonius' house."), new XElement("STAGEDIR", "Enter LAERTES and OPHELIA"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "My necessaries are embark'd: farewell:"), new XElement("LINE", "And, sister, as the winds give benefit"), new XElement("LINE", "And convoy is assistant, do not sleep,"), new XElement("LINE", "But let me hear from you.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Do you doubt that?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "For Hamlet and the trifling of his favour,"), new XElement("LINE", "Hold it a fashion and a toy in blood,"), new XElement("LINE", "A violet in the youth of primy nature,"), new XElement("LINE", "Forward, not permanent, sweet, not lasting,"), new XElement("LINE", "The perfume and suppliance of a minute; No more.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "No more but so?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Think it no more;"), new XElement("LINE", "For nature, crescent, does not grow alone"), new XElement("LINE", "In thews and bulk, but, as this temple waxes,"), new XElement("LINE", "The inward service of the mind and soul"), new XElement("LINE", "Grows wide withal. Perhaps he loves you now,"), new XElement("LINE", "And now no soil nor cautel doth besmirch"), new XElement("LINE", "The virtue of his will: but you must fear,"), new XElement("LINE", "His greatness weigh'd, his will is not his own;"), new XElement("LINE", "For he himself is subject to his birth:"), new XElement("LINE", "He may not, as unvalued persons do,"), new XElement("LINE", "Carve for himself; for on his choice depends"), new XElement("LINE", "The safety and health of this whole state;"), new XElement("LINE", "And therefore must his choice be circumscribed"), new XElement("LINE", "Unto the voice and yielding of that body"), new XElement("LINE", "Whereof he is the head. Then if he says he loves you,"), new XElement("LINE", "It fits your wisdom so far to believe it"), new XElement("LINE", "As he in his particular act and place"), new XElement("LINE", "May give his saying deed; which is no further"), new XElement("LINE", "Than the main voice of Denmark goes withal."), new XElement("LINE", "Then weigh what loss your honour may sustain,"), new XElement("LINE", "If with too credent ear you list his songs,"), new XElement("LINE", "Or lose your heart, or your chaste treasure open"), new XElement("LINE", "To his unmaster'd importunity."), new XElement("LINE", "Fear it, Ophelia, fear it, my dear sister,"), new XElement("LINE", "And keep you in the rear of your affection,"), new XElement("LINE", "Out of the shot and danger of desire."), new XElement("LINE", "The chariest maid is prodigal enough,"), new XElement("LINE", "If she unmask her beauty to the moon:"), new XElement("LINE", "Virtue itself 'scapes not calumnious strokes:"), new XElement("LINE", "The canker galls the infants of the spring,"), new XElement("LINE", "Too oft before their buttons be disclosed,"), new XElement("LINE", "And in the morn and liquid dew of youth"), new XElement("LINE", "Contagious blastments are most imminent."), new XElement("LINE", "Be wary then; best safety lies in fear:"), new XElement("LINE", "Youth to itself rebels, though none else near.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I shall the effect of this good lesson keep,"), new XElement("LINE", "As watchman to my heart. But, good my brother,"), new XElement("LINE", "Do not, as some ungracious pastors do,"), new XElement("LINE", "Show me the steep and thorny way to heaven;"), new XElement("LINE", "Whiles, like a puff'd and reckless libertine,"), new XElement("LINE", "Himself the primrose path of dalliance treads,"), new XElement("LINE", "And recks not his own rede.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "O, fear me not."), new XElement("LINE", "I stay too long: but here my father comes."), new XElement("STAGEDIR", "Enter POLONIUS"), new XElement("LINE", "A double blessing is a double grace,"), new XElement("LINE", "Occasion smiles upon a second leave.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Yet here, Laertes! aboard, aboard, for shame!"), new XElement("LINE", "The wind sits in the shoulder of your sail,"), new XElement("LINE", "And you are stay'd for. There; my blessing with thee!"), new XElement("LINE", "And these few precepts in thy memory"), new XElement("LINE", "See thou character. Give thy thoughts no tongue,"), new XElement("LINE", "Nor any unproportioned thought his act."), new XElement("LINE", "Be thou familiar, but by no means vulgar."), new XElement("LINE", "Those friends thou hast, and their adoption tried,"), new XElement("LINE", "Grapple them to thy soul with hoops of steel;"), new XElement("LINE", "But do not dull thy palm with entertainment"), new XElement("LINE", "Of each new-hatch'd, unfledged comrade. Beware"), new XElement("LINE", "Of entrance to a quarrel, but being in,"), new XElement("LINE", "Bear't that the opposed may beware of thee."), new XElement("LINE", "Give every man thy ear, but few thy voice;"), new XElement("LINE", "Take each man's censure, but reserve thy judgment."), new XElement("LINE", "Costly thy habit as thy purse can buy,"), new XElement("LINE", "But not express'd in fancy; rich, not gaudy;"), new XElement("LINE", "For the apparel oft proclaims the man,"), new XElement("LINE", "And they in France of the best rank and station"), new XElement("LINE", "Are of a most select and generous chief in that."), new XElement("LINE", "Neither a borrower nor a lender be;"), new XElement("LINE", "For loan oft loses both itself and friend,"), new XElement("LINE", "And borrowing dulls the edge of husbandry."), new XElement("LINE", "This above all: to thine ownself be true,"), new XElement("LINE", "And it must follow, as the night the day,"), new XElement("LINE", "Thou canst not then be false to any man."), new XElement("LINE", "Farewell: my blessing season this in thee!") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Most humbly do I take my leave, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "The time invites you; go; your servants tend.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Farewell, Ophelia; and remember well"), new XElement("LINE", "What I have said to you.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "'Tis in my memory lock'd,"), new XElement("LINE", "And you yourself shall keep the key of it.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Farewell.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What is't, Ophelia, be hath said to you?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "So please you, something touching the Lord Hamlet.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Marry, well bethought:"), new XElement("LINE", "'Tis told me, he hath very oft of late"), new XElement("LINE", "Given private time to you; and you yourself"), new XElement("LINE", "Have of your audience been most free and bounteous:"), new XElement("LINE", "If it be so, as so 'tis put on me,"), new XElement("LINE", "And that in way of caution, I must tell you,"), new XElement("LINE", "You do not understand yourself so clearly"), new XElement("LINE", "As it behoves my daughter and your honour."), new XElement("LINE", "What is between you? give me up the truth.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "He hath, my lord, of late made many tenders"), new XElement("LINE", "Of his affection to me.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Affection! pooh! you speak like a green girl,"), new XElement("LINE", "Unsifted in such perilous circumstance."), new XElement("LINE", "Do you believe his tenders, as you call them?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I do not know, my lord, what I should think.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Marry, I'll teach you: think yourself a baby;"), new XElement("LINE", "That you have ta'en these tenders for true pay,"), new XElement("LINE", "Which are not sterling. Tender yourself more dearly;"), new XElement("LINE", "Or--not to crack the wind of the poor phrase,"), new XElement("LINE", "Running it thus--you'll tender me a fool.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My lord, he hath importuned me with love"), new XElement("LINE", "In honourable fashion.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Ay, fashion you may call it; go to, go to.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "And hath given countenance to his speech, my lord,"), new XElement("LINE", "With almost all the holy vows of heaven.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Ay, springes to catch woodcocks. I do know,"), new XElement("LINE", "When the blood burns, how prodigal the soul"), new XElement("LINE", "Lends the tongue vows: these blazes, daughter,"), new XElement("LINE", "Giving more light than heat, extinct in both,"), new XElement("LINE", "Even in their promise, as it is a-making,"), new XElement("LINE", "You must not take for fire. From this time"), new XElement("LINE", "Be somewhat scanter of your maiden presence;"), new XElement("LINE", "Set your entreatments at a higher rate"), new XElement("LINE", "Than a command to parley. For Lord Hamlet,"), new XElement("LINE", "Believe so much in him, that he is young"), new XElement("LINE", "And with a larger tether may he walk"), new XElement("LINE", "Than may be given you: in few, Ophelia,"), new XElement("LINE", "Do not believe his vows; for they are brokers,"), new XElement("LINE", "Not of that dye which their investments show,"), new XElement("LINE", "But mere implorators of unholy suits,"), new XElement("LINE", "Breathing like sanctified and pious bawds,"), new XElement("LINE", "The better to beguile. This is for all:"), new XElement("LINE", "I would not, in plain terms, from this time forth,"), new XElement("LINE", "Have you so slander any moment leisure,"), new XElement("LINE", "As to give words or talk with the Lord Hamlet."), new XElement("LINE", "Look to't, I charge you: come your ways.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I shall obey, my lord.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE IV. The platform."), new XElement("STAGEDIR", "Enter HAMLET, HORATIO, and MARCELLUS"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The air bites shrewdly; it is very cold.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It is a nipping and an eager air.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What hour now?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I think it lacks of twelve.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, it is struck.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Indeed? I heard it not: then it draws near the season"), new XElement("LINE", "Wherein the spirit held his wont to walk."), new XElement("STAGEDIR", "A flourish of trumpets, and ordnance shot off, within"), new XElement("LINE", "What does this mean, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The king doth wake to-night and takes his rouse,"), new XElement("LINE", "Keeps wassail, and the swaggering up-spring reels;"), new XElement("LINE", "And, as he drains his draughts of Rhenish down,"), new XElement("LINE", "The kettle-drum and trumpet thus bray out"), new XElement("LINE", "The triumph of his pledge.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Is it a custom?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, marry, is't:"), new XElement("LINE", "But to my mind, though I am native here"), new XElement("LINE", "And to the manner born, it is a custom"), new XElement("LINE", "More honour'd in the breach than the observance."), new XElement("LINE", "This heavy-headed revel east and west"), new XElement("LINE", "Makes us traduced and tax'd of other nations:"), new XElement("LINE", "They clepe us drunkards, and with swinish phrase"), new XElement("LINE", "Soil our addition; and indeed it takes"), new XElement("LINE", "From our achievements, though perform'd at height,"), new XElement("LINE", "The pith and marrow of our attribute."), new XElement("LINE", "So, oft it chances in particular men,"), new XElement("LINE", "That for some vicious mole of nature in them,"), new XElement("LINE", "As, in their birth--wherein they are not guilty,"), new XElement("LINE", "Since nature cannot choose his origin--"), new XElement("LINE", "By the o'ergrowth of some complexion,"), new XElement("LINE", "Oft breaking down the pales and forts of reason,"), new XElement("LINE", "Or by some habit that too much o'er-leavens"), new XElement("LINE", "The form of plausive manners, that these men,"), new XElement("LINE", "Carrying, I say, the stamp of one defect,"), new XElement("LINE", "Being nature's livery, or fortune's star,--"), new XElement("LINE", "Their virtues else--be they as pure as grace,"), new XElement("LINE", "As infinite as man may undergo--"), new XElement("LINE", "Shall in the general censure take corruption"), new XElement("LINE", "From that particular fault: the dram of eale"), new XElement("LINE", "Doth all the noble substance of a doubt"), new XElement("LINE", "To his own scandal.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Look, my lord, it comes!") ), new XElement("STAGEDIR", "Enter Ghost"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Angels and ministers of grace defend us!"), new XElement("LINE", "Be thou a spirit of health or goblin damn'd,"), new XElement("LINE", "Bring with thee airs from heaven or blasts from hell,"), new XElement("LINE", "Be thy intents wicked or charitable,"), new XElement("LINE", "Thou comest in such a questionable shape"), new XElement("LINE", "That I will speak to thee: I'll call thee Hamlet,"), new XElement("LINE", "King, father, royal Dane: O, answer me!"), new XElement("LINE", "Let me not burst in ignorance; but tell"), new XElement("LINE", "Why thy canonized bones, hearsed in death,"), new XElement("LINE", "Have burst their cerements; why the sepulchre,"), new XElement("LINE", "Wherein we saw thee quietly inurn'd,"), new XElement("LINE", "Hath oped his ponderous and marble jaws,"), new XElement("LINE", "To cast thee up again. What may this mean,"), new XElement("LINE", "That thou, dead corse, again in complete steel"), new XElement("LINE", "Revisit'st thus the glimpses of the moon,"), new XElement("LINE", "Making night hideous; and we fools of nature"), new XElement("LINE", "So horridly to shake our disposition"), new XElement("LINE", "With thoughts beyond the reaches of our souls?"), new XElement("LINE", "Say, why is this? wherefore? what should we do?") ), new XElement("STAGEDIR", "Ghost beckons HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It beckons you to go away with it,"), new XElement("LINE", "As if it some impartment did desire"), new XElement("LINE", "To you alone.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Look, with what courteous action"), new XElement("LINE", "It waves you to a more removed ground:"), new XElement("LINE", "But do not go with it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "No, by no means.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It will not speak; then I will follow it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Do not, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, what should be the fear?"), new XElement("LINE", "I do not set my life in a pin's fee;"), new XElement("LINE", "And for my soul, what can it do to that,"), new XElement("LINE", "Being a thing immortal as itself?"), new XElement("LINE", "It waves me forth again: I'll follow it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What if it tempt you toward the flood, my lord,"), new XElement("LINE", "Or to the dreadful summit of the cliff"), new XElement("LINE", "That beetles o'er his base into the sea,"), new XElement("LINE", "And there assume some other horrible form,"), new XElement("LINE", "Which might deprive your sovereignty of reason"), new XElement("LINE", "And draw you into madness? think of it:"), new XElement("LINE", "The very place puts toys of desperation,"), new XElement("LINE", "Without more motive, into every brain"), new XElement("LINE", "That looks so many fathoms to the sea"), new XElement("LINE", "And hears it roar beneath.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It waves me still."), new XElement("LINE", "Go on; I'll follow thee.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "You shall not go, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Hold off your hands.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Be ruled; you shall not go.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "My fate cries out,"), new XElement("LINE", "And makes each petty artery in this body"), new XElement("LINE", "As hardy as the Nemean lion's nerve."), new XElement("LINE", "Still am I call'd. Unhand me, gentlemen."), new XElement("LINE", "By heaven, I'll make a ghost of him that lets me!"), new XElement("LINE", "I say, away! Go on; I'll follow thee.") ), new XElement("STAGEDIR", "Exeunt Ghost and HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "He waxes desperate with imagination.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Let's follow; 'tis not fit thus to obey him.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Have after. To what issue will this come?") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Something is rotten in the state of Denmark.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Heaven will direct it.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Nay, let's follow him.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE V. Another part of the platform."), new XElement("STAGEDIR", "Enter GHOST and HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Where wilt thou lead me? speak; I'll go no further.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Mark me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I will.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "My hour is almost come,"), new XElement("LINE", "When I to sulphurous and tormenting flames"), new XElement("LINE", "Must render up myself.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Alas, poor ghost!") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Pity me not, but lend thy serious hearing"), new XElement("LINE", "To what I shall unfold.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Speak; I am bound to hear.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "So art thou to revenge, when thou shalt hear.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What?") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "I am thy father's spirit,"), new XElement("LINE", "Doom'd for a certain term to walk the night,"), new XElement("LINE", "And for the day confined to fast in fires,"), new XElement("LINE", "Till the foul crimes done in my days of nature"), new XElement("LINE", "Are burnt and purged away. But that I am forbid"), new XElement("LINE", "To tell the secrets of my prison-house,"), new XElement("LINE", "I could a tale unfold whose lightest word"), new XElement("LINE", "Would harrow up thy soul, freeze thy young blood,"), new XElement("LINE", "Make thy two eyes, like stars, start from their spheres,"), new XElement("LINE", "Thy knotted and combined locks to part"), new XElement("LINE", "And each particular hair to stand on end,"), new XElement("LINE", "Like quills upon the fretful porpentine:"), new XElement("LINE", "But this eternal blazon must not be"), new XElement("LINE", "To ears of flesh and blood. List, list, O, list!"), new XElement("LINE", "If thou didst ever thy dear father love--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O God!") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Revenge his foul and most unnatural murder.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Murder!") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Murder most foul, as in the best it is;"), new XElement("LINE", "But this most foul, strange and unnatural.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Haste me to know't, that I, with wings as swift"), new XElement("LINE", "As meditation or the thoughts of love,"), new XElement("LINE", "May sweep to my revenge.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "I find thee apt;"), new XElement("LINE", "And duller shouldst thou be than the fat weed"), new XElement("LINE", "That roots itself in ease on Lethe wharf,"), new XElement("LINE", "Wouldst thou not stir in this. Now, Hamlet, hear:"), new XElement("LINE", "'Tis given out that, sleeping in my orchard,"), new XElement("LINE", "A serpent stung me; so the whole ear of Denmark"), new XElement("LINE", "Is by a forged process of my death"), new XElement("LINE", "Rankly abused: but know, thou noble youth,"), new XElement("LINE", "The serpent that did sting thy father's life"), new XElement("LINE", "Now wears his crown.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O my prophetic soul! My uncle!") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Ay, that incestuous, that adulterate beast,"), new XElement("LINE", "With witchcraft of his wit, with traitorous gifts,--"), new XElement("LINE", "O wicked wit and gifts, that have the power"), new XElement("LINE", "So to seduce!--won to his shameful lust"), new XElement("LINE", "The will of my most seeming-virtuous queen:"), new XElement("LINE", "O Hamlet, what a falling-off was there!"), new XElement("LINE", "From me, whose love was of that dignity"), new XElement("LINE", "That it went hand in hand even with the vow"), new XElement("LINE", "I made to her in marriage, and to decline"), new XElement("LINE", "Upon a wretch whose natural gifts were poor"), new XElement("LINE", "To those of mine!"), new XElement("LINE", "But virtue, as it never will be moved,"), new XElement("LINE", "Though lewdness court it in a shape of heaven,"), new XElement("LINE", "So lust, though to a radiant angel link'd,"), new XElement("LINE", "Will sate itself in a celestial bed,"), new XElement("LINE", "And prey on garbage."), new XElement("LINE", "But, soft! methinks I scent the morning air;"), new XElement("LINE", "Brief let me be. Sleeping within my orchard,"), new XElement("LINE", "My custom always of the afternoon,"), new XElement("LINE", "Upon my secure hour thy uncle stole,"), new XElement("LINE", "With juice of cursed hebenon in a vial,"), new XElement("LINE", "And in the porches of my ears did pour"), new XElement("LINE", "The leperous distilment; whose effect"), new XElement("LINE", "Holds such an enmity with blood of man"), new XElement("LINE", "That swift as quicksilver it courses through"), new XElement("LINE", "The natural gates and alleys of the body,"), new XElement("LINE", "And with a sudden vigour doth posset"), new XElement("LINE", "And curd, like eager droppings into milk,"), new XElement("LINE", "The thin and wholesome blood: so did it mine;"), new XElement("LINE", "And a most instant tetter bark'd about,"), new XElement("LINE", "Most lazar-like, with vile and loathsome crust,"), new XElement("LINE", "All my smooth body."), new XElement("LINE", "Thus was I, sleeping, by a brother's hand"), new XElement("LINE", "Of life, of crown, of queen, at once dispatch'd:"), new XElement("LINE", "Cut off even in the blossoms of my sin,"), new XElement("LINE", "Unhousel'd, disappointed, unanel'd,"), new XElement("LINE", "No reckoning made, but sent to my account"), new XElement("LINE", "With all my imperfections on my head:"), new XElement("LINE", "O, horrible! O, horrible! most horrible!"), new XElement("LINE", "If thou hast nature in thee, bear it not;"), new XElement("LINE", "Let not the royal bed of Denmark be"), new XElement("LINE", "A couch for luxury and damned incest."), new XElement("LINE", "But, howsoever thou pursuest this act,"), new XElement("LINE", "Taint not thy mind, nor let thy soul contrive"), new XElement("LINE", "Against thy mother aught: leave her to heaven"), new XElement("LINE", "And to those thorns that in her bosom lodge,"), new XElement("LINE", "To prick and sting her. Fare thee well at once!"), new XElement("LINE", "The glow-worm shows the matin to be near,"), new XElement("LINE", "And 'gins to pale his uneffectual fire:"), new XElement("LINE", "Adieu, adieu! Hamlet, remember me.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O all you host of heaven! O earth! what else?"), new XElement("LINE", "And shall I couple hell? O, fie! Hold, hold, my heart;"), new XElement("LINE", "And you, my sinews, grow not instant old,"), new XElement("LINE", "But bear me stiffly up. Remember thee!"), new XElement("LINE", "Ay, thou poor ghost, while memory holds a seat"), new XElement("LINE", "In this distracted globe. Remember thee!"), new XElement("LINE", "Yea, from the table of my memory"), new XElement("LINE", "I'll wipe away all trivial fond records,"), new XElement("LINE", "All saws of books, all forms, all pressures past,"), new XElement("LINE", "That youth and observation copied there;"), new XElement("LINE", "And thy commandment all alone shall live"), new XElement("LINE", "Within the book and volume of my brain,"), new XElement("LINE", "Unmix'd with baser matter: yes, by heaven!"), new XElement("LINE", "O most pernicious woman!"), new XElement("LINE", "O villain, villain, smiling, damned villain!"), new XElement("LINE", "My tables,--meet it is I set it down,"), new XElement("LINE", "That one may smile, and smile, and be a villain;"), new XElement("LINE", "At least I'm sure it may be so in Denmark:"), new XElement("STAGEDIR", "Writing"), new XElement("LINE", "So, uncle, there you are. Now to my word;"), new XElement("LINE", "It is 'Adieu, adieu! remember me.'"), new XElement("LINE", "I have sworn 't.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("SPEAKER", "HORATIO"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " My lord, my lord,--" ) ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Lord Hamlet,--" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Heaven secure him!" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "So be it!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Hillo, ho, ho, my lord!" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Hillo, ho, ho, boy! come, bird, come.") ), new XElement("STAGEDIR", "Enter HORATIO and MARCELLUS"), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "How is't, my noble lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What news, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, wonderful!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Good my lord, tell it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No; you'll reveal it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Not I, my lord, by heaven.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Nor I, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How say you, then; would heart of man once think it?"), new XElement("LINE", "But you'll be secret?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Ay, by heaven, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "There's ne'er a villain dwelling in all Denmark"), new XElement("LINE", "But he's an arrant knave.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "There needs no ghost, my lord, come from the grave"), new XElement("LINE", "To tell us this.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, right; you are i' the right;"), new XElement("LINE", "And so, without more circumstance at all,"), new XElement("LINE", "I hold it fit that we shake hands and part:"), new XElement("LINE", "You, as your business and desire shall point you;"), new XElement("LINE", "For every man has business and desire,"), new XElement("LINE", "Such as it is; and for mine own poor part,"), new XElement("LINE", "Look you, I'll go pray.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "These are but wild and whirling words, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I'm sorry they offend you, heartily;"), new XElement("LINE", "Yes, 'faith heartily.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "There's no offence, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Yes, by Saint Patrick, but there is, Horatio,"), new XElement("LINE", "And much offence too. Touching this vision here,"), new XElement("LINE", "It is an honest ghost, that let me tell you:"), new XElement("LINE", "For your desire to know what is between us,"), new XElement("LINE", "O'ermaster 't as you may. And now, good friends,"), new XElement("LINE", "As you are friends, scholars and soldiers,"), new XElement("LINE", "Give me one poor request.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What is't, my lord? we will.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Never make known what you have seen to-night.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "My lord, we will not.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, but swear't.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "In faith,"), new XElement("LINE", "My lord, not I.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "Nor I, my lord, in faith.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Upon my sword.") ), new XElement("SPEECH", new XElement("SPEAKER", "MARCELLUS"), new XElement("LINE", "We have sworn, my lord, already.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Indeed, upon my sword, indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", new XElement("STAGEDIR", "Beneath"), " Swear." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ah, ha, boy! say'st thou so? art thou there,"), new XElement("LINE", "truepenny?"), new XElement("LINE", "Come on--you hear this fellow in the cellarage--"), new XElement("LINE", "Consent to swear.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Propose the oath, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Never to speak of this that you have seen,"), new XElement("LINE", "Swear by my sword.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", new XElement("STAGEDIR", "Beneath"), " Swear." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Hic et ubique? then we'll shift our ground."), new XElement("LINE", "Come hither, gentlemen,"), new XElement("LINE", "And lay your hands again upon my sword:"), new XElement("LINE", "Never to speak of this that you have heard,"), new XElement("LINE", "Swear by my sword.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", new XElement("STAGEDIR", "Beneath"), " Swear." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Well said, old mole! canst work i' the earth so fast?"), new XElement("LINE", "A worthy pioner! Once more remove, good friends.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "O day and night, but this is wondrous strange!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "And therefore as a stranger give it welcome."), new XElement("LINE", "There are more things in heaven and earth, Horatio,"), new XElement("LINE", "Than are dreamt of in your philosophy. But come;"), new XElement("LINE", "Here, as before, never, so help you mercy,"), new XElement("LINE", "How strange or odd soe'er I bear myself,"), new XElement("LINE", "As I perchance hereafter shall think meet"), new XElement("LINE", "To put an antic disposition on,"), new XElement("LINE", "That you, at such times seeing me, never shall,"), new XElement("LINE", "With arms encumber'd thus, or this headshake,"), new XElement("LINE", "Or by pronouncing of some doubtful phrase,"), new XElement("LINE", "As 'Well, well, we know,' or 'We could, an if we would,'"), new XElement("LINE", "Or 'If we list to speak,' or 'There be, an if they might,'"), new XElement("LINE", "Or such ambiguous giving out, to note"), new XElement("LINE", "That you know aught of me: this not to do,"), new XElement("LINE", "So grace and mercy at your most need help you, Swear.") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", new XElement("STAGEDIR", "Beneath"), " Swear." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Rest, rest, perturbed spirit!"), new XElement("STAGEDIR", "They swear"), new XElement("LINE", "So, gentlemen,"), new XElement("LINE", "With all my love I do commend me to you:"), new XElement("LINE", "And what so poor a man as Hamlet is"), new XElement("LINE", "May do, to express his love and friending to you,"), new XElement("LINE", "God willing, shall not lack. Let us go in together;"), new XElement("LINE", "And still your fingers on your lips, I pray."), new XElement("LINE", "The time is out of joint: O cursed spite,"), new XElement("LINE", "That ever I was born to set it right!"), new XElement("LINE", "Nay, come, let's go together.") ), new XElement("STAGEDIR", "Exeunt") ) ), new XElement("ACT", new XElement("TITLE", "ACT II"), new XElement("SCENE", new XElement("TITLE", "SCENE I. A room in POLONIUS' house."), new XElement("STAGEDIR", "Enter POLONIUS and REYNALDO"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Give him this money and these notes, Reynaldo.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "I will, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "You shall do marvellous wisely, good Reynaldo,"), new XElement("LINE", "Before you visit him, to make inquire"), new XElement("LINE", "Of his behavior.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "My lord, I did intend it.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Marry, well said; very well said. Look you, sir,"), new XElement("LINE", "Inquire me first what Danskers are in Paris;"), new XElement("LINE", "And how, and who, what means, and where they keep,"), new XElement("LINE", "What company, at what expense; and finding"), new XElement("LINE", "By this encompassment and drift of question"), new XElement("LINE", "That they do know my son, come you more nearer"), new XElement("LINE", "Than your particular demands will touch it:"), new XElement("LINE", "Take you, as 'twere, some distant knowledge of him;"), new XElement("LINE", "As thus, 'I know his father and his friends,"), new XElement("LINE", "And in part him: ' do you mark this, Reynaldo?") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "Ay, very well, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "'And in part him; but' you may say 'not well:"), new XElement("LINE", "But, if't be he I mean, he's very wild;"), new XElement("LINE", "Addicted so and so:' and there put on him"), new XElement("LINE", "What forgeries you please; marry, none so rank"), new XElement("LINE", "As may dishonour him; take heed of that;"), new XElement("LINE", "But, sir, such wanton, wild and usual slips"), new XElement("LINE", "As are companions noted and most known"), new XElement("LINE", "To youth and liberty.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "As gaming, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Ay, or drinking, fencing, swearing, quarrelling,"), new XElement("LINE", "Drabbing: you may go so far.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "My lord, that would dishonour him.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "'Faith, no; as you may season it in the charge"), new XElement("LINE", "You must not put another scandal on him,"), new XElement("LINE", "That he is open to incontinency;"), new XElement("LINE", "That's not my meaning: but breathe his faults so quaintly"), new XElement("LINE", "That they may seem the taints of liberty,"), new XElement("LINE", "The flash and outbreak of a fiery mind,"), new XElement("LINE", "A savageness in unreclaimed blood,"), new XElement("LINE", "Of general assault.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "But, my good lord,--") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Wherefore should you do this?") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "Ay, my lord,"), new XElement("LINE", "I would know that.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Marry, sir, here's my drift;"), new XElement("LINE", "And I believe, it is a fetch of wit:"), new XElement("LINE", "You laying these slight sullies on my son,"), new XElement("LINE", "As 'twere a thing a little soil'd i' the working, Mark you,"), new XElement("LINE", "Your party in converse, him you would sound,"), new XElement("LINE", "Having ever seen in the prenominate crimes"), new XElement("LINE", "The youth you breathe of guilty, be assured"), new XElement("LINE", "He closes with you in this consequence;"), new XElement("LINE", "'Good sir,' or so, or 'friend,' or 'gentleman,'"), new XElement("LINE", "According to the phrase or the addition"), new XElement("LINE", "Of man and country.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "Very good, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "And then, sir, does he this--he does--what was I"), new XElement("LINE", "about to say? By the mass, I was about to say"), new XElement("LINE", "something: where did I leave?") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "At 'closes in the consequence,' at 'friend or so,'"), new XElement("LINE", "and 'gentleman.'") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "At 'closes in the consequence,' ay, marry;"), new XElement("LINE", "He closes thus: 'I know the gentleman;"), new XElement("LINE", "I saw him yesterday, or t' other day,"), new XElement("LINE", "Or then, or then; with such, or such; and, as you say,"), new XElement("LINE", "There was a' gaming; there o'ertook in's rouse;"), new XElement("LINE", "There falling out at tennis:' or perchance,"), new XElement("LINE", "'I saw him enter such a house of sale,'"), new XElement("LINE", "Videlicet, a brothel, or so forth."), new XElement("LINE", "See you now;"), new XElement("LINE", "Your bait of falsehood takes this carp of truth:"), new XElement("LINE", "And thus do we of wisdom and of reach,"), new XElement("LINE", "With windlasses and with assays of bias,"), new XElement("LINE", "By indirections find directions out:"), new XElement("LINE", "So by my former lecture and advice,"), new XElement("LINE", "Shall you my son. You have me, have you not?") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "My lord, I have.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "God be wi' you; fare you well.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "Good my lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Observe his inclination in yourself.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "I shall, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "And let him ply his music.") ), new XElement("SPEECH", new XElement("SPEAKER", "REYNALDO"), new XElement("LINE", "Well, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Farewell!"), new XElement("STAGEDIR", "Exit REYNALDO"), new XElement("STAGEDIR", "Enter OPHELIA"), new XElement("LINE", "How now, Ophelia! what's the matter?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "O, my lord, my lord, I have been so affrighted!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "With what, i' the name of God?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My lord, as I was sewing in my closet,"), new XElement("LINE", "Lord Hamlet, with his doublet all unbraced;"), new XElement("LINE", "No hat upon his head; his stockings foul'd,"), new XElement("LINE", "Ungarter'd, and down-gyved to his ancle;"), new XElement("LINE", "Pale as his shirt; his knees knocking each other;"), new XElement("LINE", "And with a look so piteous in purport"), new XElement("LINE", "As if he had been loosed out of hell"), new XElement("LINE", "To speak of horrors,--he comes before me.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Mad for thy love?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My lord, I do not know;"), new XElement("LINE", "But truly, I do fear it.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What said he?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "He took me by the wrist and held me hard;"), new XElement("LINE", "Then goes he to the length of all his arm;"), new XElement("LINE", "And, with his other hand thus o'er his brow,"), new XElement("LINE", "He falls to such perusal of my face"), new XElement("LINE", "As he would draw it. Long stay'd he so;"), new XElement("LINE", "At last, a little shaking of mine arm"), new XElement("LINE", "And thrice his head thus waving up and down,"), new XElement("LINE", "He raised a sigh so piteous and profound"), new XElement("LINE", "As it did seem to shatter all his bulk"), new XElement("LINE", "And end his being: that done, he lets me go:"), new XElement("LINE", "And, with his head over his shoulder turn'd,"), new XElement("LINE", "He seem'd to find his way without his eyes;"), new XElement("LINE", "For out o' doors he went without their helps,"), new XElement("LINE", "And, to the last, bended their light on me.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Come, go with me: I will go seek the king."), new XElement("LINE", "This is the very ecstasy of love,"), new XElement("LINE", "Whose violent property fordoes itself"), new XElement("LINE", "And leads the will to desperate undertakings"), new XElement("LINE", "As oft as any passion under heaven"), new XElement("LINE", "That does afflict our natures. I am sorry."), new XElement("LINE", "What, have you given him any hard words of late?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "No, my good lord, but, as you did command,"), new XElement("LINE", "I did repel his fetters and denied"), new XElement("LINE", "His access to me.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "That hath made him mad."), new XElement("LINE", "I am sorry that with better heed and judgment"), new XElement("LINE", "I had not quoted him: I fear'd he did but trifle,"), new XElement("LINE", "And meant to wreck thee; but, beshrew my jealousy!"), new XElement("LINE", "By heaven, it is as proper to our age"), new XElement("LINE", "To cast beyond ourselves in our opinions"), new XElement("LINE", "As it is common for the younger sort"), new XElement("LINE", "To lack discretion. Come, go we to the king:"), new XElement("LINE", "This must be known; which, being kept close, might"), new XElement("LINE", "move"), new XElement("LINE", "More grief to hide than hate to utter love.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE II. A room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, QUEEN GERTRUDE, ROSENCRANTZ,\n" + "GUILDENSTERN, and Attendants" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Welcome, dear Rosencrantz and Guildenstern!"), new XElement("LINE", "Moreover that we much did long to see you,"), new XElement("LINE", "The need we have to use you did provoke"), new XElement("LINE", "Our hasty sending. Something have you heard"), new XElement("LINE", "Of Hamlet's transformation; so call it,"), new XElement("LINE", "Sith nor the exterior nor the inward man"), new XElement("LINE", "Resembles that it was. What it should be,"), new XElement("LINE", "More than his father's death, that thus hath put him"), new XElement("LINE", "So much from the understanding of himself,"), new XElement("LINE", "I cannot dream of: I entreat you both,"), new XElement("LINE", "That, being of so young days brought up with him,"), new XElement("LINE", "And sith so neighbour'd to his youth and havior,"), new XElement("LINE", "That you vouchsafe your rest here in our court"), new XElement("LINE", "Some little time: so by your companies"), new XElement("LINE", "To draw him on to pleasures, and to gather,"), new XElement("LINE", "So much as from occasion you may glean,"), new XElement("LINE", "Whether aught, to us unknown, afflicts him thus,"), new XElement("LINE", "That, open'd, lies within our remedy.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Good gentlemen, he hath much talk'd of you;"), new XElement("LINE", "And sure I am two men there are not living"), new XElement("LINE", "To whom he more adheres. If it will please you"), new XElement("LINE", "To show us so much gentry and good will"), new XElement("LINE", "As to expend your time with us awhile,"), new XElement("LINE", "For the supply and profit of our hope,"), new XElement("LINE", "Your visitation shall receive such thanks"), new XElement("LINE", "As fits a king's remembrance.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Both your majesties"), new XElement("LINE", "Might, by the sovereign power you have of us,"), new XElement("LINE", "Put your dread pleasures more into command"), new XElement("LINE", "Than to entreaty.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "But we both obey,"), new XElement("LINE", "And here give up ourselves, in the full bent"), new XElement("LINE", "To lay our service freely at your feet,"), new XElement("LINE", "To be commanded.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Thanks, Rosencrantz and gentle Guildenstern.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Thanks, Guildenstern and gentle Rosencrantz:"), new XElement("LINE", "And I beseech you instantly to visit"), new XElement("LINE", "My too much changed son. Go, some of you,"), new XElement("LINE", "And bring these gentlemen where Hamlet is.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Heavens make our presence and our practises"), new XElement("LINE", "Pleasant and helpful to him!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Ay, amen!") ), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ, GUILDENSTERN, and some\n" + "Attendants" ), new XElement("STAGEDIR", "Enter POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "The ambassadors from Norway, my good lord,"), new XElement("LINE", "Are joyfully return'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Thou still hast been the father of good news.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Have I, my lord? I assure my good liege,"), new XElement("LINE", "I hold my duty, as I hold my soul,"), new XElement("LINE", "Both to my God and to my gracious king:"), new XElement("LINE", "And I do think, or else this brain of mine"), new XElement("LINE", "Hunts not the trail of policy so sure"), new XElement("LINE", "As it hath used to do, that I have found"), new XElement("LINE", "The very cause of Hamlet's lunacy.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O, speak of that; that do I long to hear.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Give first admittance to the ambassadors;"), new XElement("LINE", "My news shall be the fruit to that great feast.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Thyself do grace to them, and bring them in."), new XElement("STAGEDIR", "Exit POLONIUS"), new XElement("LINE", "He tells me, my dear Gertrude, he hath found"), new XElement("LINE", "The head and source of all your son's distemper.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "I doubt it is no other but the main;"), new XElement("LINE", "His father's death, and our o'erhasty marriage.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Well, we shall sift him."), new XElement("STAGEDIR", "Re-enter POLONIUS, with VOLTIMAND and CORNELIUS"), new XElement("LINE", "Welcome, my good friends!"), new XElement("LINE", "Say, Voltimand, what from our brother Norway?") ), new XElement("SPEECH", new XElement("SPEAKER", "VOLTIMAND"), new XElement("LINE", "Most fair return of greetings and desires."), new XElement("LINE", "Upon our first, he sent out to suppress"), new XElement("LINE", "His nephew's levies; which to him appear'd"), new XElement("LINE", "To be a preparation 'gainst the Polack;"), new XElement("LINE", "But, better look'd into, he truly found"), new XElement("LINE", "It was against your highness: whereat grieved,"), new XElement("LINE", "That so his sickness, age and impotence"), new XElement("LINE", "Was falsely borne in hand, sends out arrests"), new XElement("LINE", "On Fortinbras; which he, in brief, obeys;"), new XElement("LINE", "Receives rebuke from Norway, and in fine"), new XElement("LINE", "Makes vow before his uncle never more"), new XElement("LINE", "To give the assay of arms against your majesty."), new XElement("LINE", "Whereon old Norway, overcome with joy,"), new XElement("LINE", "Gives him three thousand crowns in annual fee,"), new XElement("LINE", "And his commission to employ those soldiers,"), new XElement("LINE", "So levied as before, against the Polack:"), new XElement("LINE", "With an entreaty, herein further shown,"), new XElement("STAGEDIR", "Giving a paper"), new XElement("LINE", "That it might please you to give quiet pass"), new XElement("LINE", "Through your dominions for this enterprise,"), new XElement("LINE", "On such regards of safety and allowance"), new XElement("LINE", "As therein are set down.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "It likes us well;"), new XElement("LINE", "And at our more consider'd time well read,"), new XElement("LINE", "Answer, and think upon this business."), new XElement("LINE", "Meantime we thank you for your well-took labour:"), new XElement("LINE", "Go to your rest; at night we'll feast together:"), new XElement("LINE", "Most welcome home!") ), new XElement("STAGEDIR", "Exeunt VOLTIMAND and CORNELIUS"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "This business is well ended."), new XElement("LINE", "My liege, and madam, to expostulate"), new XElement("LINE", "What majesty should be, what duty is,"), new XElement("LINE", "Why day is day, night night, and time is time,"), new XElement("LINE", "Were nothing but to waste night, day and time."), new XElement("LINE", "Therefore, since brevity is the soul of wit,"), new XElement("LINE", "And tediousness the limbs and outward flourishes,"), new XElement("LINE", "I will be brief: your noble son is mad:"), new XElement("LINE", "Mad call I it; for, to define true madness,"), new XElement("LINE", "What is't but to be nothing else but mad?"), new XElement("LINE", "But let that go.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "More matter, with less art.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Madam, I swear I use no art at all."), new XElement("LINE", "That he is mad, 'tis true: 'tis true 'tis pity;"), new XElement("LINE", "And pity 'tis 'tis true: a foolish figure;"), new XElement("LINE", "But farewell it, for I will use no art."), new XElement("LINE", "Mad let us grant him, then: and now remains"), new XElement("LINE", "That we find out the cause of this effect,"), new XElement("LINE", "Or rather say, the cause of this defect,"), new XElement("LINE", "For this effect defective comes by cause:"), new XElement("LINE", "Thus it remains, and the remainder thus. Perpend."), new XElement("LINE", "I have a daughter--have while she is mine--"), new XElement("LINE", "Who, in her duty and obedience, mark,"), new XElement("LINE", "Hath given me this: now gather, and surmise."), new XElement("STAGEDIR", "Reads"), new XElement("LINE", "'To the celestial and my soul's idol, the most"), new XElement("LINE", "beautified Ophelia,'--"), new XElement("LINE", "That's an ill phrase, a vile phrase; 'beautified' is"), new XElement("LINE", "a vile phrase: but you shall hear. Thus:"), new XElement("STAGEDIR", "Reads"), new XElement("LINE", "'In her excellent white bosom, these, &c.'") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Came this from Hamlet to her?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Good madam, stay awhile; I will be faithful."), new XElement("STAGEDIR", "Reads"), new XElement("LINE", "'Doubt thou the stars are fire;"), new XElement("LINE", "Doubt that the sun doth move;"), new XElement("LINE", "Doubt truth to be a liar;"), new XElement("LINE", "But never doubt I love."), new XElement("LINE", "'O dear Ophelia, I am ill at these numbers;"), new XElement("LINE", "I have not art to reckon my groans: but that"), new XElement("LINE", "I love thee best, O most best, believe it. Adieu."), new XElement("LINE", "'Thine evermore most dear lady, whilst"), new XElement("LINE", "this machine is to him, HAMLET.'"), new XElement("LINE", "This, in obedience, hath my daughter shown me,"), new XElement("LINE", "And more above, hath his solicitings,"), new XElement("LINE", "As they fell out by time, by means and place,"), new XElement("LINE", "All given to mine ear.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "But how hath she"), new XElement("LINE", "Received his love?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What do you think of me?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "As of a man faithful and honourable.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I would fain prove so. But what might you think,"), new XElement("LINE", "When I had seen this hot love on the wing--"), new XElement("LINE", "As I perceived it, I must tell you that,"), new XElement("LINE", "Before my daughter told me--what might you,"), new XElement("LINE", "Or my dear majesty your queen here, think,"), new XElement("LINE", "If I had play'd the desk or table-book,"), new XElement("LINE", "Or given my heart a winking, mute and dumb,"), new XElement("LINE", "Or look'd upon this love with idle sight;"), new XElement("LINE", "What might you think? No, I went round to work,"), new XElement("LINE", "And my young mistress thus I did bespeak:"), new XElement("LINE", "'Lord Hamlet is a prince, out of thy star;"), new XElement("LINE", "This must not be:' and then I precepts gave her,"), new XElement("LINE", "That she should lock herself from his resort,"), new XElement("LINE", "Admit no messengers, receive no tokens."), new XElement("LINE", "Which done, she took the fruits of my advice;"), new XElement("LINE", "And he, repulsed--a short tale to make--"), new XElement("LINE", "Fell into a sadness, then into a fast,"), new XElement("LINE", "Thence to a watch, thence into a weakness,"), new XElement("LINE", "Thence to a lightness, and, by this declension,"), new XElement("LINE", "Into the madness wherein now he raves,"), new XElement("LINE", "And all we mourn for.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Do you think 'tis this?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "It may be, very likely.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Hath there been such a time--I'd fain know that--"), new XElement("LINE", "That I have positively said 'Tis so,'"), new XElement("LINE", "When it proved otherwise?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Not that I know.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Pointing to his head and shoulder") ), new XElement("LINE", "Take this from this, if this be otherwise:"), new XElement("LINE", "If circumstances lead me, I will find"), new XElement("LINE", "Where truth is hid, though it were hid indeed"), new XElement("LINE", "Within the centre.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "How may we try it further?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "You know, sometimes he walks four hours together"), new XElement("LINE", "Here in the lobby.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "So he does indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "At such a time I'll loose my daughter to him:"), new XElement("LINE", "Be you and I behind an arras then;"), new XElement("LINE", "Mark the encounter: if he love her not"), new XElement("LINE", "And be not from his reason fall'n thereon,"), new XElement("LINE", "Let me be no assistant for a state,"), new XElement("LINE", "But keep a farm and carters.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "We will try it.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "But, look, where sadly the poor wretch comes reading.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Away, I do beseech you, both away:"), new XElement("LINE", "I'll board him presently."), new XElement("STAGEDIR", "Exeunt KING CLAUDIUS, QUEEN GERTRUDE, and\n" + "Attendants" ), new XElement("STAGEDIR", "Enter HAMLET, reading"), new XElement("LINE", "O, give me leave:"), new XElement("LINE", "How does my good Lord Hamlet?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Well, God-a-mercy.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Do you know me, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Excellent well; you are a fishmonger.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Not I, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then I would you were so honest a man.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Honest, my lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, sir; to be honest, as this world goes, is to be"), new XElement("LINE", "one man picked out of ten thousand.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "That's very true, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "For if the sun breed maggots in a dead dog, being a"), new XElement("LINE", "god kissing carrion,--Have you a daughter?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I have, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Let her not walk i' the sun: conception is a"), new XElement("LINE", "blessing: but not as your daughter may conceive."), new XElement("LINE", "Friend, look to 't.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " How say you by that? Still harping on my" ), new XElement("LINE", "daughter: yet he knew me not at first; he said I"), new XElement("LINE", "was a fishmonger: he is far gone, far gone: and"), new XElement("LINE", "truly in my youth I suffered much extremity for"), new XElement("LINE", "love; very near this. I'll speak to him again."), new XElement("LINE", "What do you read, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Words, words, words.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What is the matter, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Between who?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I mean, the matter that you read, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Slanders, sir: for the satirical rogue says here"), new XElement("LINE", "that old men have grey beards, that their faces are"), new XElement("LINE", "wrinkled, their eyes purging thick amber and"), new XElement("LINE", "plum-tree gum and that they have a plentiful lack of"), new XElement("LINE", "wit, together with most weak hams: all which, sir,"), new XElement("LINE", "though I most powerfully and potently believe, yet"), new XElement("LINE", "I hold it not honesty to have it thus set down, for"), new XElement("LINE", "yourself, sir, should be old as I am, if like a crab"), new XElement("LINE", "you could go backward.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " Though this be madness, yet there is method" ), new XElement("LINE", "in 't. Will you walk out of the air, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Into my grave.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Indeed, that is out o' the air."), new XElement("STAGEDIR", "Aside"), new XElement("LINE", "How pregnant sometimes his replies are! a happiness"), new XElement("LINE", "that often madness hits on, which reason and sanity"), new XElement("LINE", "could not so prosperously be delivered of. I will"), new XElement("LINE", "leave him, and suddenly contrive the means of"), new XElement("LINE", "meeting between him and my daughter.--My honourable"), new XElement("LINE", "lord, I will most humbly take my leave of you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "You cannot, sir, take from me any thing that I will"), new XElement("LINE", "more willingly part withal: except my life, except"), new XElement("LINE", "my life, except my life.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Fare you well, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "These tedious old fools!") ), new XElement("STAGEDIR", "Enter ROSENCRANTZ and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "You go to seek the Lord Hamlet; there he is.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", new XElement("STAGEDIR", "To POLONIUS"), " God save you, sir!" ) ), new XElement("STAGEDIR", "Exit POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "My honoured lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "My most dear lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "My excellent good friends! How dost thou,"), new XElement("LINE", "Guildenstern? Ah, Rosencrantz! Good lads, how do ye both?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "As the indifferent children of the earth.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Happy, in that we are not over-happy;"), new XElement("LINE", "On fortune's cap we are not the very button.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nor the soles of her shoe?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Neither, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then you live about her waist, or in the middle of"), new XElement("LINE", "her favours?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "'Faith, her privates we.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "In the secret parts of fortune? O, most true; she"), new XElement("LINE", "is a strumpet. What's the news?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "None, my lord, but that the world's grown honest.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then is doomsday near: but your news is not true."), new XElement("LINE", "Let me question more in particular: what have you,"), new XElement("LINE", "my good friends, deserved at the hands of fortune,"), new XElement("LINE", "that she sends you to prison hither?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Prison, my lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Denmark's a prison.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Then is the world one.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A goodly one; in which there are many confines,"), new XElement("LINE", "wards and dungeons, Denmark being one o' the worst.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "We think not so, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, then, 'tis none to you; for there is nothing"), new XElement("LINE", "either good or bad, but thinking makes it so: to me"), new XElement("LINE", "it is a prison.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Why then, your ambition makes it one; 'tis too"), new XElement("LINE", "narrow for your mind.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O God, I could be bounded in a nut shell and count"), new XElement("LINE", "myself a king of infinite space, were it not that I"), new XElement("LINE", "have bad dreams.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Which dreams indeed are ambition, for the very"), new XElement("LINE", "substance of the ambitious is merely the shadow of a dream.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A dream itself is but a shadow.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Truly, and I hold ambition of so airy and light a"), new XElement("LINE", "quality that it is but a shadow's shadow.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then are our beggars bodies, and our monarchs and"), new XElement("LINE", "outstretched heroes the beggars' shadows. Shall we"), new XElement("LINE", "to the court? for, by my fay, I cannot reason.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "We'll wait upon you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No such matter: I will not sort you with the rest"), new XElement("LINE", "of my servants, for, to speak to you like an honest"), new XElement("LINE", "man, I am most dreadfully attended. But, in the"), new XElement("LINE", "beaten way of friendship, what make you at Elsinore?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "To visit you, my lord; no other occasion.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Beggar that I am, I am even poor in thanks; but I"), new XElement("LINE", "thank you: and sure, dear friends, my thanks are"), new XElement("LINE", "too dear a halfpenny. Were you not sent for? Is it"), new XElement("LINE", "your own inclining? Is it a free visitation? Come,"), new XElement("LINE", "deal justly with me: come, come; nay, speak.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "What should we say, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, any thing, but to the purpose. You were sent"), new XElement("LINE", "for; and there is a kind of confession in your looks"), new XElement("LINE", "which your modesties have not craft enough to colour:"), new XElement("LINE", "I know the good king and queen have sent for you.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "To what end, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That you must teach me. But let me conjure you, by"), new XElement("LINE", "the rights of our fellowship, by the consonancy of"), new XElement("LINE", "our youth, by the obligation of our ever-preserved"), new XElement("LINE", "love, and by what more dear a better proposer could"), new XElement("LINE", "charge you withal, be even and direct with me,"), new XElement("LINE", "whether you were sent for, or no?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", new XElement("STAGEDIR", "Aside to GUILDENSTERN"), " What say you?" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " Nay, then, I have an eye of you.--If you" ), new XElement("LINE", "love me, hold not off.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "My lord, we were sent for.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I will tell you why; so shall my anticipation"), new XElement("LINE", "prevent your discovery, and your secrecy to the king"), new XElement("LINE", "and queen moult no feather. I have of late--but"), new XElement("LINE", "wherefore I know not--lost all my mirth, forgone all"), new XElement("LINE", "custom of exercises; and indeed it goes so heavily"), new XElement("LINE", "with my disposition that this goodly frame, the"), new XElement("LINE", "earth, seems to me a sterile promontory, this most"), new XElement("LINE", "excellent canopy, the air, look you, this brave"), new XElement("LINE", "o'erhanging firmament, this majestical roof fretted"), new XElement("LINE", "with golden fire, why, it appears no other thing to"), new XElement("LINE", "me than a foul and pestilent congregation of vapours."), new XElement("LINE", "What a piece of work is a man! how noble in reason!"), new XElement("LINE", "how infinite in faculty! in form and moving how"), new XElement("LINE", "express and admirable! in action how like an angel!"), new XElement("LINE", "in apprehension how like a god! the beauty of the"), new XElement("LINE", "world! the paragon of animals! And yet, to me,"), new XElement("LINE", "what is this quintessence of dust? man delights not"), new XElement("LINE", "me: no, nor woman neither, though by your smiling"), new XElement("LINE", "you seem to say so.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "My lord, there was no such stuff in my thoughts.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why did you laugh then, when I said 'man delights not me'?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "To think, my lord, if you delight not in man, what"), new XElement("LINE", "lenten entertainment the players shall receive from"), new XElement("LINE", "you: we coted them on the way; and hither are they"), new XElement("LINE", "coming, to offer you service.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "He that plays the king shall be welcome; his majesty"), new XElement("LINE", "shall have tribute of me; the adventurous knight"), new XElement("LINE", "shall use his foil and target; the lover shall not"), new XElement("LINE", "sigh gratis; the humourous man shall end his part"), new XElement("LINE", "in peace; the clown shall make those laugh whose"), new XElement("LINE", "lungs are tickled o' the sere; and the lady shall"), new XElement("LINE", "say her mind freely, or the blank verse shall halt"), new XElement("LINE", "for't. What players are they?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Even those you were wont to take delight in, the"), new XElement("LINE", "tragedians of the city.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How chances it they travel? their residence, both"), new XElement("LINE", "in reputation and profit, was better both ways.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "I think their inhibition comes by the means of the"), new XElement("LINE", "late innovation.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do they hold the same estimation they did when I was"), new XElement("LINE", "in the city? are they so followed?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "No, indeed, are they not.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How comes it? do they grow rusty?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Nay, their endeavour keeps in the wonted pace: but"), new XElement("LINE", "there is, sir, an aery of children, little eyases,"), new XElement("LINE", "that cry out on the top of question, and are most"), new XElement("LINE", "tyrannically clapped for't: these are now the"), new XElement("LINE", "fashion, and so berattle the common stages--so they"), new XElement("LINE", "call them--that many wearing rapiers are afraid of"), new XElement("LINE", "goose-quills and dare scarce come thither.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What, are they children? who maintains 'em? how are"), new XElement("LINE", "they escoted? Will they pursue the quality no"), new XElement("LINE", "longer than they can sing? will they not say"), new XElement("LINE", "afterwards, if they should grow themselves to common"), new XElement("LINE", "players--as it is most like, if their means are no"), new XElement("LINE", "better--their writers do them wrong, to make them"), new XElement("LINE", "exclaim against their own succession?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "'Faith, there has been much to do on both sides; and"), new XElement("LINE", "the nation holds it no sin to tarre them to"), new XElement("LINE", "controversy: there was, for a while, no money bid"), new XElement("LINE", "for argument, unless the poet and the player went to"), new XElement("LINE", "cuffs in the question.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Is't possible?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "O, there has been much throwing about of brains.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do the boys carry it away?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Ay, that they do, my lord; Hercules and his load too.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It is not very strange; for mine uncle is king of"), new XElement("LINE", "Denmark, and those that would make mows at him while"), new XElement("LINE", "my father lived, give twenty, forty, fifty, an"), new XElement("LINE", "hundred ducats a-piece for his picture in little."), new XElement("LINE", "'Sblood, there is something in this more than"), new XElement("LINE", "natural, if philosophy could find it out.") ), new XElement("STAGEDIR", "Flourish of trumpets within"), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "There are the players.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Gentlemen, you are welcome to Elsinore. Your hands,"), new XElement("LINE", "come then: the appurtenance of welcome is fashion"), new XElement("LINE", "and ceremony: let me comply with you in this garb,"), new XElement("LINE", "lest my extent to the players, which, I tell you,"), new XElement("LINE", "must show fairly outward, should more appear like"), new XElement("LINE", "entertainment than yours. You are welcome: but my"), new XElement("LINE", "uncle-father and aunt-mother are deceived.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "In what, my dear lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am but mad north-north-west: when the wind is"), new XElement("LINE", "southerly I know a hawk from a handsaw.") ), new XElement("STAGEDIR", "Enter POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Well be with you, gentlemen!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Hark you, Guildenstern; and you too: at each ear a"), new XElement("LINE", "hearer: that great baby you see there is not yet"), new XElement("LINE", "out of his swaddling-clouts.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Happily he's the second time come to them; for they"), new XElement("LINE", "say an old man is twice a child.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I will prophesy he comes to tell me of the players;"), new XElement("LINE", "mark it. You say right, sir: o' Monday morning;"), new XElement("LINE", "'twas so indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "My lord, I have news to tell you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "My lord, I have news to tell you."), new XElement("LINE", "When Roscius was an actor in Rome,--") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "The actors are come hither, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Buz, buz!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Upon mine honour,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then came each actor on his ass,--") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "The best actors in the world, either for tragedy,"), new XElement("LINE", "comedy, history, pastoral, pastoral-comical,"), new XElement("LINE", "historical-pastoral, tragical-historical, tragical-"), new XElement("LINE", "comical-historical-pastoral, scene individable, or"), new XElement("LINE", "poem unlimited: Seneca cannot be too heavy, nor"), new XElement("LINE", "Plautus too light. For the law of writ and the"), new XElement("LINE", "liberty, these are the only men.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O Jephthah, judge of Israel, what a treasure hadst thou!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What a treasure had he, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why,"), new XElement("LINE", "'One fair daughter and no more,"), new XElement("LINE", "The which he loved passing well.'") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " Still on my daughter." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Am I not i' the right, old Jephthah?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "If you call me Jephthah, my lord, I have a daughter"), new XElement("LINE", "that I love passing well.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, that follows not.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "What follows, then, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why,"), new XElement("LINE", "'As by lot, God wot,'"), new XElement("LINE", "and then, you know,"), new XElement("LINE", "'It came to pass, as most like it was,'--"), new XElement("LINE", "the first row of the pious chanson will show you"), new XElement("LINE", "more; for look, where my abridgement comes."), new XElement("STAGEDIR", "Enter four or five Players"), new XElement("LINE", "You are welcome, masters; welcome, all. I am glad"), new XElement("LINE", "to see thee well. Welcome, good friends. O, my old"), new XElement("LINE", "friend! thy face is valenced since I saw thee last:"), new XElement("LINE", "comest thou to beard me in Denmark? What, my young"), new XElement("LINE", "lady and mistress! By'r lady, your ladyship is"), new XElement("LINE", "nearer to heaven than when I saw you last, by the"), new XElement("LINE", "altitude of a chopine. Pray God, your voice, like"), new XElement("LINE", "apiece of uncurrent gold, be not cracked within the"), new XElement("LINE", "ring. Masters, you are all welcome. We'll e'en"), new XElement("LINE", "to't like French falconers, fly at any thing we see:"), new XElement("LINE", "we'll have a speech straight: come, give us a taste"), new XElement("LINE", "of your quality; come, a passionate speech.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "What speech, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I heard thee speak me a speech once, but it was"), new XElement("LINE", "never acted; or, if it was, not above once; for the"), new XElement("LINE", "play, I remember, pleased not the million; 'twas"), new XElement("LINE", "caviare to the general: but it was--as I received"), new XElement("LINE", "it, and others, whose judgments in such matters"), new XElement("LINE", "cried in the top of mine--an excellent play, well"), new XElement("LINE", "digested in the scenes, set down with as much"), new XElement("LINE", "modesty as cunning. I remember, one said there"), new XElement("LINE", "were no sallets in the lines to make the matter"), new XElement("LINE", "savoury, nor no matter in the phrase that might"), new XElement("LINE", "indict the author of affectation; but called it an"), new XElement("LINE", "honest method, as wholesome as sweet, and by very"), new XElement("LINE", "much more handsome than fine. One speech in it I"), new XElement("LINE", "chiefly loved: 'twas Aeneas' tale to Dido; and"), new XElement("LINE", "thereabout of it especially, where he speaks of"), new XElement("LINE", "Priam's slaughter: if it live in your memory, begin"), new XElement("LINE", "at this line: let me see, let me see--"), new XElement("LINE", "'The rugged Pyrrhus, like the Hyrcanian beast,'--"), new XElement("LINE", "it is not so:--it begins with Pyrrhus:--"), new XElement("LINE", "'The rugged Pyrrhus, he whose sable arms,"), new XElement("LINE", "Black as his purpose, did the night resemble"), new XElement("LINE", "When he lay couched in the ominous horse,"), new XElement("LINE", "Hath now this dread and black complexion smear'd"), new XElement("LINE", "With heraldry more dismal; head to foot"), new XElement("LINE", "Now is he total gules; horridly trick'd"), new XElement("LINE", "With blood of fathers, mothers, daughters, sons,"), new XElement("LINE", "Baked and impasted with the parching streets,"), new XElement("LINE", "That lend a tyrannous and damned light"), new XElement("LINE", "To their lord's murder: roasted in wrath and fire,"), new XElement("LINE", "And thus o'er-sized with coagulate gore,"), new XElement("LINE", "With eyes like carbuncles, the hellish Pyrrhus"), new XElement("LINE", "Old grandsire Priam seeks.'"), new XElement("LINE", "So, proceed you.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "'Fore God, my lord, well spoken, with good accent and"), new XElement("LINE", "good discretion.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "'Anon he finds him"), new XElement("LINE", "Striking too short at Greeks; his antique sword,"), new XElement("LINE", "Rebellious to his arm, lies where it falls,"), new XElement("LINE", "Repugnant to command: unequal match'd,"), new XElement("LINE", "Pyrrhus at Priam drives; in rage strikes wide;"), new XElement("LINE", "But with the whiff and wind of his fell sword"), new XElement("LINE", "The unnerved father falls. Then senseless Ilium,"), new XElement("LINE", "Seeming to feel this blow, with flaming top"), new XElement("LINE", "Stoops to his base, and with a hideous crash"), new XElement("LINE", "Takes prisoner Pyrrhus' ear: for, lo! his sword,"), new XElement("LINE", "Which was declining on the milky head"), new XElement("LINE", "Of reverend Priam, seem'd i' the air to stick:"), new XElement("LINE", "So, as a painted tyrant, Pyrrhus stood,"), new XElement("LINE", "And like a neutral to his will and matter,"), new XElement("LINE", "Did nothing."), new XElement("LINE", "But, as we often see, against some storm,"), new XElement("LINE", "A silence in the heavens, the rack stand still,"), new XElement("LINE", "The bold winds speechless and the orb below"), new XElement("LINE", "As hush as death, anon the dreadful thunder"), new XElement("LINE", "Doth rend the region, so, after Pyrrhus' pause,"), new XElement("LINE", "Aroused vengeance sets him new a-work;"), new XElement("LINE", "And never did the Cyclops' hammers fall"), new XElement("LINE", "On Mars's armour forged for proof eterne"), new XElement("LINE", "With less remorse than Pyrrhus' bleeding sword"), new XElement("LINE", "Now falls on Priam."), new XElement("LINE", "Out, out, thou strumpet, Fortune! All you gods,"), new XElement("LINE", "In general synod 'take away her power;"), new XElement("LINE", "Break all the spokes and fellies from her wheel,"), new XElement("LINE", "And bowl the round nave down the hill of heaven,"), new XElement("LINE", "As low as to the fiends!'") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "This is too long.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It shall to the barber's, with your beard. Prithee,"), new XElement("LINE", "say on: he's for a jig or a tale of bawdry, or he"), new XElement("LINE", "sleeps: say on: come to Hecuba.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "'But who, O, who had seen the mobled queen--'") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'The mobled queen?'") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "That's good; 'mobled queen' is good.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "'Run barefoot up and down, threatening the flames"), new XElement("LINE", "With bisson rheum; a clout upon that head"), new XElement("LINE", "Where late the diadem stood, and for a robe,"), new XElement("LINE", "About her lank and all o'er-teemed loins,"), new XElement("LINE", "A blanket, in the alarm of fear caught up;"), new XElement("LINE", "Who this had seen, with tongue in venom steep'd,"), new XElement("LINE", "'Gainst Fortune's state would treason have"), new XElement("LINE", "pronounced:"), new XElement("LINE", "But if the gods themselves did see her then"), new XElement("LINE", "When she saw Pyrrhus make malicious sport"), new XElement("LINE", "In mincing with his sword her husband's limbs,"), new XElement("LINE", "The instant burst of clamour that she made,"), new XElement("LINE", "Unless things mortal move them not at all,"), new XElement("LINE", "Would have made milch the burning eyes of heaven,"), new XElement("LINE", "And passion in the gods.'") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Look, whether he has not turned his colour and has"), new XElement("LINE", "tears in's eyes. Pray you, no more.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Tis well: I'll have thee speak out the rest soon."), new XElement("LINE", "Good my lord, will you see the players well"), new XElement("LINE", "bestowed? Do you hear, let them be well used; for"), new XElement("LINE", "they are the abstract and brief chronicles of the"), new XElement("LINE", "time: after your death you were better have a bad"), new XElement("LINE", "epitaph than their ill report while you live.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "My lord, I will use them according to their desert.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "God's bodykins, man, much better: use every man"), new XElement("LINE", "after his desert, and who should 'scape whipping?"), new XElement("LINE", "Use them after your own honour and dignity: the less"), new XElement("LINE", "they deserve, the more merit is in your bounty."), new XElement("LINE", "Take them in.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Come, sirs.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Follow him, friends: we'll hear a play to-morrow."), new XElement("STAGEDIR", "Exit POLONIUS with all the Players but the First"), new XElement("LINE", "Dost thou hear me, old friend; can you play the"), new XElement("LINE", "Murder of Gonzago?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "Ay, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "We'll ha't to-morrow night. You could, for a need,"), new XElement("LINE", "study a speech of some dozen or sixteen lines, which"), new XElement("LINE", "I would set down and insert in't, could you not?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "Ay, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Very well. Follow that lord; and look you mock him"), new XElement("LINE", "not."), new XElement("STAGEDIR", "Exit First Player"), new XElement("LINE", "My good friends, I'll leave you till night: you are"), new XElement("LINE", "welcome to Elsinore.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Good my lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, so, God be wi' ye;"), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("LINE", "Now I am alone."), new XElement("LINE", "O, what a rogue and peasant slave am I!"), new XElement("LINE", "Is it not monstrous that this player here,"), new XElement("LINE", "But in a fiction, in a dream of passion,"), new XElement("LINE", "Could force his soul so to his own conceit"), new XElement("LINE", "That from her working all his visage wann'd,"), new XElement("LINE", "Tears in his eyes, distraction in's aspect,"), new XElement("LINE", "A broken voice, and his whole function suiting"), new XElement("LINE", "With forms to his conceit? and all for nothing!"), new XElement("LINE", "For Hecuba!"), new XElement("LINE", "What's Hecuba to him, or he to Hecuba,"), new XElement("LINE", "That he should weep for her? What would he do,"), new XElement("LINE", "Had he the motive and the cue for passion"), new XElement("LINE", "That I have? He would drown the stage with tears"), new XElement("LINE", "And cleave the general ear with horrid speech,"), new XElement("LINE", "Make mad the guilty and appal the free,"), new XElement("LINE", "Confound the ignorant, and amaze indeed"), new XElement("LINE", "The very faculties of eyes and ears. Yet I,"), new XElement("LINE", "A dull and muddy-mettled rascal, peak,"), new XElement("LINE", "Like John-a-dreams, unpregnant of my cause,"), new XElement("LINE", "And can say nothing; no, not for a king,"), new XElement("LINE", "Upon whose property and most dear life"), new XElement("LINE", "A damn'd defeat was made. Am I a coward?"), new XElement("LINE", "Who calls me villain? breaks my pate across?"), new XElement("LINE", "Plucks off my beard, and blows it in my face?"), new XElement("LINE", "Tweaks me by the nose? gives me the lie i' the throat,"), new XElement("LINE", "As deep as to the lungs? who does me this?"), new XElement("LINE", "Ha!"), new XElement("LINE", "'Swounds, I should take it: for it cannot be"), new XElement("LINE", "But I am pigeon-liver'd and lack gall"), new XElement("LINE", "To make oppression bitter, or ere this"), new XElement("LINE", "I should have fatted all the region kites"), new XElement("LINE", "With this slave's offal: bloody, bawdy villain!"), new XElement("LINE", "Remorseless, treacherous, lecherous, kindless villain!"), new XElement("LINE", "O, vengeance!"), new XElement("LINE", "Why, what an ass am I! This is most brave,"), new XElement("LINE", "That I, the son of a dear father murder'd,"), new XElement("LINE", "Prompted to my revenge by heaven and hell,"), new XElement("LINE", "Must, like a whore, unpack my heart with words,"), new XElement("LINE", "And fall a-cursing, like a very drab,"), new XElement("LINE", "A scullion!"), new XElement("LINE", "Fie upon't! foh! About, my brain! I have heard"), new XElement("LINE", "That guilty creatures sitting at a play"), new XElement("LINE", "Have by the very cunning of the scene"), new XElement("LINE", "Been struck so to the soul that presently"), new XElement("LINE", "They have proclaim'd their malefactions;"), new XElement("LINE", "For murder, though it have no tongue, will speak"), new XElement("LINE", "With most miraculous organ. I'll have these players"), new XElement("LINE", "Play something like the murder of my father"), new XElement("LINE", "Before mine uncle: I'll observe his looks;"), new XElement("LINE", "I'll tent him to the quick: if he but blench,"), new XElement("LINE", "I know my course. The spirit that I have seen"), new XElement("LINE", "May be the devil: and the devil hath power"), new XElement("LINE", "To assume a pleasing shape; yea, and perhaps"), new XElement("LINE", "Out of my weakness and my melancholy,"), new XElement("LINE", "As he is very potent with such spirits,"), new XElement("LINE", "Abuses me to damn me: I'll have grounds"), new XElement("LINE", "More relative than this: the play 's the thing"), new XElement("LINE", "Wherein I'll catch the conscience of the king.") ), new XElement("STAGEDIR", "Exit") ) ), new XElement("ACT", new XElement("TITLE", "ACT III"), new XElement("SCENE", new XElement("TITLE", "SCENE I. A room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, QUEEN GERTRUDE, POLONIUS,\n" + "OPHELIA, ROSENCRANTZ, and GUILDENSTERN" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "And can you, by no drift of circumstance,"), new XElement("LINE", "Get from him why he puts on this confusion,"), new XElement("LINE", "Grating so harshly all his days of quiet"), new XElement("LINE", "With turbulent and dangerous lunacy?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "He does confess he feels himself distracted;"), new XElement("LINE", "But from what cause he will by no means speak.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Nor do we find him forward to be sounded,"), new XElement("LINE", "But, with a crafty madness, keeps aloof,"), new XElement("LINE", "When we would bring him on to some confession"), new XElement("LINE", "Of his true state.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Did he receive you well?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Most like a gentleman.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "But with much forcing of his disposition.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Niggard of question; but, of our demands,"), new XElement("LINE", "Most free in his reply.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Did you assay him?"), new XElement("LINE", "To any pastime?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Madam, it so fell out, that certain players"), new XElement("LINE", "We o'er-raught on the way: of these we told him;"), new XElement("LINE", "And there did seem in him a kind of joy"), new XElement("LINE", "To hear of it: they are about the court,"), new XElement("LINE", "And, as I think, they have already order"), new XElement("LINE", "This night to play before him.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "'Tis most true:"), new XElement("LINE", "And he beseech'd me to entreat your majesties"), new XElement("LINE", "To hear and see the matter.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "With all my heart; and it doth much content me"), new XElement("LINE", "To hear him so inclined."), new XElement("LINE", "Good gentlemen, give him a further edge,"), new XElement("LINE", "And drive his purpose on to these delights.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "We shall, my lord.") ), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Sweet Gertrude, leave us too;"), new XElement("LINE", "For we have closely sent for Hamlet hither,"), new XElement("LINE", "That he, as 'twere by accident, may here"), new XElement("LINE", "Affront Ophelia:"), new XElement("LINE", "Her father and myself, lawful espials,"), new XElement("LINE", "Will so bestow ourselves that, seeing, unseen,"), new XElement("LINE", "We may of their encounter frankly judge,"), new XElement("LINE", "And gather by him, as he is behaved,"), new XElement("LINE", "If 't be the affliction of his love or no"), new XElement("LINE", "That thus he suffers for.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "I shall obey you."), new XElement("LINE", "And for your part, Ophelia, I do wish"), new XElement("LINE", "That your good beauties be the happy cause"), new XElement("LINE", "Of Hamlet's wildness: so shall I hope your virtues"), new XElement("LINE", "Will bring him to his wonted way again,"), new XElement("LINE", "To both your honours.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Madam, I wish it may.") ), new XElement("STAGEDIR", "Exit QUEEN GERTRUDE"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Ophelia, walk you here. Gracious, so please you,"), new XElement("LINE", "We will bestow ourselves."), new XElement("STAGEDIR", "To OPHELIA"), new XElement("LINE", "Read on this book;"), new XElement("LINE", "That show of such an exercise may colour"), new XElement("LINE", "Your loneliness. We are oft to blame in this,--"), new XElement("LINE", "'Tis too much proved--that with devotion's visage"), new XElement("LINE", "And pious action we do sugar o'er"), new XElement("LINE", "The devil himself.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " O, 'tis too true!" ), new XElement("LINE", "How smart a lash that speech doth give my conscience!"), new XElement("LINE", "The harlot's cheek, beautied with plastering art,"), new XElement("LINE", "Is not more ugly to the thing that helps it"), new XElement("LINE", "Than is my deed to my most painted word:"), new XElement("LINE", "O heavy burthen!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I hear him coming: let's withdraw, my lord.") ), new XElement("STAGEDIR", "Exeunt KING CLAUDIUS and POLONIUS"), new XElement("STAGEDIR", "Enter HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "To be, or not to be: that is the question:"), new XElement("LINE", "Whether 'tis nobler in the mind to suffer"), new XElement("LINE", "The slings and arrows of outrageous fortune,"), new XElement("LINE", "Or to take arms against a sea of troubles,"), new XElement("LINE", "And by opposing end them? To die: to sleep;"), new XElement("LINE", "No more; and by a sleep to say we end"), new XElement("LINE", "The heart-ache and the thousand natural shocks"), new XElement("LINE", "That flesh is heir to, 'tis a consummation"), new XElement("LINE", "Devoutly to be wish'd. To die, to sleep;"), new XElement("LINE", "To sleep: perchance to dream: ay, there's the rub;"), new XElement("LINE", "For in that sleep of death what dreams may come"), new XElement("LINE", "When we have shuffled off this mortal coil,"), new XElement("LINE", "Must give us pause: there's the respect"), new XElement("LINE", "That makes calamity of so long life;"), new XElement("LINE", "For who would bear the whips and scorns of time,"), new XElement("LINE", "The oppressor's wrong, the proud man's contumely,"), new XElement("LINE", "The pangs of despised love, the law's delay,"), new XElement("LINE", "The insolence of office and the spurns"), new XElement("LINE", "That patient merit of the unworthy takes,"), new XElement("LINE", "When he himself might his quietus make"), new XElement("LINE", "With a bare bodkin? who would fardels bear,"), new XElement("LINE", "To grunt and sweat under a weary life,"), new XElement("LINE", "But that the dread of something after death,"), new XElement("LINE", "The undiscover'd country from whose bourn"), new XElement("LINE", "No traveller returns, puzzles the will"), new XElement("LINE", "And makes us rather bear those ills we have"), new XElement("LINE", "Than fly to others that we know not of?"), new XElement("LINE", "Thus conscience does make cowards of us all;"), new XElement("LINE", "And thus the native hue of resolution"), new XElement("LINE", "Is sicklied o'er with the pale cast of thought,"), new XElement("LINE", "And enterprises of great pith and moment"), new XElement("LINE", "With this regard their currents turn awry,"), new XElement("LINE", "And lose the name of action.--Soft you now!"), new XElement("LINE", "The fair Ophelia! Nymph, in thy orisons"), new XElement("LINE", "Be all my sins remember'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Good my lord,"), new XElement("LINE", "How does your honour for this many a day?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I humbly thank you; well, well, well.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My lord, I have remembrances of yours,"), new XElement("LINE", "That I have longed long to re-deliver;"), new XElement("LINE", "I pray you, now receive them.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, not I;"), new XElement("LINE", "I never gave you aught.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My honour'd lord, you know right well you did;"), new XElement("LINE", "And, with them, words of so sweet breath composed"), new XElement("LINE", "As made the things more rich: their perfume lost,"), new XElement("LINE", "Take these again; for to the noble mind"), new XElement("LINE", "Rich gifts wax poor when givers prove unkind."), new XElement("LINE", "There, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ha, ha! are you honest?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "My lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Are you fair?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "What means your lordship?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That if you be honest and fair, your honesty should"), new XElement("LINE", "admit no discourse to your beauty.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Could beauty, my lord, have better commerce than"), new XElement("LINE", "with honesty?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, truly; for the power of beauty will sooner"), new XElement("LINE", "transform honesty from what it is to a bawd than the"), new XElement("LINE", "force of honesty can translate beauty into his"), new XElement("LINE", "likeness: this was sometime a paradox, but now the"), new XElement("LINE", "time gives it proof. I did love you once.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Indeed, my lord, you made me believe so.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "You should not have believed me; for virtue cannot"), new XElement("LINE", "so inoculate our old stock but we shall relish of"), new XElement("LINE", "it: I loved you not.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I was the more deceived.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Get thee to a nunnery: why wouldst thou be a"), new XElement("LINE", "breeder of sinners? I am myself indifferent honest;"), new XElement("LINE", "but yet I could accuse me of such things that it"), new XElement("LINE", "were better my mother had not borne me: I am very"), new XElement("LINE", "proud, revengeful, ambitious, with more offences at"), new XElement("LINE", "my beck than I have thoughts to put them in,"), new XElement("LINE", "imagination to give them shape, or time to act them"), new XElement("LINE", "in. What should such fellows as I do crawling"), new XElement("LINE", "between earth and heaven? We are arrant knaves,"), new XElement("LINE", "all; believe none of us. Go thy ways to a nunnery."), new XElement("LINE", "Where's your father?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "At home, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Let the doors be shut upon him, that he may play the"), new XElement("LINE", "fool no where but in's own house. Farewell.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "O, help him, you sweet heavens!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "If thou dost marry, I'll give thee this plague for"), new XElement("LINE", "thy dowry: be thou as chaste as ice, as pure as"), new XElement("LINE", "snow, thou shalt not escape calumny. Get thee to a"), new XElement("LINE", "nunnery, go: farewell. Or, if thou wilt needs"), new XElement("LINE", "marry, marry a fool; for wise men know well enough"), new XElement("LINE", "what monsters you make of them. To a nunnery, go,"), new XElement("LINE", "and quickly too. Farewell.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "O heavenly powers, restore him!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I have heard of your paintings too, well enough; God"), new XElement("LINE", "has given you one face, and you make yourselves"), new XElement("LINE", "another: you jig, you amble, and you lisp, and"), new XElement("LINE", "nick-name God's creatures, and make your wantonness"), new XElement("LINE", "your ignorance. Go to, I'll no more on't; it hath"), new XElement("LINE", "made me mad. I say, we will have no more marriages:"), new XElement("LINE", "those that are married already, all but one, shall"), new XElement("LINE", "live; the rest shall keep as they are. To a"), new XElement("LINE", "nunnery, go.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "O, what a noble mind is here o'erthrown!"), new XElement("LINE", "The courtier's, soldier's, scholar's, eye, tongue, sword;"), new XElement("LINE", "The expectancy and rose of the fair state,"), new XElement("LINE", "The glass of fashion and the mould of form,"), new XElement("LINE", "The observed of all observers, quite, quite down!"), new XElement("LINE", "And I, of ladies most deject and wretched,"), new XElement("LINE", "That suck'd the honey of his music vows,"), new XElement("LINE", "Now see that noble and most sovereign reason,"), new XElement("LINE", "Like sweet bells jangled, out of tune and harsh;"), new XElement("LINE", "That unmatch'd form and feature of blown youth"), new XElement("LINE", "Blasted with ecstasy: O, woe is me,"), new XElement("LINE", "To have seen what I have seen, see what I see!") ), new XElement("STAGEDIR", "Re-enter KING CLAUDIUS and POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Love! his affections do not that way tend;"), new XElement("LINE", "Nor what he spake, though it lack'd form a little,"), new XElement("LINE", "Was not like madness. There's something in his soul,"), new XElement("LINE", "O'er which his melancholy sits on brood;"), new XElement("LINE", "And I do doubt the hatch and the disclose"), new XElement("LINE", "Will be some danger: which for to prevent,"), new XElement("LINE", "I have in quick determination"), new XElement("LINE", "Thus set it down: he shall with speed to England,"), new XElement("LINE", "For the demand of our neglected tribute"), new XElement("LINE", "Haply the seas and countries different"), new XElement("LINE", "With variable objects shall expel"), new XElement("LINE", "This something-settled matter in his heart,"), new XElement("LINE", "Whereon his brains still beating puts him thus"), new XElement("LINE", "From fashion of himself. What think you on't?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "It shall do well: but yet do I believe"), new XElement("LINE", "The origin and commencement of his grief"), new XElement("LINE", "Sprung from neglected love. How now, Ophelia!"), new XElement("LINE", "You need not tell us what Lord Hamlet said;"), new XElement("LINE", "We heard it all. My lord, do as you please;"), new XElement("LINE", "But, if you hold it fit, after the play"), new XElement("LINE", "Let his queen mother all alone entreat him"), new XElement("LINE", "To show his grief: let her be round with him;"), new XElement("LINE", "And I'll be placed, so please you, in the ear"), new XElement("LINE", "Of all their conference. If she find him not,"), new XElement("LINE", "To England send him, or confine him where"), new XElement("LINE", "Your wisdom best shall think.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "It shall be so:"), new XElement("LINE", "Madness in great ones must not unwatch'd go.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE II. A hall in the castle."), new XElement("STAGEDIR", "Enter HAMLET and Players"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Speak the speech, I pray you, as I pronounced it to"), new XElement("LINE", "you, trippingly on the tongue: but if you mouth it,"), new XElement("LINE", "as many of your players do, I had as lief the"), new XElement("LINE", "town-crier spoke my lines. Nor do not saw the air"), new XElement("LINE", "too much with your hand, thus, but use all gently;"), new XElement("LINE", "for in the very torrent, tempest, and, as I may say,"), new XElement("LINE", "the whirlwind of passion, you must acquire and beget"), new XElement("LINE", "a temperance that may give it smoothness. O, it"), new XElement("LINE", "offends me to the soul to hear a robustious"), new XElement("LINE", "periwig-pated fellow tear a passion to tatters, to"), new XElement("LINE", "very rags, to split the ears of the groundlings, who"), new XElement("LINE", "for the most part are capable of nothing but"), new XElement("LINE", "inexplicable dumbshows and noise: I would have such"), new XElement("LINE", "a fellow whipped for o'erdoing Termagant; it"), new XElement("LINE", "out-herods Herod: pray you, avoid it.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "I warrant your honour.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Be not too tame neither, but let your own discretion"), new XElement("LINE", "be your tutor: suit the action to the word, the"), new XElement("LINE", "word to the action; with this special o'erstep not"), new XElement("LINE", "the modesty of nature: for any thing so overdone is"), new XElement("LINE", "from the purpose of playing, whose end, both at the"), new XElement("LINE", "first and now, was and is, to hold, as 'twere, the"), new XElement("LINE", "mirror up to nature; to show virtue her own feature,"), new XElement("LINE", "scorn her own image, and the very age and body of"), new XElement("LINE", "the time his form and pressure. Now this overdone,"), new XElement("LINE", "or come tardy off, though it make the unskilful"), new XElement("LINE", "laugh, cannot but make the judicious grieve; the"), new XElement("LINE", "censure of the which one must in your allowance"), new XElement("LINE", "o'erweigh a whole theatre of others. O, there be"), new XElement("LINE", "players that I have seen play, and heard others"), new XElement("LINE", "praise, and that highly, not to speak it profanely,"), new XElement("LINE", "that, neither having the accent of Christians nor"), new XElement("LINE", "the gait of Christian, pagan, nor man, have so"), new XElement("LINE", "strutted and bellowed that I have thought some of"), new XElement("LINE", "nature's journeymen had made men and not made them"), new XElement("LINE", "well, they imitated humanity so abominably.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Player"), new XElement("LINE", "I hope we have reformed that indifferently with us,"), new XElement("LINE", "sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, reform it altogether. And let those that play"), new XElement("LINE", "your clowns speak no more than is set down for them;"), new XElement("LINE", "for there be of them that will themselves laugh, to"), new XElement("LINE", "set on some quantity of barren spectators to laugh"), new XElement("LINE", "too; though, in the mean time, some necessary"), new XElement("LINE", "question of the play be then to be considered:"), new XElement("LINE", "that's villanous, and shows a most pitiful ambition"), new XElement("LINE", "in the fool that uses it. Go, make you ready."), new XElement("STAGEDIR", "Exeunt Players"), new XElement("STAGEDIR", "Enter POLONIUS, ROSENCRANTZ, and GUILDENSTERN"), new XElement("LINE", "How now, my lord! I will the king hear this piece of work?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "And the queen too, and that presently.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Bid the players make haste."), new XElement("STAGEDIR", "Exit POLONIUS"), new XElement("LINE", "Will you two help to hasten them?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "We will, my lord.") ), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What ho! Horatio!") ), new XElement("STAGEDIR", "Enter HORATIO"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Here, sweet lord, at your service.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Horatio, thou art e'en as just a man"), new XElement("LINE", "As e'er my conversation coped withal.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "O, my dear lord,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, do not think I flatter;"), new XElement("LINE", "For what advancement may I hope from thee"), new XElement("LINE", "That no revenue hast but thy good spirits,"), new XElement("LINE", "To feed and clothe thee? Why should the poor be flatter'd?"), new XElement("LINE", "No, let the candied tongue lick absurd pomp,"), new XElement("LINE", "And crook the pregnant hinges of the knee"), new XElement("LINE", "Where thrift may follow fawning. Dost thou hear?"), new XElement("LINE", "Since my dear soul was mistress of her choice"), new XElement("LINE", "And could of men distinguish, her election"), new XElement("LINE", "Hath seal'd thee for herself; for thou hast been"), new XElement("LINE", "As one, in suffering all, that suffers nothing,"), new XElement("LINE", "A man that fortune's buffets and rewards"), new XElement("LINE", "Hast ta'en with equal thanks: and blest are those"), new XElement("LINE", "Whose blood and judgment are so well commingled,"), new XElement("LINE", "That they are not a pipe for fortune's finger"), new XElement("LINE", "To sound what stop she please. Give me that man"), new XElement("LINE", "That is not passion's slave, and I will wear him"), new XElement("LINE", "In my heart's core, ay, in my heart of heart,"), new XElement("LINE", "As I do thee.--Something too much of this.--"), new XElement("LINE", "There is a play to-night before the king;"), new XElement("LINE", "One scene of it comes near the circumstance"), new XElement("LINE", "Which I have told thee of my father's death:"), new XElement("LINE", "I prithee, when thou seest that act afoot,"), new XElement("LINE", "Even with the very comment of thy soul"), new XElement("LINE", "Observe mine uncle: if his occulted guilt"), new XElement("LINE", "Do not itself unkennel in one speech,"), new XElement("LINE", "It is a damned ghost that we have seen,"), new XElement("LINE", "And my imaginations are as foul"), new XElement("LINE", "As Vulcan's stithy. Give him heedful note;"), new XElement("LINE", "For I mine eyes will rivet to his face,"), new XElement("LINE", "And after we will both our judgments join"), new XElement("LINE", "In censure of his seeming.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Well, my lord:"), new XElement("LINE", "If he steal aught the whilst this play is playing,"), new XElement("LINE", "And 'scape detecting, I will pay the theft.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "They are coming to the play; I must be idle:"), new XElement("LINE", "Get you a place.") ), new XElement("STAGEDIR", "Danish march. A flourish. Enter KING CLAUDIUS,\n" + "QUEEN GERTRUDE, POLONIUS, OPHELIA, ROSENCRANTZ,\n" + "GUILDENSTERN, and others" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "How fares our cousin Hamlet?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Excellent, i' faith; of the chameleon's dish: I eat"), new XElement("LINE", "the air, promise-crammed: you cannot feed capons so.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I have nothing with this answer, Hamlet; these words"), new XElement("LINE", "are not mine.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, nor mine now."), new XElement("STAGEDIR", "To POLONIUS"), new XElement("LINE", "My lord, you played once i' the university, you say?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "That did I, my lord; and was accounted a good actor.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What did you enact?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I did enact Julius Caesar: I was killed i' the"), new XElement("LINE", "Capitol; Brutus killed me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It was a brute part of him to kill so capital a calf"), new XElement("LINE", "there. Be the players ready?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Ay, my lord; they stay upon your patience.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Come hither, my dear Hamlet, sit by me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, good mother, here's metal more attractive.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "To KING CLAUDIUS"), " O, ho! do you mark that?" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Lady, shall I lie in your lap?") ), new XElement("STAGEDIR", "Lying down at OPHELIA's feet"), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "No, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I mean, my head upon your lap?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Ay, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do you think I meant country matters?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I think nothing, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That's a fair thought to lie between maids' legs.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "What is, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nothing.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "You are merry, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Who, I?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Ay, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O God, your only jig-maker. What should a man do"), new XElement("LINE", "but be merry? for, look you, how cheerfully my"), new XElement("LINE", "mother looks, and my father died within these two hours.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Nay, 'tis twice two months, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "So long? Nay then, let the devil wear black, for"), new XElement("LINE", "I'll have a suit of sables. O heavens! die two"), new XElement("LINE", "months ago, and not forgotten yet? Then there's"), new XElement("LINE", "hope a great man's memory may outlive his life half"), new XElement("LINE", "a year: but, by'r lady, he must build churches,"), new XElement("LINE", "then; or else shall he suffer not thinking on, with"), new XElement("LINE", "the hobby-horse, whose epitaph is 'For, O, for, O,"), new XElement("LINE", "the hobby-horse is forgot.'"), new XElement("STAGEDIR", "Hautboys play. The dumb-show enters") ), new XElement("STAGEDIR", "Enter a King and a Queen very lovingly; the Queen\n" + "embracing him, and he her. She kneels, and makes\n" + "show of protestation unto him. He takes her up,\n" + "and declines his head upon her neck: lays him down\n" + "upon a bank of flowers: she, seeing him asleep,\n" + "leaves him. Anon comes in a fellow, takes off his\n" + "crown, kisses it, and pours poison in the King's\n" + "ears, and exit. The Queen returns; finds the King\n" + "dead, and makes passionate action. The Poisoner,\n" + "with some two or three Mutes, comes in again,\n" + "seeming to lament with her. The dead body is\n" + "carried away. The Poisoner wooes the Queen with\n" + "gifts: she seems loath and unwilling awhile, but\n" + "in the end accepts his love" ), new XElement("STAGEDIR", "Exeunt"), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "What means this, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Marry, this is miching mallecho; it means mischief.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Belike this show imports the argument of the play.") ), new XElement("STAGEDIR", "Enter Prologue"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "We shall know by this fellow: the players cannot"), new XElement("LINE", "keep counsel; they'll tell all.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Will he tell us what this show meant?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, or any show that you'll show him: be not you"), new XElement("LINE", "ashamed to show, he'll not shame to tell you what it means.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "You are naught, you are naught: I'll mark the play.") ), new XElement("SPEECH", new XElement("SPEAKER", "Prologue"), new XElement("LINE", "For us, and for our tragedy,"), new XElement("LINE", "Here stooping to your clemency,"), new XElement("LINE", "We beg your hearing patiently.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Is this a prologue, or the posy of a ring?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "'Tis brief, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "As woman's love.") ), new XElement("STAGEDIR", "Enter two Players, King and Queen"), new XElement("SPEECH", new XElement("SPEAKER", "Player King"), new XElement("LINE", "Full thirty times hath Phoebus' cart gone round"), new XElement("LINE", "Neptune's salt wash and Tellus' orbed ground,"), new XElement("LINE", "And thirty dozen moons with borrow'd sheen"), new XElement("LINE", "About the world have times twelve thirties been,"), new XElement("LINE", "Since love our hearts and Hymen did our hands"), new XElement("LINE", "Unite commutual in most sacred bands.") ), new XElement("SPEECH", new XElement("SPEAKER", "Player Queen"), new XElement("LINE", "So many journeys may the sun and moon"), new XElement("LINE", "Make us again count o'er ere love be done!"), new XElement("LINE", "But, woe is me, you are so sick of late,"), new XElement("LINE", "So far from cheer and from your former state,"), new XElement("LINE", "That I distrust you. Yet, though I distrust,"), new XElement("LINE", "Discomfort you, my lord, it nothing must:"), new XElement("LINE", "For women's fear and love holds quantity;"), new XElement("LINE", "In neither aught, or in extremity."), new XElement("LINE", "Now, what my love is, proof hath made you know;"), new XElement("LINE", "And as my love is sized, my fear is so:"), new XElement("LINE", "Where love is great, the littlest doubts are fear;"), new XElement("LINE", "Where little fears grow great, great love grows there.") ), new XElement("SPEECH", new XElement("SPEAKER", "Player King"), new XElement("LINE", "'Faith, I must leave thee, love, and shortly too;"), new XElement("LINE", "My operant powers their functions leave to do:"), new XElement("LINE", "And thou shalt live in this fair world behind,"), new XElement("LINE", "Honour'd, beloved; and haply one as kind"), new XElement("LINE", "For husband shalt thou--") ), new XElement("SPEECH", new XElement("SPEAKER", "Player Queen"), new XElement("LINE", "O, confound the rest!"), new XElement("LINE", "Such love must needs be treason in my breast:"), new XElement("LINE", "In second husband let me be accurst!"), new XElement("LINE", "None wed the second but who kill'd the first.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " Wormwood, wormwood." ) ), new XElement("SPEECH", new XElement("SPEAKER", "Player Queen"), new XElement("LINE", "The instances that second marriage move"), new XElement("LINE", "Are base respects of thrift, but none of love:"), new XElement("LINE", "A second time I kill my husband dead,"), new XElement("LINE", "When second husband kisses me in bed.") ), new XElement("SPEECH", new XElement("SPEAKER", "Player King"), new XElement("LINE", "I do believe you think what now you speak;"), new XElement("LINE", "But what we do determine oft we break."), new XElement("LINE", "Purpose is but the slave to memory,"), new XElement("LINE", "Of violent birth, but poor validity;"), new XElement("LINE", "Which now, like fruit unripe, sticks on the tree;"), new XElement("LINE", "But fall, unshaken, when they mellow be."), new XElement("LINE", "Most necessary 'tis that we forget"), new XElement("LINE", "To pay ourselves what to ourselves is debt:"), new XElement("LINE", "What to ourselves in passion we propose,"), new XElement("LINE", "The passion ending, doth the purpose lose."), new XElement("LINE", "The violence of either grief or joy"), new XElement("LINE", "Their own enactures with themselves destroy:"), new XElement("LINE", "Where joy most revels, grief doth most lament;"), new XElement("LINE", "Grief joys, joy grieves, on slender accident."), new XElement("LINE", "This world is not for aye, nor 'tis not strange"), new XElement("LINE", "That even our loves should with our fortunes change;"), new XElement("LINE", "For 'tis a question left us yet to prove,"), new XElement("LINE", "Whether love lead fortune, or else fortune love."), new XElement("LINE", "The great man down, you mark his favourite flies;"), new XElement("LINE", "The poor advanced makes friends of enemies."), new XElement("LINE", "And hitherto doth love on fortune tend;"), new XElement("LINE", "For who not needs shall never lack a friend,"), new XElement("LINE", "And who in want a hollow friend doth try,"), new XElement("LINE", "Directly seasons him his enemy."), new XElement("LINE", "But, orderly to end where I begun,"), new XElement("LINE", "Our wills and fates do so contrary run"), new XElement("LINE", "That our devices still are overthrown;"), new XElement("LINE", "Our thoughts are ours, their ends none of our own:"), new XElement("LINE", "So think thou wilt no second husband wed;"), new XElement("LINE", "But die thy thoughts when thy first lord is dead.") ), new XElement("SPEECH", new XElement("SPEAKER", "Player Queen"), new XElement("LINE", "Nor earth to me give food, nor heaven light!"), new XElement("LINE", "Sport and repose lock from me day and night!"), new XElement("LINE", "To desperation turn my trust and hope!"), new XElement("LINE", "An anchor's cheer in prison be my scope!"), new XElement("LINE", "Each opposite that blanks the face of joy"), new XElement("LINE", "Meet what I would have well and it destroy!"), new XElement("LINE", "Both here and hence pursue me lasting strife,"), new XElement("LINE", "If, once a widow, ever I be wife!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "If she should break it now!") ), new XElement("SPEECH", new XElement("SPEAKER", "Player King"), new XElement("LINE", "'Tis deeply sworn. Sweet, leave me here awhile;"), new XElement("LINE", "My spirits grow dull, and fain I would beguile"), new XElement("LINE", "The tedious day with sleep.") ), new XElement("STAGEDIR", "Sleeps"), new XElement("SPEECH", new XElement("SPEAKER", "Player Queen"), new XElement("LINE", "Sleep rock thy brain,"), new XElement("LINE", "And never come mischance between us twain!") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Madam, how like you this play?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "The lady protests too much, methinks.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, but she'll keep her word.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Have you heard the argument? Is there no offence in 't?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, no, they do but jest, poison in jest; no offence"), new XElement("LINE", "i' the world.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "What do you call the play?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The Mouse-trap. Marry, how? Tropically. This play"), new XElement("LINE", "is the image of a murder done in Vienna: Gonzago is"), new XElement("LINE", "the duke's name; his wife, Baptista: you shall see"), new XElement("LINE", "anon; 'tis a knavish piece of work: but what o'"), new XElement("LINE", "that? your majesty and we that have free souls, it"), new XElement("LINE", "touches us not: let the galled jade wince, our"), new XElement("LINE", "withers are unwrung."), new XElement("STAGEDIR", "Enter LUCIANUS"), new XElement("LINE", "This is one Lucianus, nephew to the king.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "You are as good as a chorus, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I could interpret between you and your love, if I"), new XElement("LINE", "could see the puppets dallying.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "You are keen, my lord, you are keen.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It would cost you a groaning to take off my edge.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Still better, and worse.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "So you must take your husbands. Begin, murderer;"), new XElement("LINE", "pox, leave thy damnable faces, and begin. Come:"), new XElement("LINE", "'the croaking raven doth bellow for revenge.'") ), new XElement("SPEECH", new XElement("SPEAKER", "LUCIANUS"), new XElement("LINE", "Thoughts black, hands apt, drugs fit, and time agreeing;"), new XElement("LINE", "Confederate season, else no creature seeing;"), new XElement("LINE", "Thou mixture rank, of midnight weeds collected,"), new XElement("LINE", "With Hecate's ban thrice blasted, thrice infected,"), new XElement("LINE", "Thy natural magic and dire property,"), new XElement("LINE", "On wholesome life usurp immediately.") ), new XElement("STAGEDIR", "Pours the poison into the sleeper's ears"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "He poisons him i' the garden for's estate. His"), new XElement("LINE", "name's Gonzago: the story is extant, and writ in"), new XElement("LINE", "choice Italian: you shall see anon how the murderer"), new XElement("LINE", "gets the love of Gonzago's wife.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "The king rises.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What, frighted with false fire!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "How fares my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Give o'er the play.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Give me some light: away!") ), new XElement("SPEECH", new XElement("SPEAKER", "All"), new XElement("LINE", "Lights, lights, lights!") ), new XElement("STAGEDIR", "Exeunt all but HAMLET and HORATIO"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, let the stricken deer go weep,"), new XElement("LINE", "The hart ungalled play;"), new XElement("LINE", "For some must watch, while some must sleep:"), new XElement("LINE", "So runs the world away."), new XElement("LINE", "Would not this, sir, and a forest of feathers-- if"), new XElement("LINE", "the rest of my fortunes turn Turk with me--with two"), new XElement("LINE", "Provincial roses on my razed shoes, get me a"), new XElement("LINE", "fellowship in a cry of players, sir?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Half a share.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A whole one, I."), new XElement("LINE", "For thou dost know, O Damon dear,"), new XElement("LINE", "This realm dismantled was"), new XElement("LINE", "Of Jove himself; and now reigns here"), new XElement("LINE", "A very, very--pajock.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "You might have rhymed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O good Horatio, I'll take the ghost's word for a"), new XElement("LINE", "thousand pound. Didst perceive?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Very well, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Upon the talk of the poisoning?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I did very well note him.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ah, ha! Come, some music! come, the recorders!"), new XElement("LINE", "For if the king like not the comedy,"), new XElement("LINE", "Why then, belike, he likes it not, perdy."), new XElement("LINE", "Come, some music!") ), new XElement("STAGEDIR", "Re-enter ROSENCRANTZ and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Good my lord, vouchsafe me a word with you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, a whole history.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "The king, sir,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, sir, what of him?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Is in his retirement marvellous distempered.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "With drink, sir?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "No, my lord, rather with choler.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Your wisdom should show itself more richer to"), new XElement("LINE", "signify this to his doctor; for, for me to put him"), new XElement("LINE", "to his purgation would perhaps plunge him into far"), new XElement("LINE", "more choler.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Good my lord, put your discourse into some frame and"), new XElement("LINE", "start not so wildly from my affair.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am tame, sir: pronounce.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "The queen, your mother, in most great affliction of"), new XElement("LINE", "spirit, hath sent me to you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "You are welcome.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Nay, good my lord, this courtesy is not of the right"), new XElement("LINE", "breed. If it shall please you to make me a"), new XElement("LINE", "wholesome answer, I will do your mother's"), new XElement("LINE", "commandment: if not, your pardon and my return"), new XElement("LINE", "shall be the end of my business.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, I cannot.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "What, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Make you a wholesome answer; my wit's diseased: but,"), new XElement("LINE", "sir, such answer as I can make, you shall command;"), new XElement("LINE", "or, rather, as you say, my mother: therefore no"), new XElement("LINE", "more, but to the matter: my mother, you say,--") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Then thus she says; your behavior hath struck her"), new XElement("LINE", "into amazement and admiration.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O wonderful son, that can so astonish a mother! But"), new XElement("LINE", "is there no sequel at the heels of this mother's"), new XElement("LINE", "admiration? Impart.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "She desires to speak with you in her closet, ere you"), new XElement("LINE", "go to bed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "We shall obey, were she ten times our mother. Have"), new XElement("LINE", "you any further trade with us?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "My lord, you once did love me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "So I do still, by these pickers and stealers.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Good my lord, what is your cause of distemper? you"), new XElement("LINE", "do, surely, bar the door upon your own liberty, if"), new XElement("LINE", "you deny your griefs to your friend.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, I lack advancement.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "How can that be, when you have the voice of the king"), new XElement("LINE", "himself for your succession in Denmark?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, but sir, 'While the grass grows,'--the proverb"), new XElement("LINE", "is something musty."), new XElement("STAGEDIR", "Re-enter Players with recorders"), new XElement("LINE", "O, the recorders! let me see one. To withdraw with"), new XElement("LINE", "you:--why do you go about to recover the wind of me,"), new XElement("LINE", "as if you would drive me into a toil?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "O, my lord, if my duty be too bold, my love is too"), new XElement("LINE", "unmannerly.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I do not well understand that. Will you play upon"), new XElement("LINE", "this pipe?") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "My lord, I cannot.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I pray you.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "Believe me, I cannot.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I do beseech you.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "I know no touch of it, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Tis as easy as lying: govern these ventages with"), new XElement("LINE", "your lingers and thumb, give it breath with your"), new XElement("LINE", "mouth, and it will discourse most eloquent music."), new XElement("LINE", "Look you, these are the stops.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "But these cannot I command to any utterance of"), new XElement("LINE", "harmony; I have not the skill.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, look you now, how unworthy a thing you make of"), new XElement("LINE", "me! You would play upon me; you would seem to know"), new XElement("LINE", "my stops; you would pluck out the heart of my"), new XElement("LINE", "mystery; you would sound me from my lowest note to"), new XElement("LINE", "the top of my compass: and there is much music,"), new XElement("LINE", "excellent voice, in this little organ; yet cannot"), new XElement("LINE", "you make it speak. 'Sblood, do you think I am"), new XElement("LINE", "easier to be played on than a pipe? Call me what"), new XElement("LINE", "instrument you will, though you can fret me, yet you"), new XElement("LINE", "cannot play upon me."), new XElement("STAGEDIR", "Enter POLONIUS"), new XElement("LINE", "God bless you, sir!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "My lord, the queen would speak with you, and"), new XElement("LINE", "presently.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do you see yonder cloud that's almost in shape of a camel?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "By the mass, and 'tis like a camel, indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Methinks it is like a weasel.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "It is backed like a weasel.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Or like a whale?") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "Very like a whale.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Then I will come to my mother by and by. They fool"), new XElement("LINE", "me to the top of my bent. I will come by and by.") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "I will say so.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "By and by is easily said."), new XElement("STAGEDIR", "Exit POLONIUS"), new XElement("LINE", "Leave me, friends."), new XElement("STAGEDIR", "Exeunt all but HAMLET"), new XElement("LINE", "Tis now the very witching time of night,"), new XElement("LINE", "When churchyards yawn and hell itself breathes out"), new XElement("LINE", "Contagion to this world: now could I drink hot blood,"), new XElement("LINE", "And do such bitter business as the day"), new XElement("LINE", "Would quake to look on. Soft! now to my mother."), new XElement("LINE", "O heart, lose not thy nature; let not ever"), new XElement("LINE", "The soul of Nero enter this firm bosom:"), new XElement("LINE", "Let me be cruel, not unnatural:"), new XElement("LINE", "I will speak daggers to her, but use none;"), new XElement("LINE", "My tongue and soul in this be hypocrites;"), new XElement("LINE", "How in my words soever she be shent,"), new XElement("LINE", "To give them seals never, my soul, consent!") ), new XElement("STAGEDIR", "Exit") ), new XElement("SCENE", new XElement("TITLE", "SCENE III. A room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, ROSENCRANTZ, and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I like him not, nor stands it safe with us"), new XElement("LINE", "To let his madness range. Therefore prepare you;"), new XElement("LINE", "I your commission will forthwith dispatch,"), new XElement("LINE", "And he to England shall along with you:"), new XElement("LINE", "The terms of our estate may not endure"), new XElement("LINE", "Hazard so dangerous as doth hourly grow"), new XElement("LINE", "Out of his lunacies.") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "We will ourselves provide:"), new XElement("LINE", "Most holy and religious fear it is"), new XElement("LINE", "To keep those many many bodies safe"), new XElement("LINE", "That live and feed upon your majesty.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "The single and peculiar life is bound,"), new XElement("LINE", "With all the strength and armour of the mind,"), new XElement("LINE", "To keep itself from noyance; but much more"), new XElement("LINE", "That spirit upon whose weal depend and rest"), new XElement("LINE", "The lives of many. The cease of majesty"), new XElement("LINE", "Dies not alone; but, like a gulf, doth draw"), new XElement("LINE", "What's near it with it: it is a massy wheel,"), new XElement("LINE", "Fix'd on the summit of the highest mount,"), new XElement("LINE", "To whose huge spokes ten thousand lesser things"), new XElement("LINE", "Are mortised and adjoin'd; which, when it falls,"), new XElement("LINE", "Each small annexment, petty consequence,"), new XElement("LINE", "Attends the boisterous ruin. Never alone"), new XElement("LINE", "Did the king sigh, but with a general groan.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Arm you, I pray you, to this speedy voyage;"), new XElement("LINE", "For we will fetters put upon this fear,"), new XElement("LINE", "Which now goes too free-footed.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "We will haste us.") ), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("STAGEDIR", "Enter POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "My lord, he's going to his mother's closet:"), new XElement("LINE", "Behind the arras I'll convey myself,"), new XElement("LINE", "To hear the process; and warrant she'll tax him home:"), new XElement("LINE", "And, as you said, and wisely was it said,"), new XElement("LINE", "'Tis meet that some more audience than a mother,"), new XElement("LINE", "Since nature makes them partial, should o'erhear"), new XElement("LINE", "The speech, of vantage. Fare you well, my liege:"), new XElement("LINE", "I'll call upon you ere you go to bed,"), new XElement("LINE", "And tell you what I know.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Thanks, dear my lord."), new XElement("STAGEDIR", "Exit POLONIUS"), new XElement("LINE", "O, my offence is rank it smells to heaven;"), new XElement("LINE", "It hath the primal eldest curse upon't,"), new XElement("LINE", "A brother's murder. Pray can I not,"), new XElement("LINE", "Though inclination be as sharp as will:"), new XElement("LINE", "My stronger guilt defeats my strong intent;"), new XElement("LINE", "And, like a man to double business bound,"), new XElement("LINE", "I stand in pause where I shall first begin,"), new XElement("LINE", "And both neglect. What if this cursed hand"), new XElement("LINE", "Were thicker than itself with brother's blood,"), new XElement("LINE", "Is there not rain enough in the sweet heavens"), new XElement("LINE", "To wash it white as snow? Whereto serves mercy"), new XElement("LINE", "But to confront the visage of offence?"), new XElement("LINE", "And what's in prayer but this two-fold force,"), new XElement("LINE", "To be forestalled ere we come to fall,"), new XElement("LINE", "Or pardon'd being down? Then I'll look up;"), new XElement("LINE", "My fault is past. But, O, what form of prayer"), new XElement("LINE", "Can serve my turn? 'Forgive me my foul murder'?"), new XElement("LINE", "That cannot be; since I am still possess'd"), new XElement("LINE", "Of those effects for which I did the murder,"), new XElement("LINE", "My crown, mine own ambition and my queen."), new XElement("LINE", "May one be pardon'd and retain the offence?"), new XElement("LINE", "In the corrupted currents of this world"), new XElement("LINE", "Offence's gilded hand may shove by justice,"), new XElement("LINE", "And oft 'tis seen the wicked prize itself"), new XElement("LINE", "Buys out the law: but 'tis not so above;"), new XElement("LINE", "There is no shuffling, there the action lies"), new XElement("LINE", "In his true nature; and we ourselves compell'd,"), new XElement("LINE", "Even to the teeth and forehead of our faults,"), new XElement("LINE", "To give in evidence. What then? what rests?"), new XElement("LINE", "Try what repentance can: what can it not?"), new XElement("LINE", "Yet what can it when one can not repent?"), new XElement("LINE", "O wretched state! O bosom black as death!"), new XElement("LINE", "O limed soul, that, struggling to be free,"), new XElement("LINE", "Art more engaged! Help, angels! Make assay!"), new XElement("LINE", "Bow, stubborn knees; and, heart with strings of steel,"), new XElement("LINE", "Be soft as sinews of the newborn babe!"), new XElement("LINE", "All may be well.") ), new XElement("STAGEDIR", "Retires and kneels"), new XElement("STAGEDIR", "Enter HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Now might I do it pat, now he is praying;"), new XElement("LINE", "And now I'll do't. And so he goes to heaven;"), new XElement("LINE", "And so am I revenged. That would be scann'd:"), new XElement("LINE", "A villain kills my father; and for that,"), new XElement("LINE", "I, his sole son, do this same villain send"), new XElement("LINE", "To heaven."), new XElement("LINE", "O, this is hire and salary, not revenge."), new XElement("LINE", "He took my father grossly, full of bread;"), new XElement("LINE", "With all his crimes broad blown, as flush as May;"), new XElement("LINE", "And how his audit stands who knows save heaven?"), new XElement("LINE", "But in our circumstance and course of thought,"), new XElement("LINE", "'Tis heavy with him: and am I then revenged,"), new XElement("LINE", "To take him in the purging of his soul,"), new XElement("LINE", "When he is fit and season'd for his passage?"), new XElement("LINE", "No!"), new XElement("LINE", "Up, sword; and know thou a more horrid hent:"), new XElement("LINE", "When he is drunk asleep, or in his rage,"), new XElement("LINE", "Or in the incestuous pleasure of his bed;"), new XElement("LINE", "At gaming, swearing, or about some act"), new XElement("LINE", "That has no relish of salvation in't;"), new XElement("LINE", "Then trip him, that his heels may kick at heaven,"), new XElement("LINE", "And that his soul may be as damn'd and black"), new XElement("LINE", "As hell, whereto it goes. My mother stays:"), new XElement("LINE", "This physic but prolongs thy sickly days.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", new XElement("STAGEDIR", "Rising"), " My words fly up, my thoughts remain below:" ), new XElement("LINE", "Words without thoughts never to heaven go.") ), new XElement("STAGEDIR", "Exit") ), new XElement("SCENE", new XElement("TITLE", "SCENE IV. The Queen's closet."), new XElement("STAGEDIR", "Enter QUEEN MARGARET and POLONIUS"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", "He will come straight. Look you lay home to him:"), new XElement("LINE", "Tell him his pranks have been too broad to bear with,"), new XElement("LINE", "And that your grace hath screen'd and stood between"), new XElement("LINE", "Much heat and him. I'll sconce me even here."), new XElement("LINE", "Pray you, be round with him.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Mother, mother, mother!" ) ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "I'll warrant you,"), new XElement("LINE", "Fear me not: withdraw, I hear him coming.") ), new XElement("STAGEDIR", "POLONIUS hides behind the arras"), new XElement("STAGEDIR", "Enter HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Now, mother, what's the matter?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Hamlet, thou hast thy father much offended.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Mother, you have my father much offended.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Come, come, you answer with an idle tongue.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Go, go, you question with a wicked tongue.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Why, how now, Hamlet!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What's the matter now?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Have you forgot me?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, by the rood, not so:"), new XElement("LINE", "You are the queen, your husband's brother's wife;"), new XElement("LINE", "And--would it were not so!--you are my mother.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Nay, then, I'll set those to you that can speak.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Come, come, and sit you down; you shall not budge;"), new XElement("LINE", "You go not till I set you up a glass"), new XElement("LINE", "Where you may see the inmost part of you.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "What wilt thou do? thou wilt not murder me?"), new XElement("LINE", "Help, help, ho!") ), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Behind"), " What, ho! help, help, help!" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Drawing"), " How now! a rat? Dead, for a ducat, dead!" ) ), new XElement("STAGEDIR", "Makes a pass through the arras"), new XElement("SPEECH", new XElement("SPEAKER", "LORD POLONIUS"), new XElement("LINE", new XElement("STAGEDIR", "Behind"), " O, I am slain!" ) ), new XElement("STAGEDIR", "Falls and dies"), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O me, what hast thou done?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, I know not:"), new XElement("LINE", "Is it the king?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O, what a rash and bloody deed is this!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A bloody deed! almost as bad, good mother,"), new XElement("LINE", "As kill a king, and marry with his brother.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "As kill a king!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, lady, 'twas my word."), new XElement("STAGEDIR", "Lifts up the array and discovers POLONIUS"), new XElement("LINE", "Thou wretched, rash, intruding fool, farewell!"), new XElement("LINE", "I took thee for thy better: take thy fortune;"), new XElement("LINE", "Thou find'st to be too busy is some danger."), new XElement("LINE", "Leave wringing of your hands: peace! sit you down,"), new XElement("LINE", "And let me wring your heart; for so I shall,"), new XElement("LINE", "If it be made of penetrable stuff,"), new XElement("LINE", "If damned custom have not brass'd it so"), new XElement("LINE", "That it is proof and bulwark against sense.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "What have I done, that thou darest wag thy tongue"), new XElement("LINE", "In noise so rude against me?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Such an act"), new XElement("LINE", "That blurs the grace and blush of modesty,"), new XElement("LINE", "Calls virtue hypocrite, takes off the rose"), new XElement("LINE", "From the fair forehead of an innocent love"), new XElement("LINE", "And sets a blister there, makes marriage-vows"), new XElement("LINE", "As false as dicers' oaths: O, such a deed"), new XElement("LINE", "As from the body of contraction plucks"), new XElement("LINE", "The very soul, and sweet religion makes"), new XElement("LINE", "A rhapsody of words: heaven's face doth glow:"), new XElement("LINE", "Yea, this solidity and compound mass,"), new XElement("LINE", "With tristful visage, as against the doom,"), new XElement("LINE", "Is thought-sick at the act.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Ay me, what act,"), new XElement("LINE", "That roars so loud, and thunders in the index?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Look here, upon this picture, and on this,"), new XElement("LINE", "The counterfeit presentment of two brothers."), new XElement("LINE", "See, what a grace was seated on this brow;"), new XElement("LINE", "Hyperion's curls; the front of Jove himself;"), new XElement("LINE", "An eye like Mars, to threaten and command;"), new XElement("LINE", "A station like the herald Mercury"), new XElement("LINE", "New-lighted on a heaven-kissing hill;"), new XElement("LINE", "A combination and a form indeed,"), new XElement("LINE", "Where every god did seem to set his seal,"), new XElement("LINE", "To give the world assurance of a man:"), new XElement("LINE", "This was your husband. Look you now, what follows:"), new XElement("LINE", "Here is your husband; like a mildew'd ear,"), new XElement("LINE", "Blasting his wholesome brother. Have you eyes?"), new XElement("LINE", "Could you on this fair mountain leave to feed,"), new XElement("LINE", "And batten on this moor? Ha! have you eyes?"), new XElement("LINE", "You cannot call it love; for at your age"), new XElement("LINE", "The hey-day in the blood is tame, it's humble,"), new XElement("LINE", "And waits upon the judgment: and what judgment"), new XElement("LINE", "Would step from this to this? Sense, sure, you have,"), new XElement("LINE", "Else could you not have motion; but sure, that sense"), new XElement("LINE", "Is apoplex'd; for madness would not err,"), new XElement("LINE", "Nor sense to ecstasy was ne'er so thrall'd"), new XElement("LINE", "But it reserved some quantity of choice,"), new XElement("LINE", "To serve in such a difference. What devil was't"), new XElement("LINE", "That thus hath cozen'd you at hoodman-blind?"), new XElement("LINE", "Eyes without feeling, feeling without sight,"), new XElement("LINE", "Ears without hands or eyes, smelling sans all,"), new XElement("LINE", "Or but a sickly part of one true sense"), new XElement("LINE", "Could not so mope."), new XElement("LINE", "O shame! where is thy blush? Rebellious hell,"), new XElement("LINE", "If thou canst mutine in a matron's bones,"), new XElement("LINE", "To flaming youth let virtue be as wax,"), new XElement("LINE", "And melt in her own fire: proclaim no shame"), new XElement("LINE", "When the compulsive ardour gives the charge,"), new XElement("LINE", "Since frost itself as actively doth burn"), new XElement("LINE", "And reason panders will.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O Hamlet, speak no more:"), new XElement("LINE", "Thou turn'st mine eyes into my very soul;"), new XElement("LINE", "And there I see such black and grained spots"), new XElement("LINE", "As will not leave their tinct.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, but to live"), new XElement("LINE", "In the rank sweat of an enseamed bed,"), new XElement("LINE", "Stew'd in corruption, honeying and making love"), new XElement("LINE", "Over the nasty sty,--") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O, speak to me no more;"), new XElement("LINE", "These words, like daggers, enter in mine ears;"), new XElement("LINE", "No more, sweet Hamlet!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A murderer and a villain;"), new XElement("LINE", "A slave that is not twentieth part the tithe"), new XElement("LINE", "Of your precedent lord; a vice of kings;"), new XElement("LINE", "A cutpurse of the empire and the rule,"), new XElement("LINE", "That from a shelf the precious diadem stole,"), new XElement("LINE", "And put it in his pocket!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "No more!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A king of shreds and patches,--"), new XElement("STAGEDIR", "Enter Ghost"), new XElement("LINE", "Save me, and hover o'er me with your wings,"), new XElement("LINE", "You heavenly guards! What would your gracious figure?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alas, he's mad!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do you not come your tardy son to chide,"), new XElement("LINE", "That, lapsed in time and passion, lets go by"), new XElement("LINE", "The important acting of your dread command? O, say!") ), new XElement("SPEECH", new XElement("SPEAKER", "Ghost"), new XElement("LINE", "Do not forget: this visitation"), new XElement("LINE", "Is but to whet thy almost blunted purpose."), new XElement("LINE", "But, look, amazement on thy mother sits:"), new XElement("LINE", "O, step between her and her fighting soul:"), new XElement("LINE", "Conceit in weakest bodies strongest works:"), new XElement("LINE", "Speak to her, Hamlet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How is it with you, lady?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alas, how is't with you,"), new XElement("LINE", "That you do bend your eye on vacancy"), new XElement("LINE", "And with the incorporal air do hold discourse?"), new XElement("LINE", "Forth at your eyes your spirits wildly peep;"), new XElement("LINE", "And, as the sleeping soldiers in the alarm,"), new XElement("LINE", "Your bedded hair, like life in excrements,"), new XElement("LINE", "Starts up, and stands on end. O gentle son,"), new XElement("LINE", "Upon the heat and flame of thy distemper"), new XElement("LINE", "Sprinkle cool patience. Whereon do you look?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "On him, on him! Look you, how pale he glares!"), new XElement("LINE", "His form and cause conjoin'd, preaching to stones,"), new XElement("LINE", "Would make them capable. Do not look upon me;"), new XElement("LINE", "Lest with this piteous action you convert"), new XElement("LINE", "My stern effects: then what I have to do"), new XElement("LINE", "Will want true colour; tears perchance for blood.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "To whom do you speak this?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do you see nothing there?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Nothing at all; yet all that is I see.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nor did you nothing hear?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "No, nothing but ourselves.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, look you there! look, how it steals away!"), new XElement("LINE", "My father, in his habit as he lived!"), new XElement("LINE", "Look, where he goes, even now, out at the portal!") ), new XElement("STAGEDIR", "Exit Ghost"), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "This the very coinage of your brain:"), new XElement("LINE", "This bodiless creation ecstasy"), new XElement("LINE", "Is very cunning in.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ecstasy!"), new XElement("LINE", "My pulse, as yours, doth temperately keep time,"), new XElement("LINE", "And makes as healthful music: it is not madness"), new XElement("LINE", "That I have utter'd: bring me to the test,"), new XElement("LINE", "And I the matter will re-word; which madness"), new XElement("LINE", "Would gambol from. Mother, for love of grace,"), new XElement("LINE", "Lay not that mattering unction to your soul,"), new XElement("LINE", "That not your trespass, but my madness speaks:"), new XElement("LINE", "It will but skin and film the ulcerous place,"), new XElement("LINE", "Whilst rank corruption, mining all within,"), new XElement("LINE", "Infects unseen. Confess yourself to heaven;"), new XElement("LINE", "Repent what's past; avoid what is to come;"), new XElement("LINE", "And do not spread the compost on the weeds,"), new XElement("LINE", "To make them ranker. Forgive me this my virtue;"), new XElement("LINE", "For in the fatness of these pursy times"), new XElement("LINE", "Virtue itself of vice must pardon beg,"), new XElement("LINE", "Yea, curb and woo for leave to do him good.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O Hamlet, thou hast cleft my heart in twain.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, throw away the worser part of it,"), new XElement("LINE", "And live the purer with the other half."), new XElement("LINE", "Good night: but go not to mine uncle's bed;"), new XElement("LINE", "Assume a virtue, if you have it not."), new XElement("LINE", "That monster, custom, who all sense doth eat,"), new XElement("LINE", "Of habits devil, is angel yet in this,"), new XElement("LINE", "That to the use of actions fair and good"), new XElement("LINE", "He likewise gives a frock or livery,"), new XElement("LINE", "That aptly is put on. Refrain to-night,"), new XElement("LINE", "And that shall lend a kind of easiness"), new XElement("LINE", "To the next abstinence: the next more easy;"), new XElement("LINE", "For use almost can change the stamp of nature,"), new XElement("LINE", "And either ... the devil, or throw him out"), new XElement("LINE", "With wondrous potency. Once more, good night:"), new XElement("LINE", "And when you are desirous to be bless'd,"), new XElement("LINE", "I'll blessing beg of you. For this same lord,"), new XElement("STAGEDIR", "Pointing to POLONIUS"), new XElement("LINE", "I do repent: but heaven hath pleased it so,"), new XElement("LINE", "To punish me with this and this with me,"), new XElement("LINE", "That I must be their scourge and minister."), new XElement("LINE", "I will bestow him, and will answer well"), new XElement("LINE", "The death I gave him. So, again, good night."), new XElement("LINE", "I must be cruel, only to be kind:"), new XElement("LINE", "Thus bad begins and worse remains behind."), new XElement("LINE", "One word more, good lady.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "What shall I do?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Not this, by no means, that I bid you do:"), new XElement("LINE", "Let the bloat king tempt you again to bed;"), new XElement("LINE", "Pinch wanton on your cheek; call you his mouse;"), new XElement("LINE", "And let him, for a pair of reechy kisses,"), new XElement("LINE", "Or paddling in your neck with his damn'd fingers,"), new XElement("LINE", "Make you to ravel all this matter out,"), new XElement("LINE", "That I essentially am not in madness,"), new XElement("LINE", "But mad in craft. 'Twere good you let him know;"), new XElement("LINE", "For who, that's but a queen, fair, sober, wise,"), new XElement("LINE", "Would from a paddock, from a bat, a gib,"), new XElement("LINE", "Such dear concernings hide? who would do so?"), new XElement("LINE", "No, in despite of sense and secrecy,"), new XElement("LINE", "Unpeg the basket on the house's top."), new XElement("LINE", "Let the birds fly, and, like the famous ape,"), new XElement("LINE", "To try conclusions, in the basket creep,"), new XElement("LINE", "And break your own neck down.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Be thou assured, if words be made of breath,"), new XElement("LINE", "And breath of life, I have no life to breathe"), new XElement("LINE", "What thou hast said to me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I must to England; you know that?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alack,"), new XElement("LINE", "I had forgot: 'tis so concluded on.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "There's letters seal'd: and my two schoolfellows,"), new XElement("LINE", "Whom I will trust as I will adders fang'd,"), new XElement("LINE", "They bear the mandate; they must sweep my way,"), new XElement("LINE", "And marshal me to knavery. Let it work;"), new XElement("LINE", "For 'tis the sport to have the engineer"), new XElement("LINE", "Hoist with his own petard: and 't shall go hard"), new XElement("LINE", "But I will delve one yard below their mines,"), new XElement("LINE", "And blow them at the moon: O, 'tis most sweet,"), new XElement("LINE", "When in one line two crafts directly meet."), new XElement("LINE", "This man shall set me packing:"), new XElement("LINE", "I'll lug the guts into the neighbour room."), new XElement("LINE", "Mother, good night. Indeed this counsellor"), new XElement("LINE", "Is now most still, most secret and most grave,"), new XElement("LINE", "Who was in life a foolish prating knave."), new XElement("LINE", "Come, sir, to draw toward an end with you."), new XElement("LINE", "Good night, mother.") ), new XElement("STAGEDIR", "Exeunt severally; HAMLET dragging in POLONIUS") ) ), new XElement("ACT", new XElement("TITLE", "ACT IV"), new XElement("SCENE", new XElement("TITLE", "SCENE I. A room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, QUEEN GERTRUDE, ROSENCRANTZ,\n" + "and GUILDENSTERN" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "There's matter in these sighs, these profound heaves:"), new XElement("LINE", "You must translate: 'tis fit we understand them."), new XElement("LINE", "Where is your son?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Bestow this place on us a little while."), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("LINE", "Ah, my good lord, what have I seen to-night!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "What, Gertrude? How does Hamlet?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Mad as the sea and wind, when both contend"), new XElement("LINE", "Which is the mightier: in his lawless fit,"), new XElement("LINE", "Behind the arras hearing something stir,"), new XElement("LINE", "Whips out his rapier, cries, 'A rat, a rat!'"), new XElement("LINE", "And, in this brainish apprehension, kills"), new XElement("LINE", "The unseen good old man.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O heavy deed!"), new XElement("LINE", "It had been so with us, had we been there:"), new XElement("LINE", "His liberty is full of threats to all;"), new XElement("LINE", "To you yourself, to us, to every one."), new XElement("LINE", "Alas, how shall this bloody deed be answer'd?"), new XElement("LINE", "It will be laid to us, whose providence"), new XElement("LINE", "Should have kept short, restrain'd and out of haunt,"), new XElement("LINE", "This mad young man: but so much was our love,"), new XElement("LINE", "We would not understand what was most fit;"), new XElement("LINE", "But, like the owner of a foul disease,"), new XElement("LINE", "To keep it from divulging, let it feed"), new XElement("LINE", "Even on the pith of Life. Where is he gone?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "To draw apart the body he hath kill'd:"), new XElement("LINE", "O'er whom his very madness, like some ore"), new XElement("LINE", "Among a mineral of metals base,"), new XElement("LINE", "Shows itself pure; he weeps for what is done.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O Gertrude, come away!"), new XElement("LINE", "The sun no sooner shall the mountains touch,"), new XElement("LINE", "But we will ship him hence: and this vile deed"), new XElement("LINE", "We must, with all our majesty and skill,"), new XElement("LINE", "Both countenance and excuse. Ho, Guildenstern!"), new XElement("STAGEDIR", "Re-enter ROSENCRANTZ and GUILDENSTERN"), new XElement("LINE", "Friends both, go join you with some further aid:"), new XElement("LINE", "Hamlet in madness hath Polonius slain,"), new XElement("LINE", "And from his mother's closet hath he dragg'd him:"), new XElement("LINE", "Go seek him out; speak fair, and bring the body"), new XElement("LINE", "Into the chapel. I pray you, haste in this."), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("LINE", "Come, Gertrude, we'll call up our wisest friends;"), new XElement("LINE", "And let them know, both what we mean to do,"), new XElement("LINE", "And what's untimely done..."), new XElement("LINE", "Whose whisper o'er the world's diameter,"), new XElement("LINE", "As level as the cannon to his blank,"), new XElement("LINE", "Transports his poison'd shot, may miss our name,"), new XElement("LINE", "And hit the woundless air. O, come away!"), new XElement("LINE", "My soul is full of discord and dismay.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE II. Another room in the castle."), new XElement("STAGEDIR", "Enter HAMLET"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Safely stowed.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Hamlet! Lord Hamlet!" ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What noise? who calls on Hamlet?"), new XElement("LINE", "O, here they come.") ), new XElement("STAGEDIR", "Enter ROSENCRANTZ and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "What have you done, my lord, with the dead body?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Compounded it with dust, whereto 'tis kin.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Tell us where 'tis, that we may take it thence"), new XElement("LINE", "And bear it to the chapel.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Do not believe it.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Believe what?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That I can keep your counsel and not mine own."), new XElement("LINE", "Besides, to be demanded of a sponge! what"), new XElement("LINE", "replication should be made by the son of a king?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Take you me for a sponge, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, sir, that soaks up the king's countenance, his"), new XElement("LINE", "rewards, his authorities. But such officers do the"), new XElement("LINE", "king best service in the end: he keeps them, like"), new XElement("LINE", "an ape, in the corner of his jaw; first mouthed, to"), new XElement("LINE", "be last swallowed: when he needs what you have"), new XElement("LINE", "gleaned, it is but squeezing you, and, sponge, you"), new XElement("LINE", "shall be dry again.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "I understand you not, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am glad of it: a knavish speech sleeps in a"), new XElement("LINE", "foolish ear.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "My lord, you must tell us where the body is, and go"), new XElement("LINE", "with us to the king.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The body is with the king, but the king is not with"), new XElement("LINE", "the body. The king is a thing--") ), new XElement("SPEECH", new XElement("SPEAKER", "GUILDENSTERN"), new XElement("LINE", "A thing, my lord!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Of nothing: bring me to him. Hide fox, and all after.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE III. Another room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS, attended"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I have sent to seek him, and to find the body."), new XElement("LINE", "How dangerous is it that this man goes loose!"), new XElement("LINE", "Yet must not we put the strong law on him:"), new XElement("LINE", "He's loved of the distracted multitude,"), new XElement("LINE", "Who like not in their judgment, but their eyes;"), new XElement("LINE", "And where tis so, the offender's scourge is weigh'd,"), new XElement("LINE", "But never the offence. To bear all smooth and even,"), new XElement("LINE", "This sudden sending him away must seem"), new XElement("LINE", "Deliberate pause: diseases desperate grown"), new XElement("LINE", "By desperate appliance are relieved,"), new XElement("LINE", "Or not at all."), new XElement("STAGEDIR", "Enter ROSENCRANTZ"), new XElement("LINE", "How now! what hath befall'n?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Where the dead body is bestow'd, my lord,"), new XElement("LINE", "We cannot get from him.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "But where is he?") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Without, my lord; guarded, to know your pleasure.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Bring him before us.") ), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Ho, Guildenstern! bring in my lord.") ), new XElement("STAGEDIR", "Enter HAMLET and GUILDENSTERN"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Now, Hamlet, where's Polonius?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "At supper.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "At supper! where?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Not where he eats, but where he is eaten: a certain"), new XElement("LINE", "convocation of politic worms are e'en at him. Your"), new XElement("LINE", "worm is your only emperor for diet: we fat all"), new XElement("LINE", "creatures else to fat us, and we fat ourselves for"), new XElement("LINE", "maggots: your fat king and your lean beggar is but"), new XElement("LINE", "variable service, two dishes, but to one table:"), new XElement("LINE", "that's the end.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Alas, alas!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "A man may fish with the worm that hath eat of a"), new XElement("LINE", "king, and cat of the fish that hath fed of that worm.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "What dost you mean by this?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nothing but to show you how a king may go a"), new XElement("LINE", "progress through the guts of a beggar.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Where is Polonius?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "In heaven; send hither to see: if your messenger"), new XElement("LINE", "find him not there, seek him i' the other place"), new XElement("LINE", "yourself. But indeed, if you find him not within"), new XElement("LINE", "this month, you shall nose him as you go up the"), new XElement("LINE", "stairs into the lobby.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Go seek him there.") ), new XElement("STAGEDIR", "To some Attendants"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "He will stay till ye come.") ), new XElement("STAGEDIR", "Exeunt Attendants"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Hamlet, this deed, for thine especial safety,--"), new XElement("LINE", "Which we do tender, as we dearly grieve"), new XElement("LINE", "For that which thou hast done,--must send thee hence"), new XElement("LINE", "With fiery quickness: therefore prepare thyself;"), new XElement("LINE", "The bark is ready, and the wind at help,"), new XElement("LINE", "The associates tend, and every thing is bent"), new XElement("LINE", "For England.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "For England!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Ay, Hamlet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Good.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "So is it, if thou knew'st our purposes.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I see a cherub that sees them. But, come; for"), new XElement("LINE", "England! Farewell, dear mother.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Thy loving father, Hamlet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "My mother: father and mother is man and wife; man"), new XElement("LINE", "and wife is one flesh; and so, my mother. Come, for England!") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Follow him at foot; tempt him with speed aboard;"), new XElement("LINE", "Delay it not; I'll have him hence to-night:"), new XElement("LINE", "Away! for every thing is seal'd and done"), new XElement("LINE", "That else leans on the affair: pray you, make haste."), new XElement("STAGEDIR", "Exeunt ROSENCRANTZ and GUILDENSTERN"), new XElement("LINE", "And, England, if my love thou hold'st at aught--"), new XElement("LINE", "As my great power thereof may give thee sense,"), new XElement("LINE", "Since yet thy cicatrice looks raw and red"), new XElement("LINE", "After the Danish sword, and thy free awe"), new XElement("LINE", "Pays homage to us--thou mayst not coldly set"), new XElement("LINE", "Our sovereign process; which imports at full,"), new XElement("LINE", "By letters congruing to that effect,"), new XElement("LINE", "The present death of Hamlet. Do it, England;"), new XElement("LINE", "For like the hectic in my blood he rages,"), new XElement("LINE", "And thou must cure me: till I know 'tis done,"), new XElement("LINE", "Howe'er my haps, my joys were ne'er begun.") ), new XElement("STAGEDIR", "Exit") ), new XElement("SCENE", new XElement("TITLE", "SCENE IV. A plain in Denmark."), new XElement("STAGEDIR", "Enter FORTINBRAS, a Captain, and Soldiers, marching"), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "Go, captain, from me greet the Danish king;"), new XElement("LINE", "Tell him that, by his licence, Fortinbras"), new XElement("LINE", "Craves the conveyance of a promised march"), new XElement("LINE", "Over his kingdom. You know the rendezvous."), new XElement("LINE", "If that his majesty would aught with us,"), new XElement("LINE", "We shall express our duty in his eye;"), new XElement("LINE", "And let him know so.") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "I will do't, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "Go softly on.") ), new XElement("STAGEDIR", "Exeunt FORTINBRAS and Soldiers"), new XElement("STAGEDIR", "Enter HAMLET, ROSENCRANTZ, GUILDENSTERN, and others"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Good sir, whose powers are these?") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "They are of Norway, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How purposed, sir, I pray you?") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "Against some part of Poland.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Who commands them, sir?") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "The nephews to old Norway, Fortinbras.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Goes it against the main of Poland, sir,"), new XElement("LINE", "Or for some frontier?") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "Truly to speak, and with no addition,"), new XElement("LINE", "We go to gain a little patch of ground"), new XElement("LINE", "That hath in it no profit but the name."), new XElement("LINE", "To pay five ducats, five, I would not farm it;"), new XElement("LINE", "Nor will it yield to Norway or the Pole"), new XElement("LINE", "A ranker rate, should it be sold in fee.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, then the Polack never will defend it.") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "Yes, it is already garrison'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Two thousand souls and twenty thousand ducats"), new XElement("LINE", "Will not debate the question of this straw:"), new XElement("LINE", "This is the imposthume of much wealth and peace,"), new XElement("LINE", "That inward breaks, and shows no cause without"), new XElement("LINE", "Why the man dies. I humbly thank you, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "Captain"), new XElement("LINE", "God be wi' you, sir.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "ROSENCRANTZ"), new XElement("LINE", "Wilt please you go, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I'll be with you straight go a little before."), new XElement("STAGEDIR", "Exeunt all except HAMLET"), new XElement("LINE", "How all occasions do inform against me,"), new XElement("LINE", "And spur my dull revenge! What is a man,"), new XElement("LINE", "If his chief good and market of his time"), new XElement("LINE", "Be but to sleep and feed? a beast, no more."), new XElement("LINE", "Sure, he that made us with such large discourse,"), new XElement("LINE", "Looking before and after, gave us not"), new XElement("LINE", "That capability and god-like reason"), new XElement("LINE", "To fust in us unused. Now, whether it be"), new XElement("LINE", "Bestial oblivion, or some craven scruple"), new XElement("LINE", "Of thinking too precisely on the event,"), new XElement("LINE", "A thought which, quarter'd, hath but one part wisdom"), new XElement("LINE", "And ever three parts coward, I do not know"), new XElement("LINE", "Why yet I live to say 'This thing's to do;'"), new XElement("LINE", "Sith I have cause and will and strength and means"), new XElement("LINE", "To do't. Examples gross as earth exhort me:"), new XElement("LINE", "Witness this army of such mass and charge"), new XElement("LINE", "Led by a delicate and tender prince,"), new XElement("LINE", "Whose spirit with divine ambition puff'd"), new XElement("LINE", "Makes mouths at the invisible event,"), new XElement("LINE", "Exposing what is mortal and unsure"), new XElement("LINE", "To all that fortune, death and danger dare,"), new XElement("LINE", "Even for an egg-shell. Rightly to be great"), new XElement("LINE", "Is not to stir without great argument,"), new XElement("LINE", "But greatly to find quarrel in a straw"), new XElement("LINE", "When honour's at the stake. How stand I then,"), new XElement("LINE", "That have a father kill'd, a mother stain'd,"), new XElement("LINE", "Excitements of my reason and my blood,"), new XElement("LINE", "And let all sleep? while, to my shame, I see"), new XElement("LINE", "The imminent death of twenty thousand men,"), new XElement("LINE", "That, for a fantasy and trick of fame,"), new XElement("LINE", "Go to their graves like beds, fight for a plot"), new XElement("LINE", "Whereon the numbers cannot try the cause,"), new XElement("LINE", "Which is not tomb enough and continent"), new XElement("LINE", "To hide the slain? O, from this time forth,"), new XElement("LINE", "My thoughts be bloody, or be nothing worth!") ), new XElement("STAGEDIR", "Exit") ), new XElement("SCENE", new XElement("TITLE", "SCENE V. Elsinore. A room in the castle."), new XElement("STAGEDIR", "Enter QUEEN GERTRUDE, HORATIO, and a Gentleman"), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "I will not speak with her.") ), new XElement("SPEECH", new XElement("SPEAKER", "Gentleman"), new XElement("LINE", "She is importunate, indeed distract:"), new XElement("LINE", "Her mood will needs be pitied.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "What would she have?") ), new XElement("SPEECH", new XElement("SPEAKER", "Gentleman"), new XElement("LINE", "She speaks much of her father; says she hears"), new XElement("LINE", "There's tricks i' the world; and hems, and beats her heart;"), new XElement("LINE", "Spurns enviously at straws; speaks things in doubt,"), new XElement("LINE", "That carry but half sense: her speech is nothing,"), new XElement("LINE", "Yet the unshaped use of it doth move"), new XElement("LINE", "The hearers to collection; they aim at it,"), new XElement("LINE", "And botch the words up fit to their own thoughts;"), new XElement("LINE", "Which, as her winks, and nods, and gestures"), new XElement("LINE", "yield them,"), new XElement("LINE", "Indeed would make one think there might be thought,"), new XElement("LINE", "Though nothing sure, yet much unhappily.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "'Twere good she were spoken with; for she may strew"), new XElement("LINE", "Dangerous conjectures in ill-breeding minds.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Let her come in."), new XElement("STAGEDIR", "Exit HORATIO"), new XElement("LINE", "To my sick soul, as sin's true nature is,"), new XElement("LINE", "Each toy seems prologue to some great amiss:"), new XElement("LINE", "So full of artless jealousy is guilt,"), new XElement("LINE", "It spills itself in fearing to be spilt.") ), new XElement("STAGEDIR", "Re-enter HORATIO, with OPHELIA"), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Where is the beauteous majesty of Denmark?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "How now, Ophelia!") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "How should I your true love know"), new XElement("LINE", "From another one?"), new XElement("LINE", "By his cockle hat and staff,"), new XElement("LINE", "And his sandal shoon.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alas, sweet lady, what imports this song?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Say you? nay, pray you, mark."), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "He is dead and gone, lady,"), new XElement("LINE", "He is dead and gone;"), new XElement("LINE", "At his head a grass-green turf,"), new XElement("LINE", "At his heels a stone.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Nay, but, Ophelia,--") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Pray you, mark."), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "White his shroud as the mountain snow,--") ), new XElement("STAGEDIR", "Enter KING CLAUDIUS"), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alas, look here, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "Larded with sweet flowers"), new XElement("LINE", "Which bewept to the grave did go"), new XElement("LINE", "With true-love showers.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "How do you, pretty lady?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Well, God 'ild you! They say the owl was a baker's"), new XElement("LINE", "daughter. Lord, we know what we are, but know not"), new XElement("LINE", "what we may be. God be at your table!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Conceit upon her father.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Pray you, let's have no words of this; but when they"), new XElement("LINE", "ask you what it means, say you this:"), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "To-morrow is Saint Valentine's day,"), new XElement("LINE", "All in the morning betime,"), new XElement("LINE", "And I a maid at your window,"), new XElement("LINE", "To be your Valentine."), new XElement("LINE", "Then up he rose, and donn'd his clothes,"), new XElement("LINE", "And dupp'd the chamber-door;"), new XElement("LINE", "Let in the maid, that out a maid"), new XElement("LINE", "Never departed more.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Pretty Ophelia!") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "Indeed, la, without an oath, I'll make an end on't:"), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "By Gis and by Saint Charity,"), new XElement("LINE", "Alack, and fie for shame!"), new XElement("LINE", "Young men will do't, if they come to't;"), new XElement("LINE", "By cock, they are to blame."), new XElement("LINE", "Quoth she, before you tumbled me,"), new XElement("LINE", "You promised me to wed."), new XElement("LINE", "So would I ha' done, by yonder sun,"), new XElement("LINE", "An thou hadst not come to my bed.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "How long hath she been thus?") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "I hope all will be well. We must be patient: but I"), new XElement("LINE", "cannot choose but weep, to think they should lay him"), new XElement("LINE", "i' the cold ground. My brother shall know of it:"), new XElement("LINE", "and so I thank you for your good counsel. Come, my"), new XElement("LINE", "coach! Good night, ladies; good night, sweet ladies;"), new XElement("LINE", "good night, good night.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Follow her close; give her good watch,"), new XElement("LINE", "I pray you."), new XElement("STAGEDIR", "Exit HORATIO"), new XElement("LINE", "O, this is the poison of deep grief; it springs"), new XElement("LINE", "All from her father's death. O Gertrude, Gertrude,"), new XElement("LINE", "When sorrows come, they come not single spies"), new XElement("LINE", "But in battalions. First, her father slain:"), new XElement("LINE", "Next, your son gone; and he most violent author"), new XElement("LINE", "Of his own just remove: the people muddied,"), new XElement("LINE", "Thick and unwholesome in their thoughts and whispers,"), new XElement("LINE", "For good Polonius' death; and we have done but greenly,"), new XElement("LINE", "In hugger-mugger to inter him: poor Ophelia"), new XElement("LINE", "Divided from herself and her fair judgment,"), new XElement("LINE", "Without the which we are pictures, or mere beasts:"), new XElement("LINE", "Last, and as much containing as all these,"), new XElement("LINE", "Her brother is in secret come from France;"), new XElement("LINE", "Feeds on his wonder, keeps himself in clouds,"), new XElement("LINE", "And wants not buzzers to infect his ear"), new XElement("LINE", "With pestilent speeches of his father's death;"), new XElement("LINE", "Wherein necessity, of matter beggar'd,"), new XElement("LINE", "Will nothing stick our person to arraign"), new XElement("LINE", "In ear and ear. O my dear Gertrude, this,"), new XElement("LINE", "Like to a murdering-piece, in many places"), new XElement("LINE", "Gives me superfluous death.") ), new XElement("STAGEDIR", "A noise within"), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Alack, what noise is this?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Where are my Switzers? Let them guard the door."), new XElement("STAGEDIR", "Enter another Gentleman"), new XElement("LINE", "What is the matter?") ), new XElement("SPEECH", new XElement("SPEAKER", "Gentleman"), new XElement("LINE", "Save yourself, my lord:"), new XElement("LINE", "The ocean, overpeering of his list,"), new XElement("LINE", "Eats not the flats with more impetuous haste"), new XElement("LINE", "Than young Laertes, in a riotous head,"), new XElement("LINE", "O'erbears your officers. The rabble call him lord;"), new XElement("LINE", "And, as the world were now but to begin,"), new XElement("LINE", "Antiquity forgot, custom not known,"), new XElement("LINE", "The ratifiers and props of every word,"), new XElement("LINE", "They cry 'Choose we: Laertes shall be king:'"), new XElement("LINE", "Caps, hands, and tongues, applaud it to the clouds:"), new XElement("LINE", "'Laertes shall be king, Laertes king!'") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "How cheerfully on the false trail they cry!"), new XElement("LINE", "O, this is counter, you false Danish dogs!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "The doors are broke.") ), new XElement("STAGEDIR", "Noise within"), new XElement("STAGEDIR", "Enter LAERTES, armed; Danes following"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Where is this king? Sirs, stand you all without.") ), new XElement("SPEECH", new XElement("SPEAKER", "Danes"), new XElement("LINE", "No, let's come in.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I pray you, give me leave.") ), new XElement("SPEECH", new XElement("SPEAKER", "Danes"), new XElement("LINE", "We will, we will.") ), new XElement("STAGEDIR", "They retire without the door"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I thank you: keep the door. O thou vile king,"), new XElement("LINE", "Give me my father!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Calmly, good Laertes.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "That drop of blood that's calm proclaims me bastard,"), new XElement("LINE", "Cries cuckold to my father, brands the harlot"), new XElement("LINE", "Even here, between the chaste unsmirched brow"), new XElement("LINE", "Of my true mother.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "What is the cause, Laertes,"), new XElement("LINE", "That thy rebellion looks so giant-like?"), new XElement("LINE", "Let him go, Gertrude; do not fear our person:"), new XElement("LINE", "There's such divinity doth hedge a king,"), new XElement("LINE", "That treason can but peep to what it would,"), new XElement("LINE", "Acts little of his will. Tell me, Laertes,"), new XElement("LINE", "Why thou art thus incensed. Let him go, Gertrude."), new XElement("LINE", "Speak, man.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Where is my father?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Dead.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "But not by him.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Let him demand his fill.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "How came he dead? I'll not be juggled with:"), new XElement("LINE", "To hell, allegiance! vows, to the blackest devil!"), new XElement("LINE", "Conscience and grace, to the profoundest pit!"), new XElement("LINE", "I dare damnation. To this point I stand,"), new XElement("LINE", "That both the worlds I give to negligence,"), new XElement("LINE", "Let come what comes; only I'll be revenged"), new XElement("LINE", "Most thoroughly for my father.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Who shall stay you?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "My will, not all the world:"), new XElement("LINE", "And for my means, I'll husband them so well,"), new XElement("LINE", "They shall go far with little.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Good Laertes,"), new XElement("LINE", "If you desire to know the certainty"), new XElement("LINE", "Of your dear father's death, is't writ in your revenge,"), new XElement("LINE", "That, swoopstake, you will draw both friend and foe,"), new XElement("LINE", "Winner and loser?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "None but his enemies.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Will you know them then?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "To his good friends thus wide I'll ope my arms;"), new XElement("LINE", "And like the kind life-rendering pelican,"), new XElement("LINE", "Repast them with my blood.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Why, now you speak"), new XElement("LINE", "Like a good child and a true gentleman."), new XElement("LINE", "That I am guiltless of your father's death,"), new XElement("LINE", "And am most sensible in grief for it,"), new XElement("LINE", "It shall as level to your judgment pierce"), new XElement("LINE", "As day does to your eye.") ), new XElement("SPEECH", new XElement("SPEAKER", "Danes"), new XElement("LINE", new XElement("STAGEDIR", "Within"), " Let her come in." ) ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "How now! what noise is that?"), new XElement("STAGEDIR", "Re-enter OPHELIA"), new XElement("LINE", "O heat, dry up my brains! tears seven times salt,"), new XElement("LINE", "Burn out the sense and virtue of mine eye!"), new XElement("LINE", "By heaven, thy madness shall be paid by weight,"), new XElement("LINE", "Till our scale turn the beam. O rose of May!"), new XElement("LINE", "Dear maid, kind sister, sweet Ophelia!"), new XElement("LINE", "O heavens! is't possible, a young maid's wits"), new XElement("LINE", "Should be as moral as an old man's life?"), new XElement("LINE", "Nature is fine in love, and where 'tis fine,"), new XElement("LINE", "It sends some precious instance of itself"), new XElement("LINE", "After the thing it loves.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "They bore him barefaced on the bier;"), new XElement("LINE", "Hey non nonny, nonny, hey nonny;"), new XElement("LINE", "And in his grave rain'd many a tear:--"), new XElement("LINE", "Fare you well, my dove!") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Hadst thou thy wits, and didst persuade revenge,"), new XElement("LINE", "It could not move thus.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "You must sing a-down a-down,"), new XElement("LINE", "An you call him a-down-a."), new XElement("LINE", "O, how the wheel becomes it! It is the false"), new XElement("LINE", "steward, that stole his master's daughter.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "This nothing's more than matter.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "There's rosemary, that's for remembrance; pray,"), new XElement("LINE", "love, remember: and there is pansies. that's for thoughts.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "A document in madness, thoughts and remembrance fitted.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", "There's fennel for you, and columbines: there's rue"), new XElement("LINE", "for you; and here's some for me: we may call it"), new XElement("LINE", "herb-grace o' Sundays: O you must wear your rue with"), new XElement("LINE", "a difference. There's a daisy: I would give you"), new XElement("LINE", "some violets, but they withered all when my father"), new XElement("LINE", "died: they say he made a good end,--"), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "For bonny sweet Robin is all my joy.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Thought and affliction, passion, hell itself,"), new XElement("LINE", "She turns to favour and to prettiness.") ), new XElement("SPEECH", new XElement("SPEAKER", "OPHELIA"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "And will he not come again?"), new XElement("LINE", "And will he not come again?"), new XElement("LINE", "No, no, he is dead:"), new XElement("LINE", "Go to thy death-bed:"), new XElement("LINE", "He never will come again."), new XElement("LINE", "His beard was as white as snow,"), new XElement("LINE", "All flaxen was his poll:"), new XElement("LINE", "He is gone, he is gone,"), new XElement("LINE", "And we cast away moan:"), new XElement("LINE", "God ha' mercy on his soul!"), new XElement("LINE", "And of all Christian souls, I pray God. God be wi' ye.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Do you see this, O God?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Laertes, I must commune with your grief,"), new XElement("LINE", "Or you deny me right. Go but apart,"), new XElement("LINE", "Make choice of whom your wisest friends you will."), new XElement("LINE", "And they shall hear and judge 'twixt you and me:"), new XElement("LINE", "If by direct or by collateral hand"), new XElement("LINE", "They find us touch'd, we will our kingdom give,"), new XElement("LINE", "Our crown, our life, and all that we can ours,"), new XElement("LINE", "To you in satisfaction; but if not,"), new XElement("LINE", "Be you content to lend your patience to us,"), new XElement("LINE", "And we shall jointly labour with your soul"), new XElement("LINE", "To give it due content.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Let this be so;"), new XElement("LINE", "His means of death, his obscure funeral--"), new XElement("LINE", "No trophy, sword, nor hatchment o'er his bones,"), new XElement("LINE", "No noble rite nor formal ostentation--"), new XElement("LINE", "Cry to be heard, as 'twere from heaven to earth,"), new XElement("LINE", "That I must call't in question.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "So you shall;"), new XElement("LINE", "And where the offence is let the great axe fall."), new XElement("LINE", "I pray you, go with me.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE VI. Another room in the castle."), new XElement("STAGEDIR", "Enter HORATIO and a Servant"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What are they that would speak with me?") ), new XElement("SPEECH", new XElement("SPEAKER", "Servant"), new XElement("LINE", "Sailors, sir: they say they have letters for you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Let them come in."), new XElement("STAGEDIR", "Exit Servant"), new XElement("LINE", "I do not know from what part of the world"), new XElement("LINE", "I should be greeted, if not from Lord Hamlet.") ), new XElement("STAGEDIR", "Enter Sailors"), new XElement("SPEECH", new XElement("SPEAKER", "First Sailor"), new XElement("LINE", "God bless you, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Let him bless thee too.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Sailor"), new XElement("LINE", "He shall, sir, an't please him. There's a letter for"), new XElement("LINE", "you, sir; it comes from the ambassador that was"), new XElement("LINE", "bound for England; if your name be Horatio, as I am"), new XElement("LINE", "let to know it is.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", new XElement("STAGEDIR", "Reads"), " 'Horatio, when thou shalt have overlooked" ), new XElement("LINE", "this, give these fellows some means to the king:"), new XElement("LINE", "they have letters for him. Ere we were two days old"), new XElement("LINE", "at sea, a pirate of very warlike appointment gave us"), new XElement("LINE", "chase. Finding ourselves too slow of sail, we put on"), new XElement("LINE", "a compelled valour, and in the grapple I boarded"), new XElement("LINE", "them: on the instant they got clear of our ship; so"), new XElement("LINE", "I alone became their prisoner. They have dealt with"), new XElement("LINE", "me like thieves of mercy: but they knew what they"), new XElement("LINE", "did; I am to do a good turn for them. Let the king"), new XElement("LINE", "have the letters I have sent; and repair thou to me"), new XElement("LINE", "with as much speed as thou wouldst fly death. I"), new XElement("LINE", "have words to speak in thine ear will make thee"), new XElement("LINE", "dumb; yet are they much too light for the bore of"), new XElement("LINE", "the matter. These good fellows will bring thee"), new XElement("LINE", "where I am. Rosencrantz and Guildenstern hold their"), new XElement("LINE", "course for England: of them I have much to tell"), new XElement("LINE", "thee. Farewell."), new XElement("LINE", "'He that thou knowest thine, HAMLET.'"), new XElement("LINE", "Come, I will make you way for these your letters;"), new XElement("LINE", "And do't the speedier, that you may direct me"), new XElement("LINE", "To him from whom you brought them.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE VII. Another room in the castle."), new XElement("STAGEDIR", "Enter KING CLAUDIUS and LAERTES"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Now must your conscience my acquaintance seal,"), new XElement("LINE", "And you must put me in your heart for friend,"), new XElement("LINE", "Sith you have heard, and with a knowing ear,"), new XElement("LINE", "That he which hath your noble father slain"), new XElement("LINE", "Pursued my life.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "It well appears: but tell me"), new XElement("LINE", "Why you proceeded not against these feats,"), new XElement("LINE", "So crimeful and so capital in nature,"), new XElement("LINE", "As by your safety, wisdom, all things else,"), new XElement("LINE", "You mainly were stirr'd up.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O, for two special reasons;"), new XElement("LINE", "Which may to you, perhaps, seem much unsinew'd,"), new XElement("LINE", "But yet to me they are strong. The queen his mother"), new XElement("LINE", "Lives almost by his looks; and for myself--"), new XElement("LINE", "My virtue or my plague, be it either which--"), new XElement("LINE", "She's so conjunctive to my life and soul,"), new XElement("LINE", "That, as the star moves not but in his sphere,"), new XElement("LINE", "I could not but by her. The other motive,"), new XElement("LINE", "Why to a public count I might not go,"), new XElement("LINE", "Is the great love the general gender bear him;"), new XElement("LINE", "Who, dipping all his faults in their affection,"), new XElement("LINE", "Would, like the spring that turneth wood to stone,"), new XElement("LINE", "Convert his gyves to graces; so that my arrows,"), new XElement("LINE", "Too slightly timber'd for so loud a wind,"), new XElement("LINE", "Would have reverted to my bow again,"), new XElement("LINE", "And not where I had aim'd them.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "And so have I a noble father lost;"), new XElement("LINE", "A sister driven into desperate terms,"), new XElement("LINE", "Whose worth, if praises may go back again,"), new XElement("LINE", "Stood challenger on mount of all the age"), new XElement("LINE", "For her perfections: but my revenge will come.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Break not your sleeps for that: you must not think"), new XElement("LINE", "That we are made of stuff so flat and dull"), new XElement("LINE", "That we can let our beard be shook with danger"), new XElement("LINE", "And think it pastime. You shortly shall hear more:"), new XElement("LINE", "I loved your father, and we love ourself;"), new XElement("LINE", "And that, I hope, will teach you to imagine--"), new XElement("STAGEDIR", "Enter a Messenger"), new XElement("LINE", "How now! what news?") ), new XElement("SPEECH", new XElement("SPEAKER", "Messenger"), new XElement("LINE", "Letters, my lord, from Hamlet:"), new XElement("LINE", "This to your majesty; this to the queen.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "From Hamlet! who brought them?") ), new XElement("SPEECH", new XElement("SPEAKER", "Messenger"), new XElement("LINE", "Sailors, my lord, they say; I saw them not:"), new XElement("LINE", "They were given me by Claudio; he received them"), new XElement("LINE", "Of him that brought them.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Laertes, you shall hear them. Leave us."), new XElement("STAGEDIR", "Exit Messenger"), new XElement("STAGEDIR", "Reads"), new XElement("LINE", "'High and mighty, You shall know I am set naked on"), new XElement("LINE", "your kingdom. To-morrow shall I beg leave to see"), new XElement("LINE", "your kingly eyes: when I shall, first asking your"), new XElement("LINE", "pardon thereunto, recount the occasion of my sudden"), new XElement("LINE", "and more strange return. 'HAMLET.'"), new XElement("LINE", "What should this mean? Are all the rest come back?"), new XElement("LINE", "Or is it some abuse, and no such thing?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Know you the hand?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "'Tis Hamlets character. 'Naked!"), new XElement("LINE", "And in a postscript here, he says 'alone.'"), new XElement("LINE", "Can you advise me?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I'm lost in it, my lord. But let him come;"), new XElement("LINE", "It warms the very sickness in my heart,"), new XElement("LINE", "That I shall live and tell him to his teeth,"), new XElement("LINE", "'Thus didest thou.'") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "If it be so, Laertes--"), new XElement("LINE", "As how should it be so? how otherwise?--"), new XElement("LINE", "Will you be ruled by me?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Ay, my lord;"), new XElement("LINE", "So you will not o'errule me to a peace.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "To thine own peace. If he be now return'd,"), new XElement("LINE", "As checking at his voyage, and that he means"), new XElement("LINE", "No more to undertake it, I will work him"), new XElement("LINE", "To an exploit, now ripe in my device,"), new XElement("LINE", "Under the which he shall not choose but fall:"), new XElement("LINE", "And for his death no wind of blame shall breathe,"), new XElement("LINE", "But even his mother shall uncharge the practise"), new XElement("LINE", "And call it accident.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "My lord, I will be ruled;"), new XElement("LINE", "The rather, if you could devise it so"), new XElement("LINE", "That I might be the organ.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "It falls right."), new XElement("LINE", "You have been talk'd of since your travel much,"), new XElement("LINE", "And that in Hamlet's hearing, for a quality"), new XElement("LINE", "Wherein, they say, you shine: your sum of parts"), new XElement("LINE", "Did not together pluck such envy from him"), new XElement("LINE", "As did that one, and that, in my regard,"), new XElement("LINE", "Of the unworthiest siege.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "What part is that, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "A very riband in the cap of youth,"), new XElement("LINE", "Yet needful too; for youth no less becomes"), new XElement("LINE", "The light and careless livery that it wears"), new XElement("LINE", "Than settled age his sables and his weeds,"), new XElement("LINE", "Importing health and graveness. Two months since,"), new XElement("LINE", "Here was a gentleman of Normandy:--"), new XElement("LINE", "I've seen myself, and served against, the French,"), new XElement("LINE", "And they can well on horseback: but this gallant"), new XElement("LINE", "Had witchcraft in't; he grew unto his seat;"), new XElement("LINE", "And to such wondrous doing brought his horse,"), new XElement("LINE", "As he had been incorpsed and demi-natured"), new XElement("LINE", "With the brave beast: so far he topp'd my thought,"), new XElement("LINE", "That I, in forgery of shapes and tricks,"), new XElement("LINE", "Come short of what he did.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "A Norman was't?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "A Norman.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Upon my life, Lamond.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "The very same.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I know him well: he is the brooch indeed"), new XElement("LINE", "And gem of all the nation.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "He made confession of you,"), new XElement("LINE", "And gave you such a masterly report"), new XElement("LINE", "For art and exercise in your defence"), new XElement("LINE", "And for your rapier most especially,"), new XElement("LINE", "That he cried out, 'twould be a sight indeed,"), new XElement("LINE", "If one could match you: the scrimers of their nation,"), new XElement("LINE", "He swore, had had neither motion, guard, nor eye,"), new XElement("LINE", "If you opposed them. Sir, this report of his"), new XElement("LINE", "Did Hamlet so envenom with his envy"), new XElement("LINE", "That he could nothing do but wish and beg"), new XElement("LINE", "Your sudden coming o'er, to play with him."), new XElement("LINE", "Now, out of this,--") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "What out of this, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Laertes, was your father dear to you?"), new XElement("LINE", "Or are you like the painting of a sorrow,"), new XElement("LINE", "A face without a heart?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Why ask you this?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Not that I think you did not love your father;"), new XElement("LINE", "But that I know love is begun by time;"), new XElement("LINE", "And that I see, in passages of proof,"), new XElement("LINE", "Time qualifies the spark and fire of it."), new XElement("LINE", "There lives within the very flame of love"), new XElement("LINE", "A kind of wick or snuff that will abate it;"), new XElement("LINE", "And nothing is at a like goodness still;"), new XElement("LINE", "For goodness, growing to a plurisy,"), new XElement("LINE", "Dies in his own too much: that we would do"), new XElement("LINE", "We should do when we would; for this 'would' changes"), new XElement("LINE", "And hath abatements and delays as many"), new XElement("LINE", "As there are tongues, are hands, are accidents;"), new XElement("LINE", "And then this 'should' is like a spendthrift sigh,"), new XElement("LINE", "That hurts by easing. But, to the quick o' the ulcer:--"), new XElement("LINE", "Hamlet comes back: what would you undertake,"), new XElement("LINE", "To show yourself your father's son in deed"), new XElement("LINE", "More than in words?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "To cut his throat i' the church.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "No place, indeed, should murder sanctuarize;"), new XElement("LINE", "Revenge should have no bounds. But, good Laertes,"), new XElement("LINE", "Will you do this, keep close within your chamber."), new XElement("LINE", "Hamlet return'd shall know you are come home:"), new XElement("LINE", "We'll put on those shall praise your excellence"), new XElement("LINE", "And set a double varnish on the fame"), new XElement("LINE", "The Frenchman gave you, bring you in fine together"), new XElement("LINE", "And wager on your heads: he, being remiss,"), new XElement("LINE", "Most generous and free from all contriving,"), new XElement("LINE", "Will not peruse the foils; so that, with ease,"), new XElement("LINE", "Or with a little shuffling, you may choose"), new XElement("LINE", "A sword unbated, and in a pass of practise"), new XElement("LINE", "Requite him for your father.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I will do't:"), new XElement("LINE", "And, for that purpose, I'll anoint my sword."), new XElement("LINE", "I bought an unction of a mountebank,"), new XElement("LINE", "So mortal that, but dip a knife in it,"), new XElement("LINE", "Where it draws blood no cataplasm so rare,"), new XElement("LINE", "Collected from all simples that have virtue"), new XElement("LINE", "Under the moon, can save the thing from death"), new XElement("LINE", "That is but scratch'd withal: I'll touch my point"), new XElement("LINE", "With this contagion, that, if I gall him slightly,"), new XElement("LINE", "It may be death.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Let's further think of this;"), new XElement("LINE", "Weigh what convenience both of time and means"), new XElement("LINE", "May fit us to our shape: if this should fail,"), new XElement("LINE", "And that our drift look through our bad performance,"), new XElement("LINE", "'Twere better not assay'd: therefore this project"), new XElement("LINE", "Should have a back or second, that might hold,"), new XElement("LINE", "If this should blast in proof. Soft! let me see:"), new XElement("LINE", "We'll make a solemn wager on your cunnings: I ha't."), new XElement("LINE", "When in your motion you are hot and dry--"), new XElement("LINE", "As make your bouts more violent to that end--"), new XElement("LINE", "And that he calls for drink, I'll have prepared him"), new XElement("LINE", "A chalice for the nonce, whereon but sipping,"), new XElement("LINE", "If he by chance escape your venom'd stuck,"), new XElement("LINE", "Our purpose may hold there."), new XElement("STAGEDIR", "Enter QUEEN GERTRUDE"), new XElement("LINE", "How now, sweet queen!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "One woe doth tread upon another's heel,"), new XElement("LINE", "So fast they follow; your sister's drown'd, Laertes.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Drown'd! O, where?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "There is a willow grows aslant a brook,"), new XElement("LINE", "That shows his hoar leaves in the glassy stream;"), new XElement("LINE", "There with fantastic garlands did she come"), new XElement("LINE", "Of crow-flowers, nettles, daisies, and long purples"), new XElement("LINE", "That liberal shepherds give a grosser name,"), new XElement("LINE", "But our cold maids do dead men's fingers call them:"), new XElement("LINE", "There, on the pendent boughs her coronet weeds"), new XElement("LINE", "Clambering to hang, an envious sliver broke;"), new XElement("LINE", "When down her weedy trophies and herself"), new XElement("LINE", "Fell in the weeping brook. Her clothes spread wide;"), new XElement("LINE", "And, mermaid-like, awhile they bore her up:"), new XElement("LINE", "Which time she chanted snatches of old tunes;"), new XElement("LINE", "As one incapable of her own distress,"), new XElement("LINE", "Or like a creature native and indued"), new XElement("LINE", "Unto that element: but long it could not be"), new XElement("LINE", "Till that her garments, heavy with their drink,"), new XElement("LINE", "Pull'd the poor wretch from her melodious lay"), new XElement("LINE", "To muddy death.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Alas, then, she is drown'd?") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Drown'd, drown'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Too much of water hast thou, poor Ophelia,"), new XElement("LINE", "And therefore I forbid my tears: but yet"), new XElement("LINE", "It is our trick; nature her custom holds,"), new XElement("LINE", "Let shame say what it will: when these are gone,"), new XElement("LINE", "The woman will be out. Adieu, my lord:"), new XElement("LINE", "I have a speech of fire, that fain would blaze,"), new XElement("LINE", "But that this folly douts it.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Let's follow, Gertrude:"), new XElement("LINE", "How much I had to do to calm his rage!"), new XElement("LINE", "Now fear I this will give it start again;"), new XElement("LINE", "Therefore let's follow.") ), new XElement("STAGEDIR", "Exeunt") ) ), new XElement("ACT", new XElement("TITLE", "ACT V"), new XElement("SCENE", new XElement("TITLE", "SCENE I. A churchyard."), new XElement("STAGEDIR", "Enter two Clowns, with spades, &c"), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Is she to be buried in Christian burial that"), new XElement("LINE", "wilfully seeks her own salvation?") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "I tell thee she is: and therefore make her grave"), new XElement("LINE", "straight: the crowner hath sat on her, and finds it"), new XElement("LINE", "Christian burial.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "How can that be, unless she drowned herself in her"), new XElement("LINE", "own defence?") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Why, 'tis found so.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "It must be 'se offendendo;' it cannot be else. For"), new XElement("LINE", "here lies the point: if I drown myself wittingly,"), new XElement("LINE", "it argues an act: and an act hath three branches: it"), new XElement("LINE", "is, to act, to do, to perform: argal, she drowned"), new XElement("LINE", "herself wittingly.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Nay, but hear you, goodman delver,--") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Give me leave. Here lies the water; good: here"), new XElement("LINE", "stands the man; good; if the man go to this water,"), new XElement("LINE", "and drown himself, it is, will he, nill he, he"), new XElement("LINE", "goes,--mark you that; but if the water come to him"), new XElement("LINE", "and drown him, he drowns not himself: argal, he"), new XElement("LINE", "that is not guilty of his own death shortens not his own life.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "But is this law?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Ay, marry, is't; crowner's quest law.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Will you ha' the truth on't? If this had not been"), new XElement("LINE", "a gentlewoman, she should have been buried out o'"), new XElement("LINE", "Christian burial.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Why, there thou say'st: and the more pity that"), new XElement("LINE", "great folk should have countenance in this world to"), new XElement("LINE", "drown or hang themselves, more than their even"), new XElement("LINE", "Christian. Come, my spade. There is no ancient"), new XElement("LINE", "gentleman but gardeners, ditchers, and grave-makers:"), new XElement("LINE", "they hold up Adam's profession.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Was he a gentleman?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "He was the first that ever bore arms.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Why, he had none.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "What, art a heathen? How dost thou understand the"), new XElement("LINE", "Scripture? The Scripture says 'Adam digged:'"), new XElement("LINE", "could he dig without arms? I'll put another"), new XElement("LINE", "question to thee: if thou answerest me not to the"), new XElement("LINE", "purpose, confess thyself--") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Go to.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "What is he that builds stronger than either the"), new XElement("LINE", "mason, the shipwright, or the carpenter?") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "The gallows-maker; for that frame outlives a"), new XElement("LINE", "thousand tenants.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "I like thy wit well, in good faith: the gallows"), new XElement("LINE", "does well; but how does it well? it does well to"), new XElement("LINE", "those that do in: now thou dost ill to say the"), new XElement("LINE", "gallows is built stronger than the church: argal,"), new XElement("LINE", "the gallows may do well to thee. To't again, come.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "'Who builds stronger than a mason, a shipwright, or"), new XElement("LINE", "a carpenter?'") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Ay, tell me that, and unyoke.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Marry, now I can tell.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "To't.") ), new XElement("SPEECH", new XElement("SPEAKER", "Second Clown"), new XElement("LINE", "Mass, I cannot tell.") ), new XElement("STAGEDIR", "Enter HAMLET and HORATIO, at a distance"), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Cudgel thy brains no more about it, for your dull"), new XElement("LINE", "ass will not mend his pace with beating; and, when"), new XElement("LINE", "you are asked this question next, say 'a"), new XElement("LINE", "grave-maker: 'the houses that he makes last till"), new XElement("LINE", "doomsday. Go, get thee to Yaughan: fetch me a"), new XElement("LINE", "stoup of liquor."), new XElement("STAGEDIR", "Exit Second Clown"), new XElement("STAGEDIR", "He digs and sings"), new XElement("LINE", "In youth, when I did love, did love,"), new XElement("LINE", "Methought it was very sweet,"), new XElement("LINE", "To contract, O, the time, for, ah, my behove,"), new XElement("LINE", "O, methought, there was nothing meet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Has this fellow no feeling of his business, that he"), new XElement("LINE", "sings at grave-making?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Custom hath made it in him a property of easiness.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Tis e'en so: the hand of little employment hath"), new XElement("LINE", "the daintier sense.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", new XElement("STAGEDIR", "Sings") ), new XElement("LINE", "But age, with his stealing steps,"), new XElement("LINE", "Hath claw'd me in his clutch,"), new XElement("LINE", "And hath shipped me intil the land,"), new XElement("LINE", "As if I had never been such.") ), new XElement("STAGEDIR", "Throws up a skull"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That skull had a tongue in it, and could sing once:"), new XElement("LINE", "how the knave jowls it to the ground, as if it were"), new XElement("LINE", "Cain's jaw-bone, that did the first murder! It"), new XElement("LINE", "might be the pate of a politician, which this ass"), new XElement("LINE", "now o'er-reaches; one that would circumvent God,"), new XElement("LINE", "might it not?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It might, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Or of a courtier; which could say 'Good morrow,"), new XElement("LINE", "sweet lord! How dost thou, good lord?' This might"), new XElement("LINE", "be my lord such-a-one, that praised my lord"), new XElement("LINE", "such-a-one's horse, when he meant to beg it; might it not?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Ay, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, e'en so: and now my Lady Worm's; chapless, and"), new XElement("LINE", "knocked about the mazzard with a sexton's spade:"), new XElement("LINE", "here's fine revolution, an we had the trick to"), new XElement("LINE", "see't. Did these bones cost no more the breeding,"), new XElement("LINE", "but to play at loggats with 'em? mine ache to think on't.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "A pick-axe, and a spade, a spade,"), new XElement("LINE", "For and a shrouding sheet:"), new XElement("LINE", "O, a pit of clay for to be made"), new XElement("LINE", "For such a guest is meet.") ), new XElement("STAGEDIR", "Throws up another skull"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "There's another: why may not that be the skull of a"), new XElement("LINE", "lawyer? Where be his quiddities now, his quillets,"), new XElement("LINE", "his cases, his tenures, and his tricks? why does he"), new XElement("LINE", "suffer this rude knave now to knock him about the"), new XElement("LINE", "sconce with a dirty shovel, and will not tell him of"), new XElement("LINE", "his action of battery? Hum! This fellow might be"), new XElement("LINE", "in's time a great buyer of land, with his statutes,"), new XElement("LINE", "his recognizances, his fines, his double vouchers,"), new XElement("LINE", "his recoveries: is this the fine of his fines, and"), new XElement("LINE", "the recovery of his recoveries, to have his fine"), new XElement("LINE", "pate full of fine dirt? will his vouchers vouch him"), new XElement("LINE", "no more of his purchases, and double ones too, than"), new XElement("LINE", "the length and breadth of a pair of indentures? The"), new XElement("LINE", "very conveyances of his lands will hardly lie in"), new XElement("LINE", "this box; and must the inheritor himself have no more, ha?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Not a jot more, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Is not parchment made of sheepskins?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Ay, my lord, and of calf-skins too.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "They are sheep and calves which seek out assurance"), new XElement("LINE", "in that. I will speak to this fellow. Whose"), new XElement("LINE", "grave's this, sirrah?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Mine, sir."), new XElement("STAGEDIR", "Sings"), new XElement("LINE", "O, a pit of clay for to be made"), new XElement("LINE", "For such a guest is meet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I think it be thine, indeed; for thou liest in't.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "You lie out on't, sir, and therefore it is not"), new XElement("LINE", "yours: for my part, I do not lie in't, and yet it is mine.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Thou dost lie in't, to be in't and say it is thine:"), new XElement("LINE", "'tis for the dead, not for the quick; therefore thou liest.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "'Tis a quick lie, sir; 'twill away gain, from me to"), new XElement("LINE", "you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What man dost thou dig it for?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "For no man, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What woman, then?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "For none, neither.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Who is to be buried in't?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "One that was a woman, sir; but, rest her soul, she's dead.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How absolute the knave is! we must speak by the"), new XElement("LINE", "card, or equivocation will undo us. By the Lord,"), new XElement("LINE", "Horatio, these three years I have taken a note of"), new XElement("LINE", "it; the age is grown so picked that the toe of the"), new XElement("LINE", "peasant comes so near the heel of the courtier, he"), new XElement("LINE", "gaffs his kibe. How long hast thou been a"), new XElement("LINE", "grave-maker?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Of all the days i' the year, I came to't that day"), new XElement("LINE", "that our last king Hamlet overcame Fortinbras.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How long is that since?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Cannot you tell that? every fool can tell that: it"), new XElement("LINE", "was the very day that young Hamlet was born; he that"), new XElement("LINE", "is mad, and sent into England.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Ay, marry, why was he sent into England?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Why, because he was mad: he shall recover his wits"), new XElement("LINE", "there; or, if he do not, it's no great matter there.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "'Twill, a not be seen in him there; there the men"), new XElement("LINE", "are as mad as he.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How came he mad?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Very strangely, they say.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How strangely?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Faith, e'en with losing his wits.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Upon what ground?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Why, here in Denmark: I have been sexton here, man"), new XElement("LINE", "and boy, thirty years.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How long will a man lie i' the earth ere he rot?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "I' faith, if he be not rotten before he die--as we"), new XElement("LINE", "have many pocky corses now-a-days, that will scarce"), new XElement("LINE", "hold the laying in--he will last you some eight year"), new XElement("LINE", "or nine year: a tanner will last you nine year.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why he more than another?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "Why, sir, his hide is so tanned with his trade, that"), new XElement("LINE", "he will keep out water a great while; and your water"), new XElement("LINE", "is a sore decayer of your whoreson dead body."), new XElement("LINE", "Here's a skull now; this skull has lain in the earth"), new XElement("LINE", "three and twenty years.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Whose was it?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "A whoreson mad fellow's it was: whose do you think it was?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, I know not.") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "A pestilence on him for a mad rogue! a' poured a"), new XElement("LINE", "flagon of Rhenish on my head once. This same skull,"), new XElement("LINE", "sir, was Yorick's skull, the king's jester.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "This?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Clown"), new XElement("LINE", "E'en that.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Let me see."), new XElement("STAGEDIR", "Takes the skull"), new XElement("LINE", "Alas, poor Yorick! I knew him, Horatio: a fellow"), new XElement("LINE", "of infinite jest, of most excellent fancy: he hath"), new XElement("LINE", "borne me on his back a thousand times; and now, how"), new XElement("LINE", "abhorred in my imagination it is! my gorge rims at"), new XElement("LINE", "it. Here hung those lips that I have kissed I know"), new XElement("LINE", "not how oft. Where be your gibes now? your"), new XElement("LINE", "gambols? your songs? your flashes of merriment,"), new XElement("LINE", "that were wont to set the table on a roar? Not one"), new XElement("LINE", "now, to mock your own grinning? quite chap-fallen?"), new XElement("LINE", "Now get you to my lady's chamber, and tell her, let"), new XElement("LINE", "her paint an inch thick, to this favour she must"), new XElement("LINE", "come; make her laugh at that. Prithee, Horatio, tell"), new XElement("LINE", "me one thing.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What's that, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Dost thou think Alexander looked o' this fashion i'"), new XElement("LINE", "the earth?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "E'en so.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "And smelt so? pah!") ), new XElement("STAGEDIR", "Puts down the skull"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "E'en so, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "To what base uses we may return, Horatio! Why may"), new XElement("LINE", "not imagination trace the noble dust of Alexander,"), new XElement("LINE", "till he find it stopping a bung-hole?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "'Twere to consider too curiously, to consider so.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, faith, not a jot; but to follow him thither with"), new XElement("LINE", "modesty enough, and likelihood to lead it: as"), new XElement("LINE", "thus: Alexander died, Alexander was buried,"), new XElement("LINE", "Alexander returneth into dust; the dust is earth; of"), new XElement("LINE", "earth we make loam; and why of that loam, whereto he"), new XElement("LINE", "was converted, might they not stop a beer-barrel?"), new XElement("LINE", "Imperious Caesar, dead and turn'd to clay,"), new XElement("LINE", "Might stop a hole to keep the wind away:"), new XElement("LINE", "O, that that earth, which kept the world in awe,"), new XElement("LINE", "Should patch a wall to expel the winter flaw!"), new XElement("LINE", "But soft! but soft! aside: here comes the king."), new XElement("STAGEDIR", "Enter Priest, &c. in procession; the Corpse of\n" + "OPHELIA, LAERTES and Mourners following; KING\n" + "CLAUDIUS, QUEEN GERTRUDE, their trains, &c" ), new XElement("LINE", "The queen, the courtiers: who is this they follow?"), new XElement("LINE", "And with such maimed rites? This doth betoken"), new XElement("LINE", "The corse they follow did with desperate hand"), new XElement("LINE", "Fordo its own life: 'twas of some estate."), new XElement("LINE", "Couch we awhile, and mark.") ), new XElement("STAGEDIR", "Retiring with HORATIO"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "What ceremony else?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That is Laertes,"), new XElement("LINE", "A very noble youth: mark.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "What ceremony else?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Priest"), new XElement("LINE", "Her obsequies have been as far enlarged"), new XElement("LINE", "As we have warrantise: her death was doubtful;"), new XElement("LINE", "And, but that great command o'ersways the order,"), new XElement("LINE", "She should in ground unsanctified have lodged"), new XElement("LINE", "Till the last trumpet: for charitable prayers,"), new XElement("LINE", "Shards, flints and pebbles should be thrown on her;"), new XElement("LINE", "Yet here she is allow'd her virgin crants,"), new XElement("LINE", "Her maiden strewments and the bringing home"), new XElement("LINE", "Of bell and burial.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Must there no more be done?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Priest"), new XElement("LINE", "No more be done:"), new XElement("LINE", "We should profane the service of the dead"), new XElement("LINE", "To sing a requiem and such rest to her"), new XElement("LINE", "As to peace-parted souls.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Lay her i' the earth:"), new XElement("LINE", "And from her fair and unpolluted flesh"), new XElement("LINE", "May violets spring! I tell thee, churlish priest,"), new XElement("LINE", "A ministering angel shall my sister be,"), new XElement("LINE", "When thou liest howling.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What, the fair Ophelia!") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Sweets to the sweet: farewell!"), new XElement("STAGEDIR", "Scattering flowers"), new XElement("LINE", "I hoped thou shouldst have been my Hamlet's wife;"), new XElement("LINE", "I thought thy bride-bed to have deck'd, sweet maid,"), new XElement("LINE", "And not have strew'd thy grave.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "O, treble woe"), new XElement("LINE", "Fall ten times treble on that cursed head,"), new XElement("LINE", "Whose wicked deed thy most ingenious sense"), new XElement("LINE", "Deprived thee of! Hold off the earth awhile,"), new XElement("LINE", "Till I have caught her once more in mine arms:"), new XElement("STAGEDIR", "Leaps into the grave"), new XElement("LINE", "Now pile your dust upon the quick and dead,"), new XElement("LINE", "Till of this flat a mountain you have made,"), new XElement("LINE", "To o'ertop old Pelion, or the skyish head"), new XElement("LINE", "Of blue Olympus.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", new XElement("STAGEDIR", "Advancing"), " What is he whose grief" ), new XElement("LINE", "Bears such an emphasis? whose phrase of sorrow"), new XElement("LINE", "Conjures the wandering stars, and makes them stand"), new XElement("LINE", "Like wonder-wounded hearers? This is I,"), new XElement("LINE", "Hamlet the Dane.") ), new XElement("STAGEDIR", "Leaps into the grave"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "The devil take thy soul!") ), new XElement("STAGEDIR", "Grappling with him"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Thou pray'st not well."), new XElement("LINE", "I prithee, take thy fingers from my throat;"), new XElement("LINE", "For, though I am not splenitive and rash,"), new XElement("LINE", "Yet have I something in me dangerous,"), new XElement("LINE", "Which let thy wiseness fear: hold off thy hand.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Pluck them asunder.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Hamlet, Hamlet!") ), new XElement("SPEECH", new XElement("SPEAKER", "All"), new XElement("LINE", "Gentlemen,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Good my lord, be quiet.") ), new XElement("STAGEDIR", "The Attendants part them, and they come out of the grave"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why I will fight with him upon this theme"), new XElement("LINE", "Until my eyelids will no longer wag.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "O my son, what theme?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I loved Ophelia: forty thousand brothers"), new XElement("LINE", "Could not, with all their quantity of love,"), new XElement("LINE", "Make up my sum. What wilt thou do for her?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O, he is mad, Laertes.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "For love of God, forbear him.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "'Swounds, show me what thou'lt do:"), new XElement("LINE", "Woo't weep? woo't fight? woo't fast? woo't tear thyself?"), new XElement("LINE", "Woo't drink up eisel? eat a crocodile?"), new XElement("LINE", "I'll do't. Dost thou come here to whine?"), new XElement("LINE", "To outface me with leaping in her grave?"), new XElement("LINE", "Be buried quick with her, and so will I:"), new XElement("LINE", "And, if thou prate of mountains, let them throw"), new XElement("LINE", "Millions of acres on us, till our ground,"), new XElement("LINE", "Singeing his pate against the burning zone,"), new XElement("LINE", "Make Ossa like a wart! Nay, an thou'lt mouth,"), new XElement("LINE", "I'll rant as well as thou.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "This is mere madness:"), new XElement("LINE", "And thus awhile the fit will work on him;"), new XElement("LINE", "Anon, as patient as the female dove,"), new XElement("LINE", "When that her golden couplets are disclosed,"), new XElement("LINE", "His silence will sit drooping.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Hear you, sir;"), new XElement("LINE", "What is the reason that you use me thus?"), new XElement("LINE", "I loved you ever: but it is no matter;"), new XElement("LINE", "Let Hercules himself do what he may,"), new XElement("LINE", "The cat will mew and dog will have his day.") ), new XElement("STAGEDIR", "Exit"), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I pray you, good Horatio, wait upon him."), new XElement("STAGEDIR", "Exit HORATIO"), new XElement("STAGEDIR", "To LAERTES"), new XElement("LINE", "Strengthen your patience in our last night's speech;"), new XElement("LINE", "We'll put the matter to the present push."), new XElement("LINE", "Good Gertrude, set some watch over your son."), new XElement("LINE", "This grave shall have a living monument:"), new XElement("LINE", "An hour of quiet shortly shall we see;"), new XElement("LINE", "Till then, in patience our proceeding be.") ), new XElement("STAGEDIR", "Exeunt") ), new XElement("SCENE", new XElement("TITLE", "SCENE II. A hall in the castle."), new XElement("STAGEDIR", "Enter HAMLET and HORATIO"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "So much for this, sir: now shall you see the other;"), new XElement("LINE", "You do remember all the circumstance?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Remember it, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, in my heart there was a kind of fighting,"), new XElement("LINE", "That would not let me sleep: methought I lay"), new XElement("LINE", "Worse than the mutines in the bilboes. Rashly,"), new XElement("LINE", "And praised be rashness for it, let us know,"), new XElement("LINE", "Our indiscretion sometimes serves us well,"), new XElement("LINE", "When our deep plots do pall: and that should teach us"), new XElement("LINE", "There's a divinity that shapes our ends,"), new XElement("LINE", "Rough-hew them how we will,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "That is most certain.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Up from my cabin,"), new XElement("LINE", "My sea-gown scarf'd about me, in the dark"), new XElement("LINE", "Groped I to find out them; had my desire."), new XElement("LINE", "Finger'd their packet, and in fine withdrew"), new XElement("LINE", "To mine own room again; making so bold,"), new XElement("LINE", "My fears forgetting manners, to unseal"), new XElement("LINE", "Their grand commission; where I found, Horatio,--"), new XElement("LINE", "O royal knavery!--an exact command,"), new XElement("LINE", "Larded with many several sorts of reasons"), new XElement("LINE", "Importing Denmark's health and England's too,"), new XElement("LINE", "With, ho! such bugs and goblins in my life,"), new XElement("LINE", "That, on the supervise, no leisure bated,"), new XElement("LINE", "No, not to stay the grinding of the axe,"), new XElement("LINE", "My head should be struck off.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Is't possible?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Here's the commission: read it at more leisure."), new XElement("LINE", "But wilt thou hear me how I did proceed?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I beseech you.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Being thus be-netted round with villanies,--"), new XElement("LINE", "Ere I could make a prologue to my brains,"), new XElement("LINE", "They had begun the play--I sat me down,"), new XElement("LINE", "Devised a new commission, wrote it fair:"), new XElement("LINE", "I once did hold it, as our statists do,"), new XElement("LINE", "A baseness to write fair and labour'd much"), new XElement("LINE", "How to forget that learning, but, sir, now"), new XElement("LINE", "It did me yeoman's service: wilt thou know"), new XElement("LINE", "The effect of what I wrote?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Ay, good my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "An earnest conjuration from the king,"), new XElement("LINE", "As England was his faithful tributary,"), new XElement("LINE", "As love between them like the palm might flourish,"), new XElement("LINE", "As peace should stiff her wheaten garland wear"), new XElement("LINE", "And stand a comma 'tween their amities,"), new XElement("LINE", "And many such-like 'As'es of great charge,"), new XElement("LINE", "That, on the view and knowing of these contents,"), new XElement("LINE", "Without debatement further, more or less,"), new XElement("LINE", "He should the bearers put to sudden death,"), new XElement("LINE", "Not shriving-time allow'd.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "How was this seal'd?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, even in that was heaven ordinant."), new XElement("LINE", "I had my father's signet in my purse,"), new XElement("LINE", "Which was the model of that Danish seal;"), new XElement("LINE", "Folded the writ up in form of the other,"), new XElement("LINE", "Subscribed it, gave't the impression, placed it safely,"), new XElement("LINE", "The changeling never known. Now, the next day"), new XElement("LINE", "Was our sea-fight; and what to this was sequent"), new XElement("LINE", "Thou know'st already.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "So Guildenstern and Rosencrantz go to't.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Why, man, they did make love to this employment;"), new XElement("LINE", "They are not near my conscience; their defeat"), new XElement("LINE", "Does by their own insinuation grow:"), new XElement("LINE", "'Tis dangerous when the baser nature comes"), new XElement("LINE", "Between the pass and fell incensed points"), new XElement("LINE", "Of mighty opposites.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Why, what a king is this!") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Does it not, think'st thee, stand me now upon--"), new XElement("LINE", "He that hath kill'd my king and whored my mother,"), new XElement("LINE", "Popp'd in between the election and my hopes,"), new XElement("LINE", "Thrown out his angle for my proper life,"), new XElement("LINE", "And with such cozenage--is't not perfect conscience,"), new XElement("LINE", "To quit him with this arm? and is't not to be damn'd,"), new XElement("LINE", "To let this canker of our nature come"), new XElement("LINE", "In further evil?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "It must be shortly known to him from England"), new XElement("LINE", "What is the issue of the business there.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It will be short: the interim is mine;"), new XElement("LINE", "And a man's life's no more than to say 'One.'"), new XElement("LINE", "But I am very sorry, good Horatio,"), new XElement("LINE", "That to Laertes I forgot myself;"), new XElement("LINE", "For, by the image of my cause, I see"), new XElement("LINE", "The portraiture of his: I'll court his favours."), new XElement("LINE", "But, sure, the bravery of his grief did put me"), new XElement("LINE", "Into a towering passion.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Peace! who comes here?") ), new XElement("STAGEDIR", "Enter OSRIC"), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Your lordship is right welcome back to Denmark.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I humbly thank you, sir. Dost know this water-fly?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "No, my good lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Thy state is the more gracious; for 'tis a vice to"), new XElement("LINE", "know him. He hath much land, and fertile: let a"), new XElement("LINE", "beast be lord of beasts, and his crib shall stand at"), new XElement("LINE", "the king's mess: 'tis a chough; but, as I say,"), new XElement("LINE", "spacious in the possession of dirt.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Sweet lord, if your lordship were at leisure, I"), new XElement("LINE", "should impart a thing to you from his majesty.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I will receive it, sir, with all diligence of"), new XElement("LINE", "spirit. Put your bonnet to his right use; 'tis for the head.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "I thank your lordship, it is very hot.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, believe me, 'tis very cold; the wind is"), new XElement("LINE", "northerly.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "It is indifferent cold, my lord, indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "But yet methinks it is very sultry and hot for my"), new XElement("LINE", "complexion.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Exceedingly, my lord; it is very sultry,--as"), new XElement("LINE", "'twere,--I cannot tell how. But, my lord, his"), new XElement("LINE", "majesty bade me signify to you that he has laid a"), new XElement("LINE", "great wager on your head: sir, this is the matter,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I beseech you, remember--") ), new XElement("STAGEDIR", "HAMLET moves him to put on his hat"), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Nay, good my lord; for mine ease, in good faith."), new XElement("LINE", "Sir, here is newly come to court Laertes; believe"), new XElement("LINE", "me, an absolute gentleman, full of most excellent"), new XElement("LINE", "differences, of very soft society and great showing:"), new XElement("LINE", "indeed, to speak feelingly of him, he is the card or"), new XElement("LINE", "calendar of gentry, for you shall find in him the"), new XElement("LINE", "continent of what part a gentleman would see.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, his definement suffers no perdition in you;"), new XElement("LINE", "though, I know, to divide him inventorially would"), new XElement("LINE", "dizzy the arithmetic of memory, and yet but yaw"), new XElement("LINE", "neither, in respect of his quick sail. But, in the"), new XElement("LINE", "verity of extolment, I take him to be a soul of"), new XElement("LINE", "great article; and his infusion of such dearth and"), new XElement("LINE", "rareness, as, to make true diction of him, his"), new XElement("LINE", "semblable is his mirror; and who else would trace"), new XElement("LINE", "him, his umbrage, nothing more.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Your lordship speaks most infallibly of him.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The concernancy, sir? why do we wrap the gentleman"), new XElement("LINE", "in our more rawer breath?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Sir?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Is't not possible to understand in another tongue?"), new XElement("LINE", "You will do't, sir, really.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What imports the nomination of this gentleman?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Of Laertes?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "His purse is empty already; all's golden words are spent.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Of him, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "I know you are not ignorant--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I would you did, sir; yet, in faith, if you did,"), new XElement("LINE", "it would not much approve me. Well, sir?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "You are not ignorant of what excellence Laertes is--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I dare not confess that, lest I should compare with"), new XElement("LINE", "him in excellence; but, to know a man well, were to"), new XElement("LINE", "know himself.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "I mean, sir, for his weapon; but in the imputation"), new XElement("LINE", "laid on him by them, in his meed he's unfellowed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What's his weapon?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Rapier and dagger.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "That's two of his weapons: but, well.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "The king, sir, hath wagered with him six Barbary"), new XElement("LINE", "horses: against the which he has imponed, as I take"), new XElement("LINE", "it, six French rapiers and poniards, with their"), new XElement("LINE", "assigns, as girdle, hangers, and so: three of the"), new XElement("LINE", "carriages, in faith, are very dear to fancy, very"), new XElement("LINE", "responsive to the hilts, most delicate carriages,"), new XElement("LINE", "and of very liberal conceit.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "What call you the carriages?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "I knew you must be edified by the margent ere you had done.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "The carriages, sir, are the hangers.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The phrase would be more german to the matter, if we"), new XElement("LINE", "could carry cannon by our sides: I would it might"), new XElement("LINE", "be hangers till then. But, on: six Barbary horses"), new XElement("LINE", "against six French swords, their assigns, and three"), new XElement("LINE", "liberal-conceited carriages; that's the French bet"), new XElement("LINE", "against the Danish. Why is this 'imponed,' as you call it?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "The king, sir, hath laid, that in a dozen passes"), new XElement("LINE", "between yourself and him, he shall not exceed you"), new XElement("LINE", "three hits: he hath laid on twelve for nine; and it"), new XElement("LINE", "would come to immediate trial, if your lordship"), new XElement("LINE", "would vouchsafe the answer.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How if I answer 'no'?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "I mean, my lord, the opposition of your person in trial.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Sir, I will walk here in the hall: if it please his"), new XElement("LINE", "majesty, 'tis the breathing time of day with me; let"), new XElement("LINE", "the foils be brought, the gentleman willing, and the"), new XElement("LINE", "king hold his purpose, I will win for him an I can;"), new XElement("LINE", "if not, I will gain nothing but my shame and the odd hits.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Shall I re-deliver you e'en so?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "To this effect, sir; after what flourish your nature will.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "I commend my duty to your lordship.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Yours, yours."), new XElement("STAGEDIR", "Exit OSRIC"), new XElement("LINE", "He does well to commend it himself; there are no"), new XElement("LINE", "tongues else for's turn.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "This lapwing runs away with the shell on his head.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "He did comply with his dug, before he sucked it."), new XElement("LINE", "Thus has he--and many more of the same bevy that I"), new XElement("LINE", "know the dressy age dotes on--only got the tune of"), new XElement("LINE", "the time and outward habit of encounter; a kind of"), new XElement("LINE", "yesty collection, which carries them through and"), new XElement("LINE", "through the most fond and winnowed opinions; and do"), new XElement("LINE", "but blow them to their trial, the bubbles are out.") ), new XElement("STAGEDIR", "Enter a Lord"), new XElement("SPEECH", new XElement("SPEAKER", "Lord"), new XElement("LINE", "My lord, his majesty commended him to you by young"), new XElement("LINE", "Osric, who brings back to him that you attend him in"), new XElement("LINE", "the hall: he sends to know if your pleasure hold to"), new XElement("LINE", "play with Laertes, or that you will take longer time.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I am constant to my purpose; they follow the king's"), new XElement("LINE", "pleasure: if his fitness speaks, mine is ready; now"), new XElement("LINE", "or whensoever, provided I be so able as now.") ), new XElement("SPEECH", new XElement("SPEAKER", "Lord"), new XElement("LINE", "The king and queen and all are coming down.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "In happy time.") ), new XElement("SPEECH", new XElement("SPEAKER", "Lord"), new XElement("LINE", "The queen desires you to use some gentle"), new XElement("LINE", "entertainment to Laertes before you fall to play.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "She well instructs me.") ), new XElement("STAGEDIR", "Exit Lord"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "You will lose this wager, my lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I do not think so: since he went into France, I"), new XElement("LINE", "have been in continual practise: I shall win at the"), new XElement("LINE", "odds. But thou wouldst not think how ill all's here"), new XElement("LINE", "about my heart: but it is no matter.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Nay, good my lord,--") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "It is but foolery; but it is such a kind of"), new XElement("LINE", "gain-giving, as would perhaps trouble a woman.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "If your mind dislike any thing, obey it: I will"), new XElement("LINE", "forestall their repair hither, and say you are not"), new XElement("LINE", "fit.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Not a whit, we defy augury: there's a special"), new XElement("LINE", "providence in the fall of a sparrow. If it be now,"), new XElement("LINE", "'tis not to come; if it be not to come, it will be"), new XElement("LINE", "now; if it be not now, yet it will come: the"), new XElement("LINE", "readiness is all: since no man has aught of what he"), new XElement("LINE", "leaves, what is't to leave betimes?") ), new XElement("STAGEDIR", "Enter KING CLAUDIUS, QUEEN GERTRUDE, LAERTES,\n" + "Lords, OSRIC, and Attendants with foils, &c" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Come, Hamlet, come, and take this hand from me.") ), new XElement("STAGEDIR", "KING CLAUDIUS puts LAERTES' hand into HAMLET's"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Give me your pardon, sir: I've done you wrong;"), new XElement("LINE", "But pardon't, as you are a gentleman."), new XElement("LINE", "This presence knows,"), new XElement("LINE", "And you must needs have heard, how I am punish'd"), new XElement("LINE", "With sore distraction. What I have done,"), new XElement("LINE", "That might your nature, honour and exception"), new XElement("LINE", "Roughly awake, I here proclaim was madness."), new XElement("LINE", "Was't Hamlet wrong'd Laertes? Never Hamlet:"), new XElement("LINE", "If Hamlet from himself be ta'en away,"), new XElement("LINE", "And when he's not himself does wrong Laertes,"), new XElement("LINE", "Then Hamlet does it not, Hamlet denies it."), new XElement("LINE", "Who does it, then? His madness: if't be so,"), new XElement("LINE", "Hamlet is of the faction that is wrong'd;"), new XElement("LINE", "His madness is poor Hamlet's enemy."), new XElement("LINE", "Sir, in this audience,"), new XElement("LINE", "Let my disclaiming from a purposed evil"), new XElement("LINE", "Free me so far in your most generous thoughts,"), new XElement("LINE", "That I have shot mine arrow o'er the house,"), new XElement("LINE", "And hurt my brother.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "I am satisfied in nature,"), new XElement("LINE", "Whose motive, in this case, should stir me most"), new XElement("LINE", "To my revenge: but in my terms of honour"), new XElement("LINE", "I stand aloof; and will no reconcilement,"), new XElement("LINE", "Till by some elder masters, of known honour,"), new XElement("LINE", "I have a voice and precedent of peace,"), new XElement("LINE", "To keep my name ungored. But till that time,"), new XElement("LINE", "I do receive your offer'd love like love,"), new XElement("LINE", "And will not wrong it.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I embrace it freely;"), new XElement("LINE", "And will this brother's wager frankly play."), new XElement("LINE", "Give us the foils. Come on.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Come, one for me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I'll be your foil, Laertes: in mine ignorance"), new XElement("LINE", "Your skill shall, like a star i' the darkest night,"), new XElement("LINE", "Stick fiery off indeed.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "You mock me, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "No, by this hand.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Give them the foils, young Osric. Cousin Hamlet,"), new XElement("LINE", "You know the wager?") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Very well, my lord"), new XElement("LINE", "Your grace hath laid the odds o' the weaker side.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I do not fear it; I have seen you both:"), new XElement("LINE", "But since he is better'd, we have therefore odds.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "This is too heavy, let me see another.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "This likes me well. These foils have all a length?") ), new XElement("STAGEDIR", "They prepare to play"), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Ay, my good lord.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Set me the stoops of wine upon that table."), new XElement("LINE", "If Hamlet give the first or second hit,"), new XElement("LINE", "Or quit in answer of the third exchange,"), new XElement("LINE", "Let all the battlements their ordnance fire:"), new XElement("LINE", "The king shall drink to Hamlet's better breath;"), new XElement("LINE", "And in the cup an union shall he throw,"), new XElement("LINE", "Richer than that which four successive kings"), new XElement("LINE", "In Denmark's crown have worn. Give me the cups;"), new XElement("LINE", "And let the kettle to the trumpet speak,"), new XElement("LINE", "The trumpet to the cannoneer without,"), new XElement("LINE", "The cannons to the heavens, the heavens to earth,"), new XElement("LINE", "'Now the king dunks to Hamlet.' Come, begin:"), new XElement("LINE", "And you, the judges, bear a wary eye.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Come on, sir.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Come, my lord.") ), new XElement("STAGEDIR", "They play"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "One.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "No.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Judgment.") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "A hit, a very palpable hit.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Well; again.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Stay; give me drink. Hamlet, this pearl is thine;"), new XElement("LINE", "Here's to thy health."), new XElement("STAGEDIR", "Trumpets sound, and cannon shot off within"), new XElement("LINE", "Give him the cup.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I'll play this bout first; set it by awhile. Come."), new XElement("STAGEDIR", "They play"), new XElement("LINE", "Another hit; what say you?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "A touch, a touch, I do confess.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Our son shall win.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "He's fat, and scant of breath."), new XElement("LINE", "Here, Hamlet, take my napkin, rub thy brows;"), new XElement("LINE", "The queen carouses to thy fortune, Hamlet.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Good madam!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Gertrude, do not drink.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "I will, my lord; I pray you, pardon me.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " It is the poison'd cup: it is too late." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "I dare not drink yet, madam; by and by.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "Come, let me wipe thy face.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "My lord, I'll hit him now.") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "I do not think't.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", new XElement("STAGEDIR", "Aside"), " And yet 'tis almost 'gainst my conscience." ) ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Come, for the third, Laertes: you but dally;"), new XElement("LINE", "I pray you, pass with your best violence;"), new XElement("LINE", "I am afeard you make a wanton of me.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Say you so? come on.") ), new XElement("STAGEDIR", "They play"), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Nothing, neither way.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Have at you now!") ), new XElement("STAGEDIR", "LAERTES wounds HAMLET; then in scuffling, they\n" + "change rapiers, and HAMLET wounds LAERTES" ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "Part them; they are incensed.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Nay, come, again.") ), new XElement("STAGEDIR", "QUEEN GERTRUDE falls"), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Look to the queen there, ho!") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "They bleed on both sides. How is it, my lord?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "How is't, Laertes?") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "Why, as a woodcock to mine own springe, Osric;"), new XElement("LINE", "I am justly kill'd with mine own treachery.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "How does the queen?") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "She swounds to see them bleed.") ), new XElement("SPEECH", new XElement("SPEAKER", "QUEEN GERTRUDE"), new XElement("LINE", "No, no, the drink, the drink,--O my dear Hamlet,--"), new XElement("LINE", "The drink, the drink! I am poison'd.") ), new XElement("STAGEDIR", "Dies"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O villany! Ho! let the door be lock'd:"), new XElement("LINE", "Treachery! Seek it out.") ), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "It is here, Hamlet: Hamlet, thou art slain;"), new XElement("LINE", "No medicine in the world can do thee good;"), new XElement("LINE", "In thee there is not half an hour of life;"), new XElement("LINE", "The treacherous instrument is in thy hand,"), new XElement("LINE", "Unbated and envenom'd: the foul practise"), new XElement("LINE", "Hath turn'd itself on me lo, here I lie,"), new XElement("LINE", "Never to rise again: thy mother's poison'd:"), new XElement("LINE", "I can no more: the king, the king's to blame.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "The point!--envenom'd too!"), new XElement("LINE", "Then, venom, to thy work.") ), new XElement("STAGEDIR", "Stabs KING CLAUDIUS"), new XElement("SPEECH", new XElement("SPEAKER", "All"), new XElement("LINE", "Treason! treason!") ), new XElement("SPEECH", new XElement("SPEAKER", "KING CLAUDIUS"), new XElement("LINE", "O, yet defend me, friends; I am but hurt.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Here, thou incestuous, murderous, damned Dane,"), new XElement("LINE", "Drink off this potion. Is thy union here?"), new XElement("LINE", "Follow my mother.") ), new XElement("STAGEDIR", "KING CLAUDIUS dies"), new XElement("SPEECH", new XElement("SPEAKER", "LAERTES"), new XElement("LINE", "He is justly served;"), new XElement("LINE", "It is a poison temper'd by himself."), new XElement("LINE", "Exchange forgiveness with me, noble Hamlet:"), new XElement("LINE", "Mine and my father's death come not upon thee,"), new XElement("LINE", "Nor thine on me.") ), new XElement("STAGEDIR", "Dies"), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "Heaven make thee free of it! I follow thee."), new XElement("LINE", "I am dead, Horatio. Wretched queen, adieu!"), new XElement("LINE", "You that look pale and tremble at this chance,"), new XElement("LINE", "That are but mutes or audience to this act,"), new XElement("LINE", "Had I but time--as this fell sergeant, death,"), new XElement("LINE", "Is strict in his arrest--O, I could tell you--"), new XElement("LINE", "But let it be. Horatio, I am dead;"), new XElement("LINE", "Thou livest; report me and my cause aright"), new XElement("LINE", "To the unsatisfied.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Never believe it:"), new XElement("LINE", "I am more an antique Roman than a Dane:"), new XElement("LINE", "Here's yet some liquor left.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "As thou'rt a man,"), new XElement("LINE", "Give me the cup: let go; by heaven, I'll have't."), new XElement("LINE", "O good Horatio, what a wounded name,"), new XElement("LINE", "Things standing thus unknown, shall live behind me!"), new XElement("LINE", "If thou didst ever hold me in thy heart"), new XElement("LINE", "Absent thee from felicity awhile,"), new XElement("LINE", "And in this harsh world draw thy breath in pain,"), new XElement("LINE", "To tell my story."), new XElement("STAGEDIR", "March afar off, and shot within"), new XElement("LINE", "What warlike noise is this?") ), new XElement("SPEECH", new XElement("SPEAKER", "OSRIC"), new XElement("LINE", "Young Fortinbras, with conquest come from Poland,"), new XElement("LINE", "To the ambassadors of England gives"), new XElement("LINE", "This warlike volley.") ), new XElement("SPEECH", new XElement("SPEAKER", "HAMLET"), new XElement("LINE", "O, I die, Horatio;"), new XElement("LINE", "The potent poison quite o'er-crows my spirit:"), new XElement("LINE", "I cannot live to hear the news from England;"), new XElement("LINE", "But I do prophesy the election lights"), new XElement("LINE", "On Fortinbras: he has my dying voice;"), new XElement("LINE", "So tell him, with the occurrents, more and less,"), new XElement("LINE", "Which have solicited. The rest is silence.") ), new XElement("STAGEDIR", "Dies"), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Now cracks a noble heart. Good night sweet prince:"), new XElement("LINE", "And flights of angels sing thee to thy rest!"), new XElement("LINE", "Why does the drum come hither?") ), new XElement("STAGEDIR", "March within"), new XElement("STAGEDIR", "Enter FORTINBRAS, the English Ambassadors,\n" + "and others" ), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "Where is this sight?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "What is it ye would see?"), new XElement("LINE", "If aught of woe or wonder, cease your search.") ), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "This quarry cries on havoc. O proud death,"), new XElement("LINE", "What feast is toward in thine eternal cell,"), new XElement("LINE", "That thou so many princes at a shot"), new XElement("LINE", "So bloodily hast struck?") ), new XElement("SPEECH", new XElement("SPEAKER", "First Ambassador"), new XElement("LINE", "The sight is dismal;"), new XElement("LINE", "And our affairs from England come too late:"), new XElement("LINE", "The ears are senseless that should give us hearing,"), new XElement("LINE", "To tell him his commandment is fulfill'd,"), new XElement("LINE", "That Rosencrantz and Guildenstern are dead:"), new XElement("LINE", "Where should we have our thanks?") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Not from his mouth,"), new XElement("LINE", "Had it the ability of life to thank you:"), new XElement("LINE", "He never gave commandment for their death."), new XElement("LINE", "But since, so jump upon this bloody question,"), new XElement("LINE", "You from the Polack wars, and you from England,"), new XElement("LINE", "Are here arrived give order that these bodies"), new XElement("LINE", "High on a stage be placed to the view;"), new XElement("LINE", "And let me speak to the yet unknowing world"), new XElement("LINE", "How these things came about: so shall you hear"), new XElement("LINE", "Of carnal, bloody, and unnatural acts,"), new XElement("LINE", "Of accidental judgments, casual slaughters,"), new XElement("LINE", "Of deaths put on by cunning and forced cause,"), new XElement("LINE", "And, in this upshot, purposes mistook"), new XElement("LINE", "Fall'n on the inventors' reads: all this can I"), new XElement("LINE", "Truly deliver.") ), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "Let us haste to hear it,"), new XElement("LINE", "And call the noblest to the audience."), new XElement("LINE", "For me, with sorrow I embrace my fortune:"), new XElement("LINE", "I have some rights of memory in this kingdom,"), new XElement("LINE", "Which now to claim my vantage doth invite me.") ), new XElement("SPEECH", new XElement("SPEAKER", "HORATIO"), new XElement("LINE", "Of that I shall have also cause to speak,"), new XElement("LINE", "And from his mouth whose voice will draw on more;"), new XElement("LINE", "But let this same be presently perform'd,"), new XElement("LINE", "Even while men's minds are wild; lest more mischance"), new XElement("LINE", "On plots and errors, happen.") ), new XElement("SPEECH", new XElement("SPEAKER", "PRINCE FORTINBRAS"), new XElement("LINE", "Let four captains"), new XElement("LINE", "Bear Hamlet, like a soldier, to the stage;"), new XElement("LINE", "For he was likely, had he been put on,"), new XElement("LINE", "To have proved most royally: and, for his passage,"), new XElement("LINE", "The soldiers' music and the rites of war"), new XElement("LINE", "Speak loudly for him."), new XElement("LINE", "Take up the bodies: such a sight as this"), new XElement("LINE", "Becomes the field, but here shows much amiss."), new XElement("LINE", "Go, bid the soldiers shoot.") ), new XElement("STAGEDIR", "A dead march. Exeunt, bearing off the dead\n" + "bodies; after which a peal of ordnance is shot off") ) ) ) ); xmlDoc = XDocument.Parse(xDoc.ToString(SaveOptions.DisableFormatting)); } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Runtime.Loader/tests/ReferencedClassLibNeutralIsSatellite/ReferencedClassLibNeutralIsSatellite.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.Resources; using System.Globalization; [assembly:NeutralResourcesLanguage("es", UltimateResourceFallbackLocation.Satellite)] namespace ReferencedClassLibNeutralIsSatellite { public class Program { public static string Describe(string lang) { try { ResourceManager rm = new ResourceManager("ReferencedClassLibNeutralIsSatellite.ReferencedStrings", typeof(Program).Assembly); CultureInfo ci = CultureInfo.CreateSpecificCulture(lang); return rm.GetString("Describe", ci); } catch (Exception e) { return e.ToString(); } } } }
// 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.Resources; using System.Globalization; [assembly:NeutralResourcesLanguage("es", UltimateResourceFallbackLocation.Satellite)] namespace ReferencedClassLibNeutralIsSatellite { public class Program { public static string Describe(string lang) { try { ResourceManager rm = new ResourceManager("ReferencedClassLibNeutralIsSatellite.ReferencedStrings", typeof(Program).Assembly); CultureInfo ci = CultureInfo.CreateSpecificCulture(lang); return rm.GetString("Describe", ci); } catch (Exception e) { return e.ToString(); } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Threading.Tasks/tests/XunitAssemblyAttributes.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; [assembly: CollectionBehavior(CollectionBehavior.CollectionPerClass, DisableTestParallelization = true)]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; [assembly: CollectionBehavior(CollectionBehavior.CollectionPerClass, DisableTestParallelization = true)]
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/GC/Performance/Tests/ToBoxOrNotToBox.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 ToBoxOrNotToBox { public interface IObjectId { } internal class ClassObjectId : IObjectId { private int m_TypeId; private long m_InstanceId; public int TypeId { get { return m_TypeId; } set { m_TypeId = value; } } public long InstanceId { get { return m_InstanceId; } set { m_InstanceId = value; } } public ClassObjectId(int typeId, long instanceId) { m_TypeId = typeId; m_InstanceId = instanceId; } } internal struct InternalObjectId { private int m_TypeId; private long m_InstanceId; public int TypeId { get { return m_TypeId; } set { m_TypeId = value; } } public long InstanceId { get { return m_InstanceId; } set { m_InstanceId = value; } } public InternalObjectId(int typeId, long instanceId) { m_TypeId = typeId; m_InstanceId = instanceId; } } public struct ObjectId { private int m_TypeId; private long m_InstanceId; internal ObjectId(InternalObjectId id) { m_TypeId = id.TypeId; m_InstanceId = id.InstanceId; } } class Program { static void PerfTest2(int count, int length) { for (int i = 0; i < count; i++) { ClassObjectId[] internalIds = new ClassObjectId[length]; for (int k = 0; k < length; k++) { internalIds[k] = new ClassObjectId(10, k + 1); } IObjectId[] publicIds = new IObjectId[length]; Array.Copy(internalIds, publicIds, length); } } static void PerfTest1(int count, int length) { for (int i = 0; i < count; i++) { InternalObjectId[] internalIds = new InternalObjectId[length]; for (int k = 0; k < length; k++) { internalIds[k] = new InternalObjectId(10, k + 1); } ObjectId[] publicIds = new ObjectId[length]; for (int k = 0; k < length; k++) { publicIds[k] = new ObjectId(internalIds[k]); } } } static void Main(string[] args) { const int baseCount = 2000000; for (int i = 1; i <= 1000000; i+=10000) { int count = baseCount / i; PerfTest1(count, i); PerfTest2(count, i); } } } }
// 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 ToBoxOrNotToBox { public interface IObjectId { } internal class ClassObjectId : IObjectId { private int m_TypeId; private long m_InstanceId; public int TypeId { get { return m_TypeId; } set { m_TypeId = value; } } public long InstanceId { get { return m_InstanceId; } set { m_InstanceId = value; } } public ClassObjectId(int typeId, long instanceId) { m_TypeId = typeId; m_InstanceId = instanceId; } } internal struct InternalObjectId { private int m_TypeId; private long m_InstanceId; public int TypeId { get { return m_TypeId; } set { m_TypeId = value; } } public long InstanceId { get { return m_InstanceId; } set { m_InstanceId = value; } } public InternalObjectId(int typeId, long instanceId) { m_TypeId = typeId; m_InstanceId = instanceId; } } public struct ObjectId { private int m_TypeId; private long m_InstanceId; internal ObjectId(InternalObjectId id) { m_TypeId = id.TypeId; m_InstanceId = id.InstanceId; } } class Program { static void PerfTest2(int count, int length) { for (int i = 0; i < count; i++) { ClassObjectId[] internalIds = new ClassObjectId[length]; for (int k = 0; k < length; k++) { internalIds[k] = new ClassObjectId(10, k + 1); } IObjectId[] publicIds = new IObjectId[length]; Array.Copy(internalIds, publicIds, length); } } static void PerfTest1(int count, int length) { for (int i = 0; i < count; i++) { InternalObjectId[] internalIds = new InternalObjectId[length]; for (int k = 0; k < length; k++) { internalIds[k] = new InternalObjectId(10, k + 1); } ObjectId[] publicIds = new ObjectId[length]; for (int k = 0; k < length; k++) { publicIds[k] = new ObjectId(internalIds[k]); } } } static void Main(string[] args) { const int baseCount = 2000000; for (int i = 1; i <= 1000000; i+=10000) { int count = baseCount / i; PerfTest1(count, i); PerfTest2(count, i); } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Methodical/Boxing/functional/sin_il_r.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="sin.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="sin.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest696/Generated696.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 Generated696 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public G3_C1168`1<T0> extends class G2_C235`2<class BaseClass0,class BaseClass0> implements class IBase2`2<!T0,class BaseClass0> { .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "G3_C1168::Method7.14704<" 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 'G2_C235<class BaseClass0,class BaseClass0>.ClassMethod1811'() cil managed noinlining { .override method instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() ldstr "G3_C1168::ClassMethod1811.MI.14705()" ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G2_C235`2<class BaseClass0,class BaseClass0>::.ctor() ret } } .class public abstract G2_C235`2<T0, T1> extends class G1_C3`1<!T1> implements class IBase1`1<class BaseClass1>, class IBase2`2<!T1,!T0> { .method public hidebysig virtual instance string Method4() cil managed noinlining { ldstr "G2_C235::Method4.6935()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method4'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C235::Method4.MI.6936()" ret } .method public hidebysig virtual instance string Method5() cil managed noinlining { ldstr "G2_C235::Method5.6937()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C235::Method5.MI.6938()" ret } .method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining { ldstr "G2_C235::Method6.6939<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method6'<M0>() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method6<[1]>() ldstr "G2_C235::Method6.MI.6940<" 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 Method7<M0>() cil managed noinlining { ldstr "G2_C235::Method7.6941<" 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<T1,T0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<!T1,!T0>::Method7<[1]>() ldstr "G2_C235::Method7.MI.6942<" 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 ClassMethod1810() cil managed noinlining { ldstr "G2_C235::ClassMethod1810.6943()" ret } .method public hidebysig newslot virtual instance string ClassMethod1811() cil managed noinlining { ldstr "G2_C235::ClassMethod1811.6944()" ret } .method public hidebysig newslot virtual instance string 'G1_C3<T1>.ClassMethod1318'() cil managed noinlining { .override method instance string class G1_C3`1<!T1>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ret } .method public hidebysig newslot virtual instance string 'G1_C3<T1>.ClassMethod1319'<M0>() cil managed noinlining { .override method instance string class G1_C3`1<!T1>::ClassMethod1319<[1]>() ldstr "G2_C235::ClassMethod1319.MI.6946<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G1_C3`1<!T1>::.ctor() ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public G1_C3`1<T0> implements class IBase2`2<class BaseClass0,class BaseClass1> { .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "G1_C3::Method7.4785<" 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 BaseClass0,class BaseClass1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<[1]>() ldstr "G1_C3::Method7.MI.4786<" 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 ClassMethod1318() cil managed noinlining { ldstr "G1_C3::ClassMethod1318.4787()" ret } .method public hidebysig newslot virtual instance string ClassMethod1319<M0>() cil managed noinlining { ldstr "G1_C3::ClassMethod1319.4788<" 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 ClassMethod1320<M0>() cil managed noinlining { ldstr "G1_C3::ClassMethod1320.4789<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated696 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1168.T<T0,(class G3_C1168`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1168.T<T0,(class G3_C1168`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1168.A<(class G3_C1168`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1168.A<(class G3_C1168`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1168.B<(class G3_C1168`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1168.B<(class G3_C1168`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.T.T<T0,T1,(class G2_C235`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.T.T<T0,T1,(class G2_C235`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.A.T<T1,(class G2_C235`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.A.T<T1,(class G2_C235`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.A.A<(class G2_C235`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.A.A<(class G2_C235`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.A.B<(class G2_C235`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.A.B<(class G2_C235`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.B.T<T1,(class G2_C235`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.B.T<T1,(class G2_C235`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.B.A<(class G2_C235`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.B.A<(class G2_C235`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.B.B<(class G2_C235`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.B.B<(class G2_C235`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.T<T0,(class G1_C3`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.T<T0,(class G1_C3`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.A<(class G1_C3`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.A<(class G1_C3`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.B<(class G1_C3`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.B<(class G1_C3`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1168`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1810() ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C235::Method7.6941<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G2_C235::Method5.6937()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C235::Method4.6935()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1811() ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1810() ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::Method6<object>() ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::Method5() ldstr "G2_C235::Method5.6937()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::Method4() ldstr "G2_C235::Method4.6935()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G3_C1168`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1810() ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C235::Method7.6941<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G2_C235::Method5.6937()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C235::Method4.6935()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1811() ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1810() ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::Method6<object>() ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::Method5() ldstr "G2_C235::Method5.6937()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::Method4() ldstr "G2_C235::Method4.6935()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1168`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.T<class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.A<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1168`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass1,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.B<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.T.T<class BaseClass0,class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.A.T<class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.A.A<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.T<class BaseClass1,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.B<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.A<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.T<class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.A<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.G3_C1168.T<class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.G3_C1168.A<class G3_C1168`1<class BaseClass0>>(!!0,string) newobj instance void class G3_C1168`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.T<class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.A<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.B<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.T.T<class BaseClass0,class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.A.T<class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.A.A<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.T<class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.B<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.A<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.T<class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.A<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.G3_C1168.T<class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.G3_C1168.B<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.B.T<class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.B.A<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.B.T<class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.B.B<class G3_C1168`1<class BaseClass1>>(!!0,string) newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.T<class BaseClass0,class G1_C3`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.A<class G1_C3`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G1_C3`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass1,class G1_C3`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.A.B<class G1_C3`1<class BaseClass0>>(!!0,string) newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.T<class BaseClass1,class G1_C3`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.B<class G1_C3`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G1_C3`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass1,class G1_C3`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.A.B<class G1_C3`1<class BaseClass1>>(!!0,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1168`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1810() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method7.6941<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method5.6937()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method4.6935()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::ClassMethod1811() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::ClassMethod1810() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::Method5() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method5.6937()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::Method4() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method4.6935()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G3_C1168`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1810() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method7.6941<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method5.6937()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method4.6935()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::ClassMethod1811() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::ClassMethod1810() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::Method5() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method5.6937()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::Method4() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method4.6935()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated696::MethodCallingTest() call void Generated696::ConstrainedCallsTest() call void Generated696::StructConstrainedInterfaceCallsTest() call void Generated696::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 Generated696 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public G3_C1168`1<T0> extends class G2_C235`2<class BaseClass0,class BaseClass0> implements class IBase2`2<!T0,class BaseClass0> { .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "G3_C1168::Method7.14704<" 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 'G2_C235<class BaseClass0,class BaseClass0>.ClassMethod1811'() cil managed noinlining { .override method instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() ldstr "G3_C1168::ClassMethod1811.MI.14705()" ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G2_C235`2<class BaseClass0,class BaseClass0>::.ctor() ret } } .class public abstract G2_C235`2<T0, T1> extends class G1_C3`1<!T1> implements class IBase1`1<class BaseClass1>, class IBase2`2<!T1,!T0> { .method public hidebysig virtual instance string Method4() cil managed noinlining { ldstr "G2_C235::Method4.6935()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method4'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C235::Method4.MI.6936()" ret } .method public hidebysig virtual instance string Method5() cil managed noinlining { ldstr "G2_C235::Method5.6937()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C235::Method5.MI.6938()" ret } .method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining { ldstr "G2_C235::Method6.6939<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass1>.Method6'<M0>() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass1>::Method6<[1]>() ldstr "G2_C235::Method6.MI.6940<" 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 Method7<M0>() cil managed noinlining { ldstr "G2_C235::Method7.6941<" 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<T1,T0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<!T1,!T0>::Method7<[1]>() ldstr "G2_C235::Method7.MI.6942<" 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 ClassMethod1810() cil managed noinlining { ldstr "G2_C235::ClassMethod1810.6943()" ret } .method public hidebysig newslot virtual instance string ClassMethod1811() cil managed noinlining { ldstr "G2_C235::ClassMethod1811.6944()" ret } .method public hidebysig newslot virtual instance string 'G1_C3<T1>.ClassMethod1318'() cil managed noinlining { .override method instance string class G1_C3`1<!T1>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ret } .method public hidebysig newslot virtual instance string 'G1_C3<T1>.ClassMethod1319'<M0>() cil managed noinlining { .override method instance string class G1_C3`1<!T1>::ClassMethod1319<[1]>() ldstr "G2_C235::ClassMethod1319.MI.6946<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G1_C3`1<!T1>::.ctor() ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public G1_C3`1<T0> implements class IBase2`2<class BaseClass0,class BaseClass1> { .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "G1_C3::Method7.4785<" 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 BaseClass0,class BaseClass1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<[1]>() ldstr "G1_C3::Method7.MI.4786<" 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 ClassMethod1318() cil managed noinlining { ldstr "G1_C3::ClassMethod1318.4787()" ret } .method public hidebysig newslot virtual instance string ClassMethod1319<M0>() cil managed noinlining { ldstr "G1_C3::ClassMethod1319.4788<" 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 ClassMethod1320<M0>() cil managed noinlining { ldstr "G1_C3::ClassMethod1320.4789<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated696 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1168.T<T0,(class G3_C1168`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1168.T<T0,(class G3_C1168`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1168.A<(class G3_C1168`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1168.A<(class G3_C1168`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1168.B<(class G3_C1168`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1168.B<(class G3_C1168`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1168`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.T.T<T0,T1,(class G2_C235`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.T.T<T0,T1,(class G2_C235`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.A.T<T1,(class G2_C235`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.A.T<T1,(class G2_C235`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.A.A<(class G2_C235`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.A.A<(class G2_C235`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.A.B<(class G2_C235`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.A.B<(class G2_C235`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.B.T<T1,(class G2_C235`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.B.T<T1,(class G2_C235`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.B.A<(class G2_C235`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.B.A<(class G2_C235`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C235.B.B<(class G2_C235`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 14 .locals init (string[] actualResults) ldc.i4.s 9 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C235.B.B<(class G2_C235`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 9 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::ClassMethod1810() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::ClassMethod1811() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G2_C235`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.T<T0,(class G1_C3`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.T<T0,(class G1_C3`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.A<(class G1_C3`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.A<(class G1_C3`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.B<(class G1_C3`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.B<(class G1_C3`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1168`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1810() ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C235::Method7.6941<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G2_C235::Method5.6937()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C235::Method4.6935()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1811() ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1810() ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::Method6<object>() ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::Method5() ldstr "G2_C235::Method5.6937()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::Method4() ldstr "G2_C235::Method4.6935()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass0> callvirt instance string class G3_C1168`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G3_C1168`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1810() ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C235::Method7.6941<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method5() ldstr "G2_C235::Method5.6937()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method4() ldstr "G2_C235::Method4.6935()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C235`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass1>::Method4() ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method5() ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1811() ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1810() ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::Method6<object>() ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::Method5() ldstr "G2_C235::Method5.6937()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::Method4() ldstr "G2_C235::Method4.6935()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1168`1<class BaseClass1> callvirt instance string class G3_C1168`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1168`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.T<class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.A<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1168`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass1,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.B<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.T.T<class BaseClass0,class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.A.T<class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.A.A<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.T<class BaseClass1,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.B<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.A<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.T<class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.A<class G3_C1168`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.G3_C1168.T<class BaseClass0,class G3_C1168`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.G3_C1168.A<class G3_C1168`1<class BaseClass0>>(!!0,string) newobj instance void class G3_C1168`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.T<class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.A<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.B<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.T.T<class BaseClass0,class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.A.T<class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G2_C235::Method7.6941<System.Object>()#" call void Generated696::M.G2_C235.A.A<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.T<class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.B<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.A.A<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.T<class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C235::Method4.MI.6936()#G2_C235::Method5.MI.6938()#G2_C235::Method6.MI.6940<System.Object>()#" call void Generated696::M.IBase1.A<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.G3_C1168.T<class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C235::ClassMethod1318.MI.6945()#G2_C235::ClassMethod1319.MI.6946<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G2_C235::ClassMethod1810.6943()#G3_C1168::ClassMethod1811.MI.14705()#G2_C235::Method4.6935()#G2_C235::Method5.6937()#G2_C235::Method6.6939<System.Object>()#G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.G3_C1168.B<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass1,class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.B.T<class BaseClass0,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.B.A<class G3_C1168`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.B.T<class BaseClass1,class G3_C1168`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G3_C1168::Method7.14704<System.Object>()#" call void Generated696::M.IBase2.B.B<class G3_C1168`1<class BaseClass1>>(!!0,string) newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.T<class BaseClass0,class G1_C3`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.A<class G1_C3`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G1_C3`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass1,class G1_C3`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.A.B<class G1_C3`1<class BaseClass0>>(!!0,string) newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.T<class BaseClass1,class G1_C3`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated696::M.G1_C3.B<class G1_C3`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G1_C3`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.A.T<class BaseClass1,class G1_C3`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated696::M.IBase2.A.B<class G1_C3`1<class BaseClass1>>(!!0,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1168`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1810() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method7.6941<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method5.6937()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method4.6935()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::ClassMethod1811() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::ClassMethod1810() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::Method5() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method5.6937()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::Method4() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::Method4.6935()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass0>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass0>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G3_C1168`1<class BaseClass0> on type class G3_C1168`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G3_C1168`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1811() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1810() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method7.6941<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method5() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method5.6937()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::Method4() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method4.6935()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C235`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C235`2<class BaseClass0,class BaseClass0>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G2_C235`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method4() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method5() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method4.MI.6936()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method5.MI.6938()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method6.MI.6940<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::ClassMethod1811() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::ClassMethod1811.MI.14705()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::ClassMethod1810() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1810.6943()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::Method6<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method6.6939<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::Method5() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method5.6937()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::Method4() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::Method4.6935()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1319.MI.6946<System.Object>()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1168`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1168`1<class BaseClass1>::ClassMethod1318() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G2_C235::ClassMethod1318.MI.6945()" ldstr "class G3_C1168`1<class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1168`1<class BaseClass1>) ldstr "G3_C1168::Method7.14704<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1168`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated696::MethodCallingTest() call void Generated696::ConstrainedCallsTest() call void Generated696::StructConstrainedInterfaceCallsTest() call void Generated696::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Or.Vector64.UInt64.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 Or_Vector64_UInt64() { var test = new SimpleBinaryOpTest__Or_Vector64_UInt64(); 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__Or_Vector64_UInt64 { 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(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); 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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1; public Vector64<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Or_Vector64_UInt64 testClass) { var result = AdvSimd.Or(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Or_Vector64_UInt64 testClass) { fixed (Vector64<UInt64>* pFld1 = &_fld1) fixed (Vector64<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Or( AdvSimd.LoadVector64((UInt64*)(pFld1)), AdvSimd.LoadVector64((UInt64*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector64<UInt64> _clsVar1; private static Vector64<UInt64> _clsVar2; private Vector64<UInt64> _fld1; private Vector64<UInt64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Or_Vector64_UInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); } public SimpleBinaryOpTest__Or_Vector64_UInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt64[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.Or( Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt64>>(_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.Or( AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt64*)(_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.Or), new Type[] { typeof(Vector64<UInt64>), typeof(Vector64<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt64>)(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.Or), new Type[] { typeof(Vector64<UInt64>), typeof(Vector64<UInt64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Or( AdvSimd.LoadVector64((UInt64*)(pClsVar1)), AdvSimd.LoadVector64((UInt64*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray2Ptr); var result = AdvSimd.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Or_Vector64_UInt64(); var result = AdvSimd.Or(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__Or_Vector64_UInt64(); fixed (Vector64<UInt64>* pFld1 = &test._fld1) fixed (Vector64<UInt64>* pFld2 = &test._fld2) { var result = AdvSimd.Or( AdvSimd.LoadVector64((UInt64*)(pFld1)), AdvSimd.LoadVector64((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt64>* pFld1 = &_fld1) fixed (Vector64<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Or( AdvSimd.LoadVector64((UInt64*)(pFld1)), AdvSimd.LoadVector64((UInt64*)(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.Or(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.Or( AdvSimd.LoadVector64((UInt64*)(&test._fld1)), AdvSimd.LoadVector64((UInt64*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<UInt64> op1, Vector64<UInt64> op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Or(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Or)}<UInt64>(Vector64<UInt64>, Vector64<UInt64>): {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 Or_Vector64_UInt64() { var test = new SimpleBinaryOpTest__Or_Vector64_UInt64(); 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__Or_Vector64_UInt64 { 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(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); 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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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<UInt64> _fld1; public Vector64<UInt64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Or_Vector64_UInt64 testClass) { var result = AdvSimd.Or(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Or_Vector64_UInt64 testClass) { fixed (Vector64<UInt64>* pFld1 = &_fld1) fixed (Vector64<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Or( AdvSimd.LoadVector64((UInt64*)(pFld1)), AdvSimd.LoadVector64((UInt64*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector64<UInt64> _clsVar1; private static Vector64<UInt64> _clsVar2; private Vector64<UInt64> _fld1; private Vector64<UInt64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Or_Vector64_UInt64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); } public SimpleBinaryOpTest__Or_Vector64_UInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data2, new UInt64[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.Or( Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt64>>(_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.Or( AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt64*)(_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.Or), new Type[] { typeof(Vector64<UInt64>), typeof(Vector64<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt64>)(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.Or), new Type[] { typeof(Vector64<UInt64>), typeof(Vector64<UInt64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Or( AdvSimd.LoadVector64((UInt64*)(pClsVar1)), AdvSimd.LoadVector64((UInt64*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray2Ptr); var result = AdvSimd.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Or_Vector64_UInt64(); var result = AdvSimd.Or(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__Or_Vector64_UInt64(); fixed (Vector64<UInt64>* pFld1 = &test._fld1) fixed (Vector64<UInt64>* pFld2 = &test._fld2) { var result = AdvSimd.Or( AdvSimd.LoadVector64((UInt64*)(pFld1)), AdvSimd.LoadVector64((UInt64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt64>* pFld1 = &_fld1) fixed (Vector64<UInt64>* pFld2 = &_fld2) { var result = AdvSimd.Or( AdvSimd.LoadVector64((UInt64*)(pFld1)), AdvSimd.LoadVector64((UInt64*)(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.Or(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.Or( AdvSimd.LoadVector64((UInt64*)(&test._fld1)), AdvSimd.LoadVector64((UInt64*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<UInt64> op1, Vector64<UInt64> op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Or(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Or)}<UInt64>(Vector64<UInt64>, Vector64<UInt64>): {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,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApi/XmlResolver_Sub.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="Dummy"> <result>Nothing fancy in here</result> </xsl:template> </xsl:stylesheet>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="Dummy"> <result>Nothing fancy in here</result> </xsl:template> </xsl:stylesheet>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/coreclr/md/export.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // File: export.h // // // Popular types/macros defined in MetaData directory (no subdirectories). // It's supposed to be included from other subcomponents (i.e. subdirectories), not from this directory. // // ====================================================================================== #pragma once #include "debug_metadata.h" #include "errors_metadata.h" #include "datablob.h"
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // File: export.h // // // Popular types/macros defined in MetaData directory (no subdirectories). // It's supposed to be included from other subcomponents (i.e. subdirectories), not from this directory. // // ====================================================================================== #pragma once #include "debug_metadata.h" #include "errors_metadata.h" #include "datablob.h"
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/Regressions/coreclr/16371/ptrarray.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ptrarray.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ptrarray.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Directed/coverage/oldtests/ovfldiv2.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 { } .assembly extern xunit.core {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly ovfldiv2 {} .class private auto ansi beforefieldinit ovfldiv2 extends [mscorlib]System.Object { .method private hidebysig static int32 Main(string[] args) cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 ldc.i4 0x80000000 conv.u4 ldc.i4 1 div dup call void [System.Console]System.Console::WriteLine(int32) //ldc.i4 0xFFFFFFFF80000000 ldc.i4 0x80000000 ceq brfalse FAIL ldc.i4 0xFFFFFFFF conv.u4 ldc.i4 1 div dup call void [System.Console]System.Console::WriteLine(int32) ldc.i4.m1 ceq brfalse FAIL ldc.i4 0x79999999 conv.u4 ldc.i4.m1 div dup call void [System.Console]System.Console::WriteLine(int32) //ldc.i4 0xFFFFFFFF86666667 ldc.i4 0x86666667 ceq brfalse FAIL .try { ldc.i4 0x80000000 conv.u4 ldc.i4.m1 div leave FAIL } catch [mscorlib]System.OverflowException { leave PASS } PASS: ldstr "PASSED" call void [System.Console]System.Console::WriteLine(string) ldc.i4 100 ret FAIL: ldstr "FAILED" call void [System.Console]System.Console::WriteLine(string) ldc.i4 1 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 { } .assembly extern xunit.core {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly ovfldiv2 {} .class private auto ansi beforefieldinit ovfldiv2 extends [mscorlib]System.Object { .method private hidebysig static int32 Main(string[] args) cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 ldc.i4 0x80000000 conv.u4 ldc.i4 1 div dup call void [System.Console]System.Console::WriteLine(int32) //ldc.i4 0xFFFFFFFF80000000 ldc.i4 0x80000000 ceq brfalse FAIL ldc.i4 0xFFFFFFFF conv.u4 ldc.i4 1 div dup call void [System.Console]System.Console::WriteLine(int32) ldc.i4.m1 ceq brfalse FAIL ldc.i4 0x79999999 conv.u4 ldc.i4.m1 div dup call void [System.Console]System.Console::WriteLine(int32) //ldc.i4 0xFFFFFFFF86666667 ldc.i4 0x86666667 ceq brfalse FAIL .try { ldc.i4 0x80000000 conv.u4 ldc.i4.m1 div leave FAIL } catch [mscorlib]System.OverflowException { leave PASS } PASS: ldstr "PASSED" call void [System.Console]System.Console::WriteLine(string) ldc.i4 100 ret FAIL: ldstr "FAILED" call void [System.Console]System.Console::WriteLine(string) ldc.i4 1 ret } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CertStrToName.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; internal static partial class Interop { internal static partial class Crypt32 { [GeneratedDllImport(Libraries.Crypt32, EntryPoint = "CertStrToNameW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool CertStrToName(CertEncodingType dwCertEncodingType, string pszX500, CertNameStrTypeAndFlags dwStrType, IntPtr pvReserved, byte[]? pbEncoded, ref int pcbEncoded, IntPtr ppszError); } }
// 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; internal static partial class Interop { internal static partial class Crypt32 { [GeneratedDllImport(Libraries.Crypt32, EntryPoint = "CertStrToNameW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool CertStrToName(CertEncodingType dwCertEncodingType, string pszX500, CertNameStrTypeAndFlags dwStrType, IntPtr pvReserved, byte[]? pbEncoded, ref int pcbEncoded, IntPtr ppszError); } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/jit64/valuetypes/nullable/castclass/interface/castclass-interface008.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)(IComparable)o, Helper.Create(default(byte))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((byte?)(IComparable)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)(IComparable)o, Helper.Create(default(byte))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((byte?)(IComparable)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,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Methodical/switch/switch7.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="switch7.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="switch7.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Methodical/explicit/rotate/rotarg_double_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="rotarg_double.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="rotarg_double.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M01/b12425/b12425.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="test_17.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="test_17.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/FixupRuntimeTypeHandle.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 Internal.Runtime; namespace Internal.Runtime.CompilerServices { public unsafe struct FixupRuntimeTypeHandle { private IntPtr _value; public FixupRuntimeTypeHandle(RuntimeTypeHandle runtimeTypeHandle) { _value = *(IntPtr*)&runtimeTypeHandle; } public RuntimeTypeHandle RuntimeTypeHandle { get { // Managed debugger uses this logic to figure out the interface's type // Update managed debugger too whenever this is changed. // See CordbObjectValue::WalkPtrAndTypeData in debug\dbi\values.cpp if (((_value.ToInt64()) & IndirectionConstants.IndirectionCellPointer) != 0) { return *(RuntimeTypeHandle*)(_value.ToInt64() - IndirectionConstants.IndirectionCellPointer); } else { RuntimeTypeHandle returnValue = default(RuntimeTypeHandle); *(IntPtr*)&returnValue = _value; return returnValue; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Internal.Runtime; namespace Internal.Runtime.CompilerServices { public unsafe struct FixupRuntimeTypeHandle { private IntPtr _value; public FixupRuntimeTypeHandle(RuntimeTypeHandle runtimeTypeHandle) { _value = *(IntPtr*)&runtimeTypeHandle; } public RuntimeTypeHandle RuntimeTypeHandle { get { // Managed debugger uses this logic to figure out the interface's type // Update managed debugger too whenever this is changed. // See CordbObjectValue::WalkPtrAndTypeData in debug\dbi\values.cpp if (((_value.ToInt64()) & IndirectionConstants.IndirectionCellPointer) != 0) { return *(RuntimeTypeHandle*)(_value.ToInt64() - IndirectionConstants.IndirectionCellPointer); } else { RuntimeTypeHandle returnValue = default(RuntimeTypeHandle); *(IntPtr*)&returnValue = _value; return returnValue; } } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/SIMD/VectorHWAccel.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.Numerics; internal partial class VectorTest { private const int Pass = 100; private const int Fail = -1; private class VectorHWAccelTest<T> where T : struct, IComparable<T>, IEquatable<T> { public static int VectorHWAccel(T a, T b, T c) { if (Vector.IsHardwareAccelerated) { Vector<T> A = new Vector<T>(a); Vector<T> B = new Vector<T>(b); Vector<T> C = A + B; for (int i = 0; i < Vector<T>.Count; i++) { if (!(CheckValue<T>(C[i], c))) { return Fail; } } return Pass; } else { return Pass; } } } private static int Main() { int returnVal = Pass; if (VectorHWAccelTest<float>.VectorHWAccel(1, 2, (float)(1 + 2)) != Pass) returnVal = Fail; return returnVal; } }
// 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.Numerics; internal partial class VectorTest { private const int Pass = 100; private const int Fail = -1; private class VectorHWAccelTest<T> where T : struct, IComparable<T>, IEquatable<T> { public static int VectorHWAccel(T a, T b, T c) { if (Vector.IsHardwareAccelerated) { Vector<T> A = new Vector<T>(a); Vector<T> B = new Vector<T>(b); Vector<T> C = A + B; for (int i = 0; i < Vector<T>.Count; i++) { if (!(CheckValue<T>(C[i], c))) { return Fail; } } return Pass; } else { return Pass; } } } private static int Main() { int returnVal = Pass; if (VectorHWAccelTest<float>.VectorHWAccel(1, 2, (float)(1 + 2)) != Pass) returnVal = Fail; return returnVal; } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/EnumConverterTests.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.IO; using System.Threading.Tasks; using Xunit; namespace System.Text.Json.Serialization.Tests { public class EnumConverterTests { [Fact] public void ConvertDayOfWeek() { JsonSerializerOptions options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); WhenClass when = JsonSerializer.Deserialize<WhenClass>(@"{""Day"":""Monday""}", options); Assert.Equal(DayOfWeek.Monday, when.Day); DayOfWeek day = JsonSerializer.Deserialize<DayOfWeek>(@"""Tuesday""", options); Assert.Equal(DayOfWeek.Tuesday, day); // We are case insensitive on read day = JsonSerializer.Deserialize<DayOfWeek>(@"""wednesday""", options); Assert.Equal(DayOfWeek.Wednesday, day); // Numbers work by default day = JsonSerializer.Deserialize<DayOfWeek>(@"4", options); Assert.Equal(DayOfWeek.Thursday, day); string json = JsonSerializer.Serialize(DayOfWeek.Friday, options); Assert.Equal(@"""Friday""", json); // Try a unique naming policy options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter(new ToLowerNamingPolicy())); json = JsonSerializer.Serialize(DayOfWeek.Friday, options); Assert.Equal(@"""friday""", json); // Undefined values should come out as a number (not a string) json = JsonSerializer.Serialize((DayOfWeek)(-1), options); Assert.Equal(@"-1", json); // Not permitting integers should throw options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false)); Assert.Throws<JsonException>(() => JsonSerializer.Serialize((DayOfWeek)(-1), options)); } public class ToLowerNamingPolicy : JsonNamingPolicy { public override string ConvertName(string name) => name.ToLowerInvariant(); } public class WhenClass { public DayOfWeek Day { get; set; } } [Fact] public void ConvertFileAttributes() { JsonSerializerOptions options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); FileState state = JsonSerializer.Deserialize<FileState>(@"{""Attributes"":""ReadOnly""}", options); Assert.Equal(FileAttributes.ReadOnly, state.Attributes); state = JsonSerializer.Deserialize<FileState>(@"{""Attributes"":""Directory, ReparsePoint""}", options); Assert.Equal(FileAttributes.Directory | FileAttributes.ReparsePoint, state.Attributes); FileAttributes attributes = JsonSerializer.Deserialize<FileAttributes>(@"""Normal""", options); Assert.Equal(FileAttributes.Normal, attributes); attributes = JsonSerializer.Deserialize<FileAttributes>(@"""System, SparseFile""", options); Assert.Equal(FileAttributes.System | FileAttributes.SparseFile, attributes); // We are case insensitive on read attributes = JsonSerializer.Deserialize<FileAttributes>(@"""OFFLINE""", options); Assert.Equal(FileAttributes.Offline, attributes); attributes = JsonSerializer.Deserialize<FileAttributes>(@"""compressed, notcontentindexed""", options); Assert.Equal(FileAttributes.Compressed | FileAttributes.NotContentIndexed, attributes); // Numbers are cool by default attributes = JsonSerializer.Deserialize<FileAttributes>(@"131072", options); Assert.Equal(FileAttributes.NoScrubData, attributes); attributes = JsonSerializer.Deserialize<FileAttributes>(@"3", options); Assert.Equal(FileAttributes.Hidden | FileAttributes.ReadOnly, attributes); string json = JsonSerializer.Serialize(FileAttributes.Hidden, options); Assert.Equal(@"""Hidden""", json); json = JsonSerializer.Serialize(FileAttributes.Temporary | FileAttributes.Offline, options); Assert.Equal(@"""Temporary, Offline""", json); // Try a unique casing options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter(new ToLowerNamingPolicy())); json = JsonSerializer.Serialize(FileAttributes.NoScrubData, options); Assert.Equal(@"""noscrubdata""", json); json = JsonSerializer.Serialize(FileAttributes.System | FileAttributes.Offline, options); Assert.Equal(@"""system, offline""", json); // Undefined values should come out as a number (not a string) json = JsonSerializer.Serialize((FileAttributes)(-1), options); Assert.Equal(@"-1", json); // Not permitting integers should throw options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false)); Assert.Throws<JsonException>(() => JsonSerializer.Serialize((FileAttributes)(-1), options)); // Flag values honor naming policy correctly options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter(new SimpleSnakeCasePolicy())); json = JsonSerializer.Serialize( FileAttributes.Directory | FileAttributes.Compressed | FileAttributes.IntegrityStream, options); Assert.Equal(@"""directory, compressed, integrity_stream""", json); json = JsonSerializer.Serialize(FileAttributes.Compressed & FileAttributes.Device, options); Assert.Equal(@"0", json); json = JsonSerializer.Serialize(FileAttributes.Directory & FileAttributes.Compressed | FileAttributes.IntegrityStream, options); Assert.Equal(@"""integrity_stream""", json); } public class FileState { public FileAttributes Attributes { get; set; } } public class Week { [JsonConverter(typeof(JsonStringEnumConverter))] public DayOfWeek WorkStart { get; set; } public DayOfWeek WorkEnd { get; set; } [JsonConverter(typeof(LowerCaseEnumConverter))] public DayOfWeek WeekEnd { get; set; } } private class LowerCaseEnumConverter : JsonStringEnumConverter { public LowerCaseEnumConverter() : base(new ToLowerNamingPolicy()) { } } [Fact] public void ConvertEnumUsingAttributes() { Week week = new Week { WorkStart = DayOfWeek.Monday, WorkEnd = DayOfWeek.Friday, WeekEnd = DayOfWeek.Saturday }; string json = JsonSerializer.Serialize(week); Assert.Equal(@"{""WorkStart"":""Monday"",""WorkEnd"":5,""WeekEnd"":""saturday""}", json); week = JsonSerializer.Deserialize<Week>(json); Assert.Equal(DayOfWeek.Monday, week.WorkStart); Assert.Equal(DayOfWeek.Friday, week.WorkEnd); Assert.Equal(DayOfWeek.Saturday, week.WeekEnd); } [Fact] public void EnumConverterComposition() { JsonSerializerOptions options = new JsonSerializerOptions { Converters = { new NoFlagsStringEnumConverter() } }; string json = JsonSerializer.Serialize(DayOfWeek.Monday, options); Assert.Equal(@"""Monday""", json); json = JsonSerializer.Serialize(FileAccess.Read); Assert.Equal(@"1", json); } public class NoFlagsStringEnumConverter : JsonConverterFactory { private static JsonStringEnumConverter s_stringEnumConverter = new JsonStringEnumConverter(); public override bool CanConvert(Type typeToConvert) => typeToConvert.IsEnum && !typeToConvert.IsDefined(typeof(FlagsAttribute), inherit: false); public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => s_stringEnumConverter.CreateConverter(typeToConvert, options); } [JsonConverter(typeof(JsonStringEnumConverter))] private enum MyCustomEnum { First = 1, Second = 2 } [Fact] public void EnumWithConverterAttribute() { string json = JsonSerializer.Serialize(MyCustomEnum.Second); Assert.Equal(@"""Second""", json); MyCustomEnum obj = JsonSerializer.Deserialize<MyCustomEnum>("\"Second\""); Assert.Equal(MyCustomEnum.Second, obj); obj = JsonSerializer.Deserialize<MyCustomEnum>("2"); Assert.Equal(MyCustomEnum.Second, obj); } [Fact] public static void EnumWithNoValues() { var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } }; Assert.Equal("-1", JsonSerializer.Serialize((EmptyEnum)(-1), options)); Assert.Equal("1", JsonSerializer.Serialize((EmptyEnum)(1), options)); } public enum EmptyEnum { }; [Fact] public static void MoreThan64EnumValuesToSerialize() { var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } }; for (int i = 0; i < 128; i++) { MyEnum value = (MyEnum)i; string asStr = value.ToString(); string expected = char.IsLetter(asStr[0]) ? $@"""{asStr}""" : asStr; Assert.Equal(expected, JsonSerializer.Serialize(value, options)); } } [Fact] public static void MoreThan64EnumValuesToSerializeWithNamingPolicy() { var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter(new ToLowerNamingPolicy()) } }; for (int i = 0; i < 128; i++) { MyEnum value = (MyEnum)i; string asStr = value.ToString().ToLowerInvariant(); string expected = char.IsLetter(asStr[0]) ? $@"""{asStr}""" : asStr; Assert.Equal(expected, JsonSerializer.Serialize(value, options)); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [OuterLoop] public static void VeryLargeAmountOfEnumsToSerialize() { // Ensure we don't throw OutOfMemoryException. var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } }; const int MaxValue = 2097152; // value for MyEnum.V // Every value between 0 and MaxValue maps to a valid enum // identifier, and is a candidate to go into the name cache. // Write the first 45 values. for (int i = 1; i < 46; i++) { JsonSerializer.Serialize((MyEnum)i, options); } // At this point, there are 60 values in the name cache; // 22 cached at warm-up, the rest in the above loop. // Ensure the approximate size limit for the name cache (a concurrent dictionary) is honored. // Use multiple threads to perhaps go over the soft limit of 64, but not by more than a couple. Parallel.For(0, 8, i => JsonSerializer.Serialize((MyEnum)(46 + i), options)); // Write the remaining enum values. The cache is capped to avoid // OutOfMemoryException due to having too many cached items. for (int i = 54; i <= MaxValue; i++) { JsonSerializer.Serialize((MyEnum)i, options); } } [Flags] public enum MyEnum { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, H = 1 << 7, I = 1 << 8, J = 1 << 9, K = 1 << 10, L = 1 << 11, M = 1 << 12, N = 1 << 13, O = 1 << 14, P = 1 << 15, Q = 1 << 16, R = 1 << 17, S = 1 << 18, T = 1 << 19, U = 1 << 20, V = 1 << 21, } [Fact, OuterLoop] [ActiveIssue("https://github.com/dotnet/runtime/issues/42677", platforms: TestPlatforms.Windows, runtimes: TestRuntimes.Mono)] public static void VeryLargeAmountOfEnumDictionaryKeysToSerialize() { // Ensure we don't throw OutOfMemoryException. const int MaxValue = (int)MyEnum.V; // Every value between 0 and MaxValue maps to a valid enum // identifier, and is a candidate to go into the name cache. // Write the first 45 values. Dictionary<MyEnum, int> dictionary; for (int i = 1; i < 46; i++) { dictionary = new Dictionary<MyEnum, int> { { (MyEnum)i, i } }; JsonSerializer.Serialize(dictionary); } // At this point, there are 60 values in the name cache; // 22 cached at warm-up, the rest in the above loop. // Ensure the approximate size limit for the name cache (a concurrent dictionary) is honored. // Use multiple threads to perhaps go over the soft limit of 64, but not by more than a couple. Parallel.For( 0, 8, i => { dictionary = new Dictionary<MyEnum, int> { { (MyEnum)(46 + i), i } }; JsonSerializer.Serialize(dictionary); } ); // Write the remaining enum values. The cache is capped to avoid // OutOfMemoryException due to having too many cached items. for (int i = 54; i <= MaxValue; i++) { dictionary = new Dictionary<MyEnum, int> { { (MyEnum)i, i } }; JsonSerializer.Serialize(dictionary); } } public abstract class NumericEnumKeyDictionaryBase<T> { public abstract Dictionary<T, int> BuildDictionary(int i); [Fact] public void SerilizeDictionaryWhenCacheIsFull() { Dictionary<T, int> dictionary; for (int i = 1; i <= 64; i++) { dictionary = BuildDictionary(i); JsonSerializer.Serialize(dictionary); } dictionary = BuildDictionary(0); string json = JsonSerializer.Serialize(dictionary); Assert.Equal($"{{\"0\":0}}", json); } } public class Int32EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumInt32> { public override Dictionary<SampleEnumInt32, int> BuildDictionary(int i) => new Dictionary<SampleEnumInt32, int> { { (SampleEnumInt32)i, i } }; } public class UInt32EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumUInt32> { public override Dictionary<SampleEnumUInt32, int> BuildDictionary(int i) => new Dictionary<SampleEnumUInt32, int> { { (SampleEnumUInt32)i, i } }; } public class UInt64EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumUInt64> { public override Dictionary<SampleEnumUInt64, int> BuildDictionary(int i) => new Dictionary<SampleEnumUInt64, int> { { (SampleEnumUInt64)i, i } }; } public class Int64EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumInt64> { public override Dictionary<SampleEnumInt64, int> BuildDictionary(int i) => new Dictionary<SampleEnumInt64, int> { { (SampleEnumInt64)i, i } }; } public class Int16EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumInt16> { public override Dictionary<SampleEnumInt16, int> BuildDictionary(int i) => new Dictionary<SampleEnumInt16, int> { { (SampleEnumInt16)i, i } }; } public class UInt16EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumUInt16> { public override Dictionary<SampleEnumUInt16, int> BuildDictionary(int i) => new Dictionary<SampleEnumUInt16, int> { { (SampleEnumUInt16)i, i } }; } public class ByteEnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumByte> { public override Dictionary<SampleEnumByte, int> BuildDictionary(int i) => new Dictionary<SampleEnumByte, int> { { (SampleEnumByte)i, i } }; } public class SByteEnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumSByte> { public override Dictionary<SampleEnumSByte, int> BuildDictionary(int i) => new Dictionary<SampleEnumSByte, int> { { (SampleEnumSByte)i, i } }; } [Flags] public enum SampleEnumInt32 { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumUInt32 : uint { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumUInt64 : ulong { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumInt64 : long { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumInt16 : short { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumUInt16 : ushort { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumByte : byte { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumSByte : sbyte { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } } }
// 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.IO; using System.Threading.Tasks; using Xunit; namespace System.Text.Json.Serialization.Tests { public class EnumConverterTests { [Fact] public void ConvertDayOfWeek() { JsonSerializerOptions options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); WhenClass when = JsonSerializer.Deserialize<WhenClass>(@"{""Day"":""Monday""}", options); Assert.Equal(DayOfWeek.Monday, when.Day); DayOfWeek day = JsonSerializer.Deserialize<DayOfWeek>(@"""Tuesday""", options); Assert.Equal(DayOfWeek.Tuesday, day); // We are case insensitive on read day = JsonSerializer.Deserialize<DayOfWeek>(@"""wednesday""", options); Assert.Equal(DayOfWeek.Wednesday, day); // Numbers work by default day = JsonSerializer.Deserialize<DayOfWeek>(@"4", options); Assert.Equal(DayOfWeek.Thursday, day); string json = JsonSerializer.Serialize(DayOfWeek.Friday, options); Assert.Equal(@"""Friday""", json); // Try a unique naming policy options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter(new ToLowerNamingPolicy())); json = JsonSerializer.Serialize(DayOfWeek.Friday, options); Assert.Equal(@"""friday""", json); // Undefined values should come out as a number (not a string) json = JsonSerializer.Serialize((DayOfWeek)(-1), options); Assert.Equal(@"-1", json); // Not permitting integers should throw options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false)); Assert.Throws<JsonException>(() => JsonSerializer.Serialize((DayOfWeek)(-1), options)); } public class ToLowerNamingPolicy : JsonNamingPolicy { public override string ConvertName(string name) => name.ToLowerInvariant(); } public class WhenClass { public DayOfWeek Day { get; set; } } [Fact] public void ConvertFileAttributes() { JsonSerializerOptions options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); FileState state = JsonSerializer.Deserialize<FileState>(@"{""Attributes"":""ReadOnly""}", options); Assert.Equal(FileAttributes.ReadOnly, state.Attributes); state = JsonSerializer.Deserialize<FileState>(@"{""Attributes"":""Directory, ReparsePoint""}", options); Assert.Equal(FileAttributes.Directory | FileAttributes.ReparsePoint, state.Attributes); FileAttributes attributes = JsonSerializer.Deserialize<FileAttributes>(@"""Normal""", options); Assert.Equal(FileAttributes.Normal, attributes); attributes = JsonSerializer.Deserialize<FileAttributes>(@"""System, SparseFile""", options); Assert.Equal(FileAttributes.System | FileAttributes.SparseFile, attributes); // We are case insensitive on read attributes = JsonSerializer.Deserialize<FileAttributes>(@"""OFFLINE""", options); Assert.Equal(FileAttributes.Offline, attributes); attributes = JsonSerializer.Deserialize<FileAttributes>(@"""compressed, notcontentindexed""", options); Assert.Equal(FileAttributes.Compressed | FileAttributes.NotContentIndexed, attributes); // Numbers are cool by default attributes = JsonSerializer.Deserialize<FileAttributes>(@"131072", options); Assert.Equal(FileAttributes.NoScrubData, attributes); attributes = JsonSerializer.Deserialize<FileAttributes>(@"3", options); Assert.Equal(FileAttributes.Hidden | FileAttributes.ReadOnly, attributes); string json = JsonSerializer.Serialize(FileAttributes.Hidden, options); Assert.Equal(@"""Hidden""", json); json = JsonSerializer.Serialize(FileAttributes.Temporary | FileAttributes.Offline, options); Assert.Equal(@"""Temporary, Offline""", json); // Try a unique casing options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter(new ToLowerNamingPolicy())); json = JsonSerializer.Serialize(FileAttributes.NoScrubData, options); Assert.Equal(@"""noscrubdata""", json); json = JsonSerializer.Serialize(FileAttributes.System | FileAttributes.Offline, options); Assert.Equal(@"""system, offline""", json); // Undefined values should come out as a number (not a string) json = JsonSerializer.Serialize((FileAttributes)(-1), options); Assert.Equal(@"-1", json); // Not permitting integers should throw options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false)); Assert.Throws<JsonException>(() => JsonSerializer.Serialize((FileAttributes)(-1), options)); // Flag values honor naming policy correctly options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter(new SimpleSnakeCasePolicy())); json = JsonSerializer.Serialize( FileAttributes.Directory | FileAttributes.Compressed | FileAttributes.IntegrityStream, options); Assert.Equal(@"""directory, compressed, integrity_stream""", json); json = JsonSerializer.Serialize(FileAttributes.Compressed & FileAttributes.Device, options); Assert.Equal(@"0", json); json = JsonSerializer.Serialize(FileAttributes.Directory & FileAttributes.Compressed | FileAttributes.IntegrityStream, options); Assert.Equal(@"""integrity_stream""", json); } public class FileState { public FileAttributes Attributes { get; set; } } public class Week { [JsonConverter(typeof(JsonStringEnumConverter))] public DayOfWeek WorkStart { get; set; } public DayOfWeek WorkEnd { get; set; } [JsonConverter(typeof(LowerCaseEnumConverter))] public DayOfWeek WeekEnd { get; set; } } private class LowerCaseEnumConverter : JsonStringEnumConverter { public LowerCaseEnumConverter() : base(new ToLowerNamingPolicy()) { } } [Fact] public void ConvertEnumUsingAttributes() { Week week = new Week { WorkStart = DayOfWeek.Monday, WorkEnd = DayOfWeek.Friday, WeekEnd = DayOfWeek.Saturday }; string json = JsonSerializer.Serialize(week); Assert.Equal(@"{""WorkStart"":""Monday"",""WorkEnd"":5,""WeekEnd"":""saturday""}", json); week = JsonSerializer.Deserialize<Week>(json); Assert.Equal(DayOfWeek.Monday, week.WorkStart); Assert.Equal(DayOfWeek.Friday, week.WorkEnd); Assert.Equal(DayOfWeek.Saturday, week.WeekEnd); } [Fact] public void EnumConverterComposition() { JsonSerializerOptions options = new JsonSerializerOptions { Converters = { new NoFlagsStringEnumConverter() } }; string json = JsonSerializer.Serialize(DayOfWeek.Monday, options); Assert.Equal(@"""Monday""", json); json = JsonSerializer.Serialize(FileAccess.Read); Assert.Equal(@"1", json); } public class NoFlagsStringEnumConverter : JsonConverterFactory { private static JsonStringEnumConverter s_stringEnumConverter = new JsonStringEnumConverter(); public override bool CanConvert(Type typeToConvert) => typeToConvert.IsEnum && !typeToConvert.IsDefined(typeof(FlagsAttribute), inherit: false); public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => s_stringEnumConverter.CreateConverter(typeToConvert, options); } [JsonConverter(typeof(JsonStringEnumConverter))] private enum MyCustomEnum { First = 1, Second = 2 } [Fact] public void EnumWithConverterAttribute() { string json = JsonSerializer.Serialize(MyCustomEnum.Second); Assert.Equal(@"""Second""", json); MyCustomEnum obj = JsonSerializer.Deserialize<MyCustomEnum>("\"Second\""); Assert.Equal(MyCustomEnum.Second, obj); obj = JsonSerializer.Deserialize<MyCustomEnum>("2"); Assert.Equal(MyCustomEnum.Second, obj); } [Fact] public static void EnumWithNoValues() { var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } }; Assert.Equal("-1", JsonSerializer.Serialize((EmptyEnum)(-1), options)); Assert.Equal("1", JsonSerializer.Serialize((EmptyEnum)(1), options)); } public enum EmptyEnum { }; [Fact] public static void MoreThan64EnumValuesToSerialize() { var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } }; for (int i = 0; i < 128; i++) { MyEnum value = (MyEnum)i; string asStr = value.ToString(); string expected = char.IsLetter(asStr[0]) ? $@"""{asStr}""" : asStr; Assert.Equal(expected, JsonSerializer.Serialize(value, options)); } } [Fact] public static void MoreThan64EnumValuesToSerializeWithNamingPolicy() { var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter(new ToLowerNamingPolicy()) } }; for (int i = 0; i < 128; i++) { MyEnum value = (MyEnum)i; string asStr = value.ToString().ToLowerInvariant(); string expected = char.IsLetter(asStr[0]) ? $@"""{asStr}""" : asStr; Assert.Equal(expected, JsonSerializer.Serialize(value, options)); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [OuterLoop] public static void VeryLargeAmountOfEnumsToSerialize() { // Ensure we don't throw OutOfMemoryException. var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } }; const int MaxValue = 2097152; // value for MyEnum.V // Every value between 0 and MaxValue maps to a valid enum // identifier, and is a candidate to go into the name cache. // Write the first 45 values. for (int i = 1; i < 46; i++) { JsonSerializer.Serialize((MyEnum)i, options); } // At this point, there are 60 values in the name cache; // 22 cached at warm-up, the rest in the above loop. // Ensure the approximate size limit for the name cache (a concurrent dictionary) is honored. // Use multiple threads to perhaps go over the soft limit of 64, but not by more than a couple. Parallel.For(0, 8, i => JsonSerializer.Serialize((MyEnum)(46 + i), options)); // Write the remaining enum values. The cache is capped to avoid // OutOfMemoryException due to having too many cached items. for (int i = 54; i <= MaxValue; i++) { JsonSerializer.Serialize((MyEnum)i, options); } } [Flags] public enum MyEnum { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, H = 1 << 7, I = 1 << 8, J = 1 << 9, K = 1 << 10, L = 1 << 11, M = 1 << 12, N = 1 << 13, O = 1 << 14, P = 1 << 15, Q = 1 << 16, R = 1 << 17, S = 1 << 18, T = 1 << 19, U = 1 << 20, V = 1 << 21, } [Fact, OuterLoop] [ActiveIssue("https://github.com/dotnet/runtime/issues/42677", platforms: TestPlatforms.Windows, runtimes: TestRuntimes.Mono)] public static void VeryLargeAmountOfEnumDictionaryKeysToSerialize() { // Ensure we don't throw OutOfMemoryException. const int MaxValue = (int)MyEnum.V; // Every value between 0 and MaxValue maps to a valid enum // identifier, and is a candidate to go into the name cache. // Write the first 45 values. Dictionary<MyEnum, int> dictionary; for (int i = 1; i < 46; i++) { dictionary = new Dictionary<MyEnum, int> { { (MyEnum)i, i } }; JsonSerializer.Serialize(dictionary); } // At this point, there are 60 values in the name cache; // 22 cached at warm-up, the rest in the above loop. // Ensure the approximate size limit for the name cache (a concurrent dictionary) is honored. // Use multiple threads to perhaps go over the soft limit of 64, but not by more than a couple. Parallel.For( 0, 8, i => { dictionary = new Dictionary<MyEnum, int> { { (MyEnum)(46 + i), i } }; JsonSerializer.Serialize(dictionary); } ); // Write the remaining enum values. The cache is capped to avoid // OutOfMemoryException due to having too many cached items. for (int i = 54; i <= MaxValue; i++) { dictionary = new Dictionary<MyEnum, int> { { (MyEnum)i, i } }; JsonSerializer.Serialize(dictionary); } } public abstract class NumericEnumKeyDictionaryBase<T> { public abstract Dictionary<T, int> BuildDictionary(int i); [Fact] public void SerilizeDictionaryWhenCacheIsFull() { Dictionary<T, int> dictionary; for (int i = 1; i <= 64; i++) { dictionary = BuildDictionary(i); JsonSerializer.Serialize(dictionary); } dictionary = BuildDictionary(0); string json = JsonSerializer.Serialize(dictionary); Assert.Equal($"{{\"0\":0}}", json); } } public class Int32EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumInt32> { public override Dictionary<SampleEnumInt32, int> BuildDictionary(int i) => new Dictionary<SampleEnumInt32, int> { { (SampleEnumInt32)i, i } }; } public class UInt32EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumUInt32> { public override Dictionary<SampleEnumUInt32, int> BuildDictionary(int i) => new Dictionary<SampleEnumUInt32, int> { { (SampleEnumUInt32)i, i } }; } public class UInt64EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumUInt64> { public override Dictionary<SampleEnumUInt64, int> BuildDictionary(int i) => new Dictionary<SampleEnumUInt64, int> { { (SampleEnumUInt64)i, i } }; } public class Int64EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumInt64> { public override Dictionary<SampleEnumInt64, int> BuildDictionary(int i) => new Dictionary<SampleEnumInt64, int> { { (SampleEnumInt64)i, i } }; } public class Int16EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumInt16> { public override Dictionary<SampleEnumInt16, int> BuildDictionary(int i) => new Dictionary<SampleEnumInt16, int> { { (SampleEnumInt16)i, i } }; } public class UInt16EnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumUInt16> { public override Dictionary<SampleEnumUInt16, int> BuildDictionary(int i) => new Dictionary<SampleEnumUInt16, int> { { (SampleEnumUInt16)i, i } }; } public class ByteEnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumByte> { public override Dictionary<SampleEnumByte, int> BuildDictionary(int i) => new Dictionary<SampleEnumByte, int> { { (SampleEnumByte)i, i } }; } public class SByteEnumDictionary : NumericEnumKeyDictionaryBase<SampleEnumSByte> { public override Dictionary<SampleEnumSByte, int> BuildDictionary(int i) => new Dictionary<SampleEnumSByte, int> { { (SampleEnumSByte)i, i } }; } [Flags] public enum SampleEnumInt32 { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumUInt32 : uint { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumUInt64 : ulong { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumInt64 : long { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumInt16 : short { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumUInt16 : ushort { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumByte : byte { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } [Flags] public enum SampleEnumSByte : sbyte { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, E = 1 << 4, F = 1 << 5, G = 1 << 6, } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/profiler/gc/gcallocate.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <OutputType>exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <Optimize>true</Optimize> <!-- This test provides no interesting scenarios for GCStress --> <GCStressIncompatible>true</GCStressIncompatible> <!-- The test launches a secondary process and process launch creates an infinite event loop in the SocketAsyncEngine on Linux. Since runincontext loads even framework assemblies into the unloadable context, locals in this loop prevent unloading --> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> <ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" /> <ProjectReference Include="../common/profiler_common.csproj" /> <CMakeProjectReference Include="$(MSBuildThisFileDirectory)/../native/CMakeLists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <OutputType>exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <Optimize>true</Optimize> <!-- This test provides no interesting scenarios for GCStress --> <GCStressIncompatible>true</GCStressIncompatible> <!-- The test launches a secondary process and process launch creates an infinite event loop in the SocketAsyncEngine on Linux. Since runincontext loads even framework assemblies into the unloadable context, locals in this loop prevent unloading --> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> <ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" /> <ProjectReference Include="../common/profiler_common.csproj" /> <CMakeProjectReference Include="$(MSBuildThisFileDirectory)/../native/CMakeLists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ConvertToUInt64RoundToZero.Vector128.Double.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 ConvertToUInt64RoundToZero_Vector128_Double() { var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double(); 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 SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.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<Double> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double testClass) { var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static Double[] _data1 = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar1; private Vector128<Double> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, new UInt64[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.ConvertToUInt64RoundToZero( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ConvertToUInt64RoundToZero), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ConvertToUInt64RoundToZero), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double(); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double(); fixed (Vector128<Double>* pFld1 = &test._fld1) { var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _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<Double> op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Double[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ConvertToUInt64RoundToZero(firstOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ConvertToUInt64RoundToZero)}<UInt64>(Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.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 ConvertToUInt64RoundToZero_Vector128_Double() { var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double(); 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 SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.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<Double> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double testClass) { var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static Double[] _data1 = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar1; private Vector128<Double> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, new UInt64[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.ConvertToUInt64RoundToZero( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ConvertToUInt64RoundToZero), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ConvertToUInt64RoundToZero), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double(); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToZero_Vector128_Double(); fixed (Vector128<Double>* pFld1 = &test._fld1) { var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ConvertToUInt64RoundToZero( AdvSimd.LoadVector128((Double*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _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<Double> op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Double[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ConvertToUInt64RoundToZero(firstOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ConvertToUInt64RoundToZero)}<UInt64>(Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,326
Fix some exception messages for BindHandle-like cases
- Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
kouvel
2022-03-08T06:44:15Z
2022-03-09T02:35:56Z
60f593b4dc3760268956b9a874daad7f49b0255d
a0a5fc9771f63aa31cb45b3577a7cea31527a2fb
Fix some exception messages for BindHandle-like cases. - Updated `ThrowHelper.ThrowApplicationException` to get and include an error message - CoreCLR seems to have special code for producing exception messages from HRs and differs a bit from `Marshal.GetExceptionForHR`, forked to throw from the native side in CoreCLR to retain the previous messages - Enabled the disabled tests, disabled a `BindHandle` test on Unixes where it now throws `PNSE` before `ArgumentNullException`, kept some tests disabled for Mono since the tests check for specific parts of exception messages that are specific to CoreCLR's code Fixes https://github.com/dotnet/runtime/issues/66273 Fixes https://github.com/dotnet/runtime/issues/66274
./src/libraries/System.Diagnostics.Contracts/Directory.Build.props
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <StrongNameKeyId>Microsoft</StrongNameKeyId> </PropertyGroup> </Project>
<Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <StrongNameKeyId>Microsoft</StrongNameKeyId> </PropertyGroup> </Project>
-1
dotnet/runtime
66,321
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug
Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
stephentoub
2022-03-08T01:37:40Z
2022-03-08T19:24:48Z
446a0d610d4479fa9ba58ec14a89132a18ed33c4
b6c5a12cfa92e06734286bd991e7cca87ded1e24
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug. Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
./src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.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; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; // NOTE: The logic in this file is largely a copy of logic in RegexCompiler, emitting C# instead of MSIL. // Most changes made to this file should be kept in sync, so far as bug fixes and relevant optimizations // are concerned. namespace System.Text.RegularExpressions.Generator { public partial class RegexGenerator { /// <summary>Code for a [GeneratedCode] attribute to put on the top-level generated members.</summary> private static readonly string s_generatedCodeAttribute = $"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{typeof(RegexGenerator).Assembly.GetName().Name}\", \"{typeof(RegexGenerator).Assembly.GetName().Version}\")]"; /// <summary>Header comments and usings to include at the top of every generated file.</summary> private static readonly string[] s_headers = new string[] { "// <auto-generated/>", "#nullable enable", "#pragma warning disable CS0162 // Unreachable code", "#pragma warning disable CS0164 // Unreferenced label", "#pragma warning disable CS0219 // Variable assigned but never used", "", }; /// <summary>Generates the code for one regular expression class.</summary> private static (string, ImmutableArray<Diagnostic>) EmitRegexType(RegexType regexClass, bool allowUnsafe) { var sb = new StringBuilder(1024); var writer = new IndentedTextWriter(new StringWriter(sb)); // Emit the namespace if (!string.IsNullOrWhiteSpace(regexClass.Namespace)) { writer.WriteLine($"namespace {regexClass.Namespace}"); writer.WriteLine("{"); writer.Indent++; } // Emit containing types RegexType? parent = regexClass.ParentClass; var parentClasses = new Stack<string>(); while (parent is not null) { parentClasses.Push($"partial {parent.Keyword} {parent.Name}"); parent = parent.ParentClass; } while (parentClasses.Count != 0) { writer.WriteLine($"{parentClasses.Pop()}"); writer.WriteLine("{"); writer.Indent++; } // Emit the direct parent type writer.WriteLine($"partial {regexClass.Keyword} {regexClass.Name}"); writer.WriteLine("{"); writer.Indent++; // Generate a name to describe the regex instance. This includes the method name // the user provided and a non-randomized (for determinism) hash of it to try to make // the name that much harder to predict. Debug.Assert(regexClass.Method is not null); string generatedName = $"GeneratedRegex_{regexClass.Method.MethodName}_"; generatedName += ComputeStringHash(generatedName).ToString("X"); // Generate the regex type ImmutableArray<Diagnostic> diagnostics = EmitRegexMethod(writer, regexClass.Method, generatedName, allowUnsafe); while (writer.Indent != 0) { writer.Indent--; writer.WriteLine("}"); } writer.Flush(); return (sb.ToString(), diagnostics); // FNV-1a hash function. The actual algorithm used doesn't matter; just something simple // to create a deterministic, pseudo-random value that's based on input text. static uint ComputeStringHash(string s) { uint hashCode = 2166136261; foreach (char c in s) { hashCode = (c ^ hashCode) * 16777619; } return hashCode; } } /// <summary>Generates the code for a regular expression method.</summary> private static ImmutableArray<Diagnostic> EmitRegexMethod(IndentedTextWriter writer, RegexMethod rm, string id, bool allowUnsafe) { string patternExpression = Literal(rm.Pattern); string optionsExpression = Literal(rm.Options); string timeoutExpression = rm.MatchTimeout == Timeout.Infinite ? "global::System.Threading.Timeout.InfiniteTimeSpan" : $"global::System.TimeSpan.FromMilliseconds({rm.MatchTimeout.ToString(CultureInfo.InvariantCulture)})"; writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine($"{rm.Modifiers} global::System.Text.RegularExpressions.Regex {rm.MethodName}() => {id}.Instance;"); writer.WriteLine(); writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine("[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]"); writer.WriteLine($"{(writer.Indent != 0 ? "private" : "internal")} sealed class {id} : global::System.Text.RegularExpressions.Regex"); writer.WriteLine("{"); writer.Write(" public static global::System.Text.RegularExpressions.Regex Instance { get; } = "); // If we can't support custom generation for this regex, spit out a Regex constructor call. if (!rm.Tree.Root.SupportsCompilation(out string? reason)) { writer.WriteLine(); writer.WriteLine($" // Cannot generate Regex-derived implementation because {reason}."); writer.WriteLine($" new global::System.Text.RegularExpressions.Regex({patternExpression}, {optionsExpression}, {timeoutExpression});"); writer.WriteLine("}"); return ImmutableArray.Create(Diagnostic.Create(DiagnosticDescriptors.LimitedSourceGeneration, rm.MethodSyntax.GetLocation())); } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(rm.Tree); writer.WriteLine($"new {id}();"); writer.WriteLine(); writer.WriteLine($" private {id}()"); writer.WriteLine($" {{"); writer.WriteLine($" base.pattern = {patternExpression};"); writer.WriteLine($" base.roptions = {optionsExpression};"); writer.WriteLine($" base.internalMatchTimeout = {timeoutExpression};"); writer.WriteLine($" base.factory = new RunnerFactory();"); if (rm.Tree.CaptureNumberSparseMapping is not null) { writer.Write(" base.Caps = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNumberSparseMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNameToNumberMapping is not null) { writer.Write(" base.CapNames = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNameToNumberMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNames is not null) { writer.Write(" base.capslist = new string[] {"); string separator = ""; foreach (string s in rm.Tree.CaptureNames) { writer.Write(separator); writer.Write(Literal(s)); separator = ", "; } writer.WriteLine(" };"); } writer.WriteLine($" base.capsize = {rm.Tree.CaptureCount};"); writer.WriteLine($" }}"); writer.WriteLine(" "); writer.WriteLine($" private sealed class RunnerFactory : global::System.Text.RegularExpressions.RegexRunnerFactory"); writer.WriteLine($" {{"); writer.WriteLine($" protected override global::System.Text.RegularExpressions.RegexRunner CreateInstance() => new Runner();"); writer.WriteLine(); writer.WriteLine($" private sealed class Runner : global::System.Text.RegularExpressions.RegexRunner"); writer.WriteLine($" {{"); // Main implementation methods writer.WriteLine(" // Description:"); DescribeExpression(writer, rm.Tree.Root.Child(0), " // ", analysis); // skip implicit root capture writer.WriteLine(); writer.WriteLine($" protected override void Scan(global::System.ReadOnlySpan<char> text)"); writer.WriteLine($" {{"); writer.Indent += 4; EmitScan(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); writer.WriteLine($" private bool TryFindNextPossibleStartingPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; RequiredHelperFunctions requiredHelpers = EmitTryFindNextPossibleStartingPosition(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); if (allowUnsafe) { writer.WriteLine($" [global::System.Runtime.CompilerServices.SkipLocalsInit]"); } writer.WriteLine($" private bool TryMatchAtCurrentPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; requiredHelpers |= EmitTryMatchAtCurrentPosition(writer, rm, id, analysis); writer.Indent -= 4; writer.WriteLine($" }}"); if ((requiredHelpers & RequiredHelperFunctions.IsWordChar) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character is part of the [\\w] set.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsWordChar(char ch)"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.ReadOnlySpan<byte> ascii = new byte[]"); writer.WriteLine($" {{"); writer.WriteLine($" 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03,"); writer.WriteLine($" 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07"); writer.WriteLine($" }};"); writer.WriteLine(); writer.WriteLine($" int chDiv8 = ch >> 3;"); writer.WriteLine($" return (uint)chDiv8 < (uint)ascii.Length ?"); writer.WriteLine($" (ascii[chDiv8] & (1 << (ch & 0x7))) != 0 :"); writer.WriteLine($" global::System.Globalization.CharUnicodeInfo.GetUnicodeCategory(ch) switch"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.UppercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.LowercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.TitlecaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ModifierLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.OtherLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.NonSpacingMark or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.DecimalDigitNumber or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ConnectorPunctuation => true,"); writer.WriteLine($" _ => false,"); writer.WriteLine($" }};"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsBoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsBoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsBoundaryWordChar(char ch) =>"); writer.WriteLine($" IsWordChar(ch) || (ch == '\\u200C' | ch == '\\u200D');"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsECMABoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsECMABoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsECMAWordChar(char ch) =>"); writer.WriteLine($" ((((uint)ch - 'A') & ~0x20) < 26) || // ASCII letter"); writer.WriteLine($" (((uint)ch - '0') < 10) || // digit"); writer.WriteLine($" ch == '_' || // underscore"); writer.WriteLine($" ch == '\\u0130'; // latin capital letter I with dot above"); writer.WriteLine($" }}"); } writer.WriteLine($" }}"); writer.WriteLine($" }}"); writer.WriteLine("}"); return ImmutableArray<Diagnostic>.Empty; static void AppendHashtableContents(IndentedTextWriter writer, Hashtable ht) { IDictionaryEnumerator en = ht.GetEnumerator(); string separator = ""; while (en.MoveNext()) { writer.Write(separator); separator = ", "; writer.Write(" { "); if (en.Key is int key) { writer.Write(key); } else { writer.Write($"\"{en.Key}\""); } writer.Write($", {en.Value} }} "); } } } /// <summary>Emits the body of the Scan method override.</summary> private static void EmitScan(IndentedTextWriter writer, RegexMethod rm, string id) { bool rtl = (rm.Options & RegexOptions.RightToLeft) != 0; using (EmitBlock(writer, "while (TryFindNextPossibleStartingPosition(text))")) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("base.CheckTimeout();"); writer.WriteLine(); } writer.WriteLine("// If we find a match on the current position, or we have reached the end of the input, we are done."); using (EmitBlock(writer, $"if (TryMatchAtCurrentPosition(text) || base.runtextpos == {(!rtl ? "text.Length" : "0")})")) { writer.WriteLine("return;"); } writer.WriteLine(); writer.WriteLine($"base.runtextpos{(!rtl ? "++" : "--")};"); } } /// <summary>Emits the body of the TryFindNextPossibleStartingPosition.</summary> private static RequiredHelperFunctions EmitTryFindNextPossibleStartingPosition(IndentedTextWriter writer, RegexMethod rm, string id) { RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; bool hasTextInfo = false; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; bool rtl = (options & RegexOptions.RightToLeft) != 0; // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); // Emit locals initialization writer.WriteLine("int pos = base.runtextpos;"); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; writer.WriteLine(); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = rm.Tree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); string clause = (minRequiredLength, rtl) switch { (0, false) => "if (pos <= inputSpan.Length)", (1, false) => "if (pos < inputSpan.Length)", (_, false) => $"if (pos <= inputSpan.Length - {minRequiredLength})", (0, true) => "if (pos >= 0)", (1, true) => "if (pos > 0)", (_, true) => $"if (pos >= {minRequiredLength})", }; using (EmitBlock(writer, clause)) { // Emit any anchors. if (!EmitAnchors()) { // Either anchors weren't specified, or they don't completely root all matches to a specific location. // If whatever search operation we need to perform entails case-insensitive operations // that weren't already handled via creation of sets, we need to get an store the // TextInfo object to use (unless RegexOptions.CultureInvariant was specified). EmitTextInfo(writer, ref hasTextInfo, rm); // Emit the code for whatever find mode has been determined. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_LeftToRight(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_RightToLeft(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_LeftToRight(); break; case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_RightToLeft(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: writer.WriteLine("return true;"); break; } } } writer.WriteLine(); const string NoStartingPositionFound = "NoStartingPositionFound"; writer.WriteLine("// No starting position found"); writer.WriteLine($"{NoStartingPositionFound}:"); writer.WriteLine($"base.runtextpos = {(!rtl ? "inputSpan.Length" : "0")};"); writer.WriteLine("return false;"); // We're done. Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); return requiredHelpers; // Emit a goto for the specified label. void Goto(string label) => writer.WriteLine($"goto {label};"); // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool EmitAnchors() { // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: writer.WriteLine("// Beginning \\A anchor"); using (EmitBlock(writer, "if (pos != 0)")) { // If we're not currently at the beginning, we'll never be, so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: writer.WriteLine("// Start \\G anchor"); using (EmitBlock(writer, "if (pos != base.runtextstart)")) { // For both left-to-right and right-to-left, if we're not currently at the starting (because // we've already moved beyond it), then we'll never be, so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: writer.WriteLine("// Leading end \\Z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length - 1)")) { // If we're not currently at the end (or a newline just before it), skip ahead // since nothing until then can possibly match. writer.WriteLine("base.runtextpos = inputSpan.Length - 1;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: writer.WriteLine("// Leading end \\z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length)")) { // If we're not currently at the end (or a newline just before it), skip ahead // since nothing until then can possibly match. writer.WriteLine("base.runtextpos = inputSpan.Length;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: writer.WriteLine("// Beginning \\A anchor"); using (EmitBlock(writer, "if (pos != 0)")) { // If we're not currently at the beginning, skip ahead (or, rather, backwards) // since nothing until then can possibly match. (We're iterating from the end // to the beginning in RightToLeft mode.) writer.WriteLine("base.runtextpos = 0;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: writer.WriteLine("// Leading end \\Z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n'))")) { // If we're not currently at the end, we'll never be (we're iterating from end to beginning), // so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: writer.WriteLine("// Leading end \\z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length)")) { // If we're not currently at the end, we'll never be (we're iterating from end to beginning), // so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length, minus 1 (for a possible ending \n). writer.WriteLine("// Trailing end \\Z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1};"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: // Jump to the end, minus the min required length, which in this case is actually the fixed length. writer.WriteLine("// Trailing end \\z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength};"); } writer.WriteLine("return true;"); return true; } // Now handle anchors that boost the position but may not determine immediate success or failure. switch (regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. writer.WriteLine("// Beginning-of-line anchor"); using (EmitBlock(writer, "if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { writer.WriteLine("int newlinePos = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), '\\n');"); using (EmitBlock(writer, "if ((uint)newlinePos > inputSpan.Length - pos - 1)")) { Goto(NoStartingPositionFound); } writer.WriteLine("pos = newlinePos + pos + 1;"); // We've updated the position. Make sure there's still enough room in the input for a possible match. using (EmitBlock(writer, minRequiredLength switch { 0 => "if (pos > inputSpan.Length)", 1 => "if (pos >= inputSpan.Length)", _ => $"if (pos > inputSpan.Length - {minRequiredLength})" })) { Goto(NoStartingPositionFound); } } writer.WriteLine(); break; } switch (regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength};"); } writer.WriteLine(); break; case RegexNodeKind.EndZ when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\Z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength + 1})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength + 1};"); } writer.WriteLine(); break; } return false; } // Emits a case-sensitive prefix search for a string at the beginning of the pattern. void EmitIndexOf_LeftToRight(string prefix) { writer.WriteLine($"int i = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), {Literal(prefix)});"); writer.WriteLine("if (i >= 0)"); writer.WriteLine("{"); writer.WriteLine(" base.runtextpos = pos + i;"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } // Emits a case-sensitive right-to-left prefix search for a string at the beginning of the pattern. void EmitIndexOf_RightToLeft(string prefix) { writer.WriteLine($"pos = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice(0, pos), {Literal(prefix)});"); writer.WriteLine("if (pos >= 0)"); writer.WriteLine("{"); writer.WriteLine($" base.runtextpos = pos + {prefix.Length};"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } // Emits a search for a set at a fixed position from the start of the pattern, // and potentially other sets at other fixed positions in the pattern. void EmitFixedSet_LeftToRight() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; FinishEmitScope loopBlock = default; if (needLoop) { writer.WriteLine("global::System.ReadOnlySpan<char> span = inputSpan.Slice(pos);"); string upperBound = "span.Length" + (setsToUse > 1 || primarySet.Distance != 0 ? $" - {minRequiredLength - 1}" : ""); loopBlock = EmitBlock(writer, $"for (int i = 0; i < {upperBound}; i++)"); } if (canUseIndexOf) { string span = needLoop ? "span" : "inputSpan.Slice(pos)"; span = (needLoop, primarySet.Distance) switch { (false, 0) => span, (true, 0) => $"{span}.Slice(i)", (false, _) => $"{span}.Slice({primarySet.Distance})", (true, _) => $"{span}.Slice(i + {primarySet.Distance})", }; string indexOf = primarySet.Chars!.Length switch { 1 => $"global::System.MemoryExtensions.IndexOf({span}, {Literal(primarySet.Chars[0])})", 2 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])})", 3 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])}, {Literal(primarySet.Chars[2])})", _ => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(new string(primarySet.Chars))})", }; if (needLoop) { writer.WriteLine($"int indexOfPos = {indexOf};"); using (EmitBlock(writer, "if (indexOfPos < 0)")) { Goto(NoStartingPositionFound); } writer.WriteLine("i += indexOfPos;"); writer.WriteLine(); if (setsToUse > 1) { using (EmitBlock(writer, $"if (i >= span.Length - {minRequiredLength - 1})")) { Goto(NoStartingPositionFound); } writer.WriteLine(); } } else { writer.WriteLine($"int i = {indexOf};"); using (EmitBlock(writer, "if (i >= 0)")) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } setIndex = 1; } if (needLoop) { Debug.Assert(setIndex == 0 || setIndex == 1); bool hasCharClassConditions = false; if (setIndex < setsToUse) { // if (CharInClass(textSpan[i + charClassIndex], prefix[0], "...") && // ...) Debug.Assert(needLoop); int start = setIndex; for (; setIndex < setsToUse; setIndex++) { string spanIndex = $"span[i{(sets[setIndex].Distance > 0 ? $" + {sets[setIndex].Distance}" : "")}]"; string charInClassExpr = MatchCharacterClass(hasTextInfo, options, spanIndex, sets[setIndex].Set, sets[setIndex].CaseInsensitive, negate: false, additionalDeclarations, ref requiredHelpers); if (setIndex == start) { writer.Write($"if ({charInClassExpr}"); } else { writer.WriteLine(" &&"); writer.Write($" {charInClassExpr}"); } } writer.WriteLine(")"); hasCharClassConditions = true; } using (hasCharClassConditions ? EmitBlock(writer, null) : default) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } loopBlock.Dispose(); } // Emits a right-to-left search for a set at a fixed position from the start of the pattern. // (Currently that position will always be a distance of 0, meaning the start of the pattern itself.) void EmitFixedSet_RightToLeft() { (char[]? Chars, string Set, int Distance, bool CaseInsensitive) set = regexTree.FindOptimizations.FixedDistanceSets![0]; Debug.Assert(set.Distance == 0); if (set.Chars is { Length: 1 } && !set.CaseInsensitive) { writer.WriteLine($"pos = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice(0, pos), {Literal(set.Chars[0])});"); writer.WriteLine("if (pos >= 0)"); writer.WriteLine("{"); writer.WriteLine(" base.runtextpos = pos + 1;"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } else { using (EmitBlock(writer, "while ((uint)--pos < (uint)inputSpan.Length)")) { using (EmitBlock(writer, $"if ({MatchCharacterClass(hasTextInfo, options, "inputSpan[pos]", set.Set, set.CaseInsensitive, negate: false, additionalDeclarations, ref requiredHelpers)})")) { writer.WriteLine("base.runtextpos = pos + 1;"); writer.WriteLine("return true;"); } } } } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); using (EmitBlock(writer, "while (true)")) { writer.WriteLine($"global::System.ReadOnlySpan<char> slice = inputSpan.Slice(pos);"); writer.WriteLine(); // Find the literal. If we can't find it, we're done searching. writer.Write("int i = global::System.MemoryExtensions."); writer.WriteLine( target.Literal.String is string literalString ? $"IndexOf(slice, {Literal(literalString)});" : target.Literal.Chars is not char[] literalChars ? $"IndexOf(slice, {Literal(target.Literal.Char)});" : literalChars.Length switch { 2 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])});", 3 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])}, {Literal(literalChars[2])});", _ => $"IndexOfAny(slice, {Literal(new string(literalChars))});", }); using (EmitBlock(writer, $"if (i < 0)")) { writer.WriteLine("break;"); } writer.WriteLine(); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. writer.WriteLine("int prev = i;"); writer.WriteLine($"while ((uint)--prev < (uint)slice.Length && {MatchCharacterClass(hasTextInfo, options, "slice[prev]", target.LoopNode.Str!, caseInsensitive: false, negate: false, additionalDeclarations, ref requiredHelpers)});"); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. writer.WriteLine($"if ((i - prev - 1) < {target.LoopNode.M})"); writer.WriteLine("{"); writer.WriteLine(" pos += i + 1;"); writer.WriteLine(" continue;"); writer.WriteLine("}"); } writer.WriteLine(); // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. writer.WriteLine("base.runtextpos = pos + prev + 1;"); writer.WriteLine("return true;"); } } // If a TextInfo is needed to perform ToLower operations, emits a local initialized to the TextInfo to use. static void EmitTextInfo(IndentedTextWriter writer, ref bool hasTextInfo, RegexMethod rm) { // Emit local to store current culture if needed if ((rm.Options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = rm.Tree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when rm.Tree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { hasTextInfo = true; writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); } } } } /// <summary>Emits the body of the TryMatchAtCurrentPosition.</summary> private static RequiredHelperFunctions EmitTryMatchAtCurrentPosition(IndentedTextWriter writer, RegexMethod rm, string id, AnalysisResults analysis) { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; // Helper to define names. Names start unadorned, but as soon as there's repetition, // they begin to have a numbered suffix. var usedNames = new Dictionary<string, int>(); // Every RegexTree is rooted in the implicit Capture for the whole expression. // Skip the Capture node. We handle the implicit root capture specially. RegexNode node = regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. writer.WriteLine($"int start = base.runtextpos;"); writer.WriteLine($"int end = start {((node.Options & RegexOptions.RightToLeft) == 0 ? "+" : "-")} {(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1)};"); writer.WriteLine("base.Capture(0, start, end);"); writer.WriteLine("base.runtextpos = end;"); writer.WriteLine("return true;"); return requiredHelpers; case RegexNodeKind.Empty: // This case isn't common in production, but it's very common when first getting started with the // source generator and seeing what happens as you add more to expressions. When approaching // it from a learning perspective, this is very common, as it's the empty string you start with. writer.WriteLine("base.Capture(0, base.runtextpos, base.runtextpos);"); writer.WriteLine("return true;"); return requiredHelpers; } // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); var additionalLocalFunctions = new Dictionary<string, string[]>(); // Declare some locals. string sliceSpan = "slice"; writer.WriteLine("int pos = base.runtextpos;"); writer.WriteLine($"int original_pos = pos;"); bool hasTimeout = EmitLoopTimeoutCounterIfNeeded(writer, rm); bool hasTextInfo = EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(writer, rm, analysis); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(writer, defineLocal: true); writer.WriteLine(); // doneLabel starts out as the top-level label for the whole expression failing to match. However, // it may be changed by the processing of a node to point to whereever subsequent match failures // should jump to, in support of backtracking or other constructs. For example, before emitting // the code for a branch N, an alternation will set the the doneLabel to point to the label for // processing the next branch N+1: that way, any failures in the branch N's processing will // implicitly end up jumping to the right location without needing to know in what context it's used. string doneLabel = ReserveName("NoMatch"); string topLevelDoneLabel = doneLabel; // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // If we fall through to this place in the code, we've successfully matched the expression. writer.WriteLine(); writer.WriteLine("// The input matched."); if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); // TransferSliceStaticPosToPos would also slice, which isn't needed here } writer.WriteLine("base.runtextpos = pos;"); writer.WriteLine("base.Capture(0, original_pos, pos);"); writer.WriteLine("return true;"); // We're done with the match. // Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); // And emit any required helpers. if (additionalLocalFunctions.Count != 0) { foreach (KeyValuePair<string, string[]> localFunctions in additionalLocalFunctions.OrderBy(k => k.Key)) { writer.WriteLine(); foreach (string line in localFunctions.Value) { writer.WriteLine(line); } } } return requiredHelpers; // Helper to create a name guaranteed to be unique within the function. string ReserveName(string prefix) { usedNames.TryGetValue(prefix, out int count); usedNames[prefix] = count + 1; return count == 0 ? prefix : $"{prefix}{count}"; } // Helper to emit a label. As of C# 10, labels aren't statements of their own and need to adorn a following statement; // if a label appears just before a closing brace, then, it's a compilation error. To avoid issues there, this by // default implements a blank statement (a semicolon) after each label, but individual uses can opt-out of the semicolon // when it's known the label will always be followed by a statement. void MarkLabel(string label, bool emitSemicolon = true) => writer.WriteLine($"{label}:{(emitSemicolon ? ";" : "")}"); // Emits a goto to jump to the specified label. However, if the specified label is the top-level done label indicating // that the entire match has failed, we instead emit our epilogue, uncapturing if necessary and returning out of TryMatchAtCurrentPosition. void Goto(string label) { if (label == topLevelDoneLabel) { // We only get here in the code if the whole expression fails to match and jumps to // the original value of doneLabel. if (expressionHasCaptures) { EmitUncaptureUntil("0"); } writer.WriteLine("return false; // The input didn't match."); } else { writer.WriteLine($"goto {label};"); } } // Emits a case or default line followed by an indented body. void CaseGoto(string clause, string label) { writer.WriteLine(clause); writer.Indent++; Goto(label); writer.Indent--; } // Whether the node has RegexOptions.IgnoreCase set. static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan(IndentedTextWriter writer, bool defineLocal = false) { if (defineLocal) { writer.Write("global::System.ReadOnlySpan<char> "); } writer.WriteLine($"{sliceSpan} = inputSpan.Slice(pos);"); } // Emits the sum of a constant and a value from a local. string Sum(int constant, string? local = null) => local is null ? constant.ToString(CultureInfo.InvariantCulture) : constant == 0 ? local : $"{constant} + {local}"; // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) { Debug.Assert(requiredLength > 0); using (EmitBlock(writer, $"if ({SpanLengthCheck(requiredLength, dynamicRequiredLength)})")) { Goto(doneLabel); } } // Returns a length check for the current span slice. The check returns true if // the span isn't long enough for the specified length. string SpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) => dynamicRequiredLength is null && sliceStaticPos + requiredLength == 1 ? $"{sliceSpan}.IsEmpty" : $"(uint){sliceSpan}.Length < {Sum(sliceStaticPos + requiredLength, dynamicRequiredLength)}"; // Adds the value of sliceStaticPos into the pos local, slices slice by the corresponding amount, // and zeros out sliceStaticPos. void TransferSliceStaticPosToPos(bool forceSliceReload = false) { if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); sliceStaticPos = 0; SliceInputSpan(writer); } else if (forceSliceReload) { SliceInputSpan(writer); } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); string originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // If no child branch overlaps with another child branch, we can emit more streamlined code // that avoids checking unnecessary branches, e.g. with abc|def|ghi if the next character in // the input is 'a', we needn't try the def or ghi branches. A simple, relatively common case // of this is if every branch begins with a specific, unique character, in which case // the whole alternation can be treated as a simple switch, so we special-case that. However, // we can't goto _into_ switch cases, which means we can't use this approach if there's any // possibility of backtracking into the alternation. bool useSwitchedBranches = false; if ((node.Options & RegexOptions.RightToLeft) == 0) { useSwitchedBranches = isAtomic; if (!useSwitchedBranches) { useSwitchedBranches = true; for (int i = 0; i < childCount; i++) { if (analysis.MayBacktrack(node.Child(i))) { useSwitchedBranches = false; break; } } } } // Detect whether every branch begins with one or more unique characters. const int SetCharsSize = 5; // arbitrary limit (for IgnoreCase, we want this to be at least 3 to handle the vast majority of values) Span<char> setChars = stackalloc char[SetCharsSize]; if (useSwitchedBranches) { // Iterate through every branch, seeing if we can easily find a starting One, Multi, or small Set. // If we can, extract its starting char (or multiple in the case of a set), validate that all such // starting characters are unique relative to all the branches. var seenChars = new HashSet<char>(); for (int i = 0; i < childCount && useSwitchedBranches; i++) { // If it's not a One, Multi, or Set, we can't apply this optimization. // If it's IgnoreCase (and wasn't reduced to a non-IgnoreCase set), also ignore it to keep the logic simple. if (node.Child(i).FindBranchOneMultiOrSetStart() is not RegexNode oneMultiOrSet || (oneMultiOrSet.Options & RegexOptions.IgnoreCase) != 0) // TODO: https://github.com/dotnet/runtime/issues/61048 { useSwitchedBranches = false; break; } // If it's a One or a Multi, get the first character and add it to the set. // If it was already in the set, we can't apply this optimization. if (oneMultiOrSet.Kind is RegexNodeKind.One or RegexNodeKind.Multi) { if (!seenChars.Add(oneMultiOrSet.FirstCharOfOneOrMulti())) { useSwitchedBranches = false; break; } } else { // The branch begins with a set. Make sure it's a set of only a few characters // and get them. If we can't, we can't apply this optimization. Debug.Assert(oneMultiOrSet.Kind is RegexNodeKind.Set); int numChars; if (RegexCharClass.IsNegated(oneMultiOrSet.Str!) || (numChars = RegexCharClass.GetSetChars(oneMultiOrSet.Str!, setChars)) == 0) { useSwitchedBranches = false; break; } // Check to make sure each of the chars is unique relative to all other branches examined. foreach (char c in setChars.Slice(0, numChars)) { if (!seenChars.Add(c)) { useSwitchedBranches = false; break; } } } } } if (useSwitchedBranches) { // Note: This optimization does not exist with RegexOptions.Compiled. Here we rely on the // C# compiler to lower the C# switch statement with appropriate optimizations. In some // cases there are enough branches that the compiler will emit a jump table. In others // it'll optimize the order of checks in order to minimize the total number in the worst // case. In any case, we get easier to read and reason about C#. EmitSwitchedBranches(); } else { EmitAllBranches(); } return; // Emits the code for a switch-based alternation of non-overlapping branches. void EmitSwitchedBranches() { // We need at least 1 remaining character in the span, for the char to switch on. EmitSpanLengthCheck(1); writer.WriteLine(); // Emit a switch statement on the first char of each branch. using (EmitBlock(writer, $"switch ({sliceSpan}[{sliceStaticPos++}])")) { Span<char> setChars = stackalloc char[SetCharsSize]; // needs to be same size as detection check in caller int startingSliceStaticPos = sliceStaticPos; // Emit a case for each branch. for (int i = 0; i < childCount; i++) { sliceStaticPos = startingSliceStaticPos; RegexNode child = node.Child(i); Debug.Assert(child.Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set or RegexNodeKind.Concatenate, DescribeNode(child, analysis)); Debug.Assert(child.Kind is not RegexNodeKind.Concatenate || (child.ChildCount() >= 2 && child.Child(0).Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set)); RegexNode? childStart = child.FindBranchOneMultiOrSetStart(); Debug.Assert(childStart is not null, "Unexpectedly couldn't find the branch starting node."); Debug.Assert((childStart.Options & RegexOptions.IgnoreCase) == 0, "Expected only to find non-IgnoreCase branch starts"); if (childStart.Kind is RegexNodeKind.Set) { int numChars = RegexCharClass.GetSetChars(childStart.Str!, setChars); Debug.Assert(numChars != 0); writer.WriteLine($"case {string.Join(" or ", setChars.Slice(0, numChars).ToArray().Select(c => Literal(c)))}:"); } else { writer.WriteLine($"case {Literal(childStart.FirstCharOfOneOrMulti())}:"); } writer.Indent++; // Emit the code for the branch, without the first character that was already matched in the switch. switch (child.Kind) { case RegexNodeKind.Multi: EmitNode(CloneMultiWithoutFirstChar(child)); writer.WriteLine(); break; case RegexNodeKind.Concatenate: var newConcat = new RegexNode(RegexNodeKind.Concatenate, child.Options); if (childStart.Kind == RegexNodeKind.Multi) { newConcat.AddChild(CloneMultiWithoutFirstChar(childStart)); } int concatChildCount = child.ChildCount(); for (int j = 1; j < concatChildCount; j++) { newConcat.AddChild(child.Child(j)); } EmitNode(newConcat.Reduce()); writer.WriteLine(); break; static RegexNode CloneMultiWithoutFirstChar(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Multi); Debug.Assert(node.Str!.Length >= 2); return node.Str!.Length == 2 ? new RegexNode(RegexNodeKind.One, node.Options, node.Str![1]) : new RegexNode(RegexNodeKind.Multi, node.Options, node.Str!.Substring(1)); } } // This is only ever used for atomic alternations, so we can simply reset the doneLabel // after emitting the child, as nothing will backtrack here (and we need to reset it // so that all branches see the original). doneLabel = originalDoneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); writer.WriteLine($"break;"); writer.WriteLine(); writer.Indent--; } // Default branch if the character didn't match the start of any branches. CaseGoto("default:", doneLabel); } } void EmitAllBranches() { // Label to jump to when any branch completes successfully. string matchLabel = ReserveName("AlternationMatch"); // Save off pos. We'll need to reset this each time a branch fails. string startingPos = ReserveName("alternation_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. string? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { startingCapturePos = ReserveName("alternation_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } writer.WriteLine(); // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new string[childCount]; string backtrackLabel = ReserveName("AlternationBacktrack"); for (int i = 0; i < childCount; i++) { // If the alternation isn't atomic, backtracking may require our jump table jumping back // into these branches, so we can't use actual scopes, as that would hide the labels. using (EmitScope(writer, $"Branch {i}", faux: !isAtomic)) { bool isLastBranch = i == childCount - 1; string? nextBranch = null; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = ReserveName("AlternationBranch"); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); writer.WriteLine(); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { EmitStackPush(startingCapturePos is not null ? new[] { i.ToString(), startingPos, startingCapturePos } : new[] { i.ToString(), startingPos }); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); if (!isLastBranch || !isAtomic) { // If this isn't the last branch, we're about to output a reset section, // and if this isn't atomic, there will be a backtracking section before // the end of the method. In both of those cases, we've successfully // matched and need to skip over that code. If, however, this is the // last branch and this is an atomic alternation, we can just fall // through to the successfully matched location. Goto(matchLabel); } // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { writer.WriteLine(); MarkLabel(nextBranch!, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } writer.WriteLine(); } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel, emitSemicolon: false); EmitStackPop(startingCapturePos is not null ? new[] { startingCapturePos, startingPos } : new[] { startingPos}); using (EmitBlock(writer, $"switch ({StackPop()})")) { for (int i = 0; i < labelMap.Length; i++) { CaseGoto($"case {i}:", labelMap[i]); } } writer.WriteLine(); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); if (sliceStaticPos > 0) { TransferSliceStaticPosToPos(); writer.WriteLine(); } // If the specified capture hasn't yet captured anything, fail to match... except when using RegexOptions.ECMAScript, // in which case per ECMA 262 section 21.2.2.9 the backreference should succeed. if ((node.Options & RegexOptions.ECMAScript) != 0) { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference matches with RegexOptions.ECMAScript rules."); using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { EmitWhenHasCapture(); } } else { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference doesn't match."); using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(doneLabel); } writer.WriteLine(); EmitWhenHasCapture(); } void EmitWhenHasCapture() { writer.WriteLine("// Get the captured text. If it doesn't match at the current position, the backreference doesn't match."); additionalDeclarations.Add("int matchLength = 0;"); writer.WriteLine($"matchLength = base.MatchLength({capnum});"); bool caseInsensitive = IsCaseInsensitive(node); if ((node.Options & RegexOptions.RightToLeft) == 0) { if (!caseInsensitive) { // If we're case-sensitive, we can simply validate that the remaining length of the slice is sufficient // to possibly match, and then do a SequenceEqual against the matched text. writer.WriteLine($"if ({sliceSpan}.Length < matchLength || "); using (EmitBlock(writer, $" !global::System.MemoryExtensions.SequenceEqual(inputSpan.Slice(base.MatchIndex({capnum}), matchLength), {sliceSpan}.Slice(0, matchLength)))")) { Goto(doneLabel); } } else { // For case-insensitive, we have to walk each character individually. using (EmitBlock(writer, $"if ({sliceSpan}.Length < matchLength)")) { Goto(doneLabel); } writer.WriteLine(); additionalDeclarations.Add("int matchIndex = 0;"); writer.WriteLine($"matchIndex = base.MatchIndex({capnum});"); using (EmitBlock(writer, $"for (int i = 0; i < matchLength; i++)")) { using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"inputSpan[matchIndex + i]")} != {ToLower(hasTextInfo, options, $"{sliceSpan}[i]")})")) { Goto(doneLabel); } } } writer.WriteLine(); writer.WriteLine($"pos += matchLength;"); SliceInputSpan(writer); } else { using (EmitBlock(writer, $"if (pos < matchLength)")) { Goto(doneLabel); } writer.WriteLine(); additionalDeclarations.Add("int matchIndex = 0;"); writer.WriteLine($"matchIndex = base.MatchIndex({capnum});"); using (EmitBlock(writer, $"for (int i = 0; i < matchLength; i++)")) { using (EmitBlock(writer, $"if ({ToLowerIfNeeded(hasTextInfo, options, $"inputSpan[matchIndex + i]", caseInsensitive)} != {ToLowerIfNeeded(hasTextInfo, options, $"inputSpan[pos - matchLength + i]", caseInsensitive)})")) { Goto(doneLabel); } } writer.WriteLine(); writer.WriteLine($"pos -= matchLength;"); } } } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; // If the child branches might backtrack, we can't emit the branches inside constructs that // require braces, e.g. if/else, even though that would yield more idiomatic output. // But if we know for certain they won't backtrack, we can output the nicer code. if (analysis.IsAtomicByAncestor(node) || (!analysis.MayBacktrack(yesBranch) && (noBranch is null || !analysis.MayBacktrack(noBranch)))) { using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { writer.WriteLine($"// The {DescribeCapture(node.M, analysis)} captured a value. Match the first branch."); EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } if (noBranch is not null) { using (EmitBlock(writer, $"else")) { writer.WriteLine($"// Otherwise, match the second branch."); EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } } doneLabel = originalDoneLabel; // atomicity return; } string refNotMatched = ReserveName("ConditionalBackreferenceNotMatched"); string endConditional = ReserveName("ConditionalBackreferenceEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalbackreference_branch"); writer.WriteLine($"int {resumeAt} = 0;"); // While it would be nicely readable to use an if/else block, if the branches contain // anything that triggers backtracking, labels will end up being defined, and if they're // inside the scope block for the if or else, that will prevent jumping to them from // elsewhere. So we implement the if/else with labels and gotos manually. // Check to see if the specified capture number was captured. using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(refNotMatched); } writer.WriteLine(); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { Goto(endConditional); writer.WriteLine(); } MarkLabel(refNotMatched); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. bool hasBacktracking = postYesDoneLabel != originalDoneLabel || postNoDoneLabel != originalDoneLabel; if (hasBacktracking) { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); // Backtrack section string backtrack = ReserveName("ConditionalBackreferenceBacktrack"); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } } if (needsEndConditional) { MarkLabel(endConditional); } if (hasBacktracking) { // We're not atomic and at least one of the yes or no branches contained backtracking constructs, // so finish outputting our backtracking logic, which involves pushing onto the stack which // branch to backtrack into. EmitStackPush(resumeAt); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookaround. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; string expressionNotMatched = ReserveName("ConditionalExpressionNotMatched"); string endConditional = ReserveName("ConditionalExpressionEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalexpression_branch"); if (!isAtomic) { writer.WriteLine($"int {resumeAt} = 0;"); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. string? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { startingCapturePos = ReserveName("conditionalexpression_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookaround; however, a positive lookaround only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("conditionalexpression_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. writer.WriteLine("// Condition:"); EmitNode(condition); writer.WriteLine(); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. writer.WriteLine("// Condition matched:"); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; writer.WriteLine(); // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } Goto(endConditional); writer.WriteLine(); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. writer.WriteLine("// Condition did not match:"); MarkLabel(expressionNotMatched, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } writer.WriteLine(); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); string backtrack = ReserveName("ConditionalExpressionBacktrack"); doneLabel = backtrack; MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } MarkLabel(endConditional, emitSemicolon: false); EmitStackPush(resumeAt); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, rm.Tree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); TransferSliceStaticPosToPos(); string startingPos = ReserveName("capture_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); RegexNode child = node.Child(0); if (uncapnum != -1) { using (EmitBlock(writer, $"if (!base.IsMatched({uncapnum}))")) { Goto(doneLabel); } writer.WriteLine(); } // Emit child node. string originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; writer.WriteLine(); TransferSliceStaticPosToPos(); if (uncapnum == -1) { writer.WriteLine($"base.Capture({capnum}, {startingPos}, pos);"); } else { writer.WriteLine($"base.TransferCapture({capnum}, {uncapnum}, {startingPos}, pos);"); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. writer.WriteLine(); EmitStackPush(startingPos); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"CaptureBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(startingPos); if (!childBacktracks) { writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); } Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } // Emits the code to handle a positive lookaround assertion. This is a positive lookahead // for left-to-right and a positive lookbehind for right-to-left. void EmitPositiveLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("positivelookaround_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. writer.WriteLine(); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; } // Emits the code to handle a negative lookaround assertion. This is a negative lookahead // for left-to-right and a negative lookbehind for right-to-left. void EmitNegativeLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } string originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("negativelookaround_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; string negativeLookaroundDoneLabel = ReserveName("NegativeLookaroundMatch"); doneLabel = negativeLookaroundDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookaround, which actually // means failure for a _negative_ lookaround, so we need to jump to the original done. writer.WriteLine(); Goto(originalDoneLabel); writer.WriteLine(); // Failures (success for a negative lookaround) jump here. MarkLabel(negativeLookaroundDoneLabel, emitSemicolon: false); // After the child completes in failure (success for negative lookaround), reset the text positions. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } if ((node.Options & RegexOptions.RightToLeft) != 0) { // RightToLeft doesn't take advantage of static positions. While RightToLeft won't update static // positions, a previous operation may have left us with a non-zero one. Make sure it's zero'd out // such that pos and slice are up-to-date. Note that RightToLeft also shouldn't use the slice span, // as it's not kept up-to-date; any RightToLeft implementation that wants to use it must first update // it from pos. TransferSliceStaticPosToPos(); } // Separate out several node types that, for conciseness, don't need a header and scope written into the source. switch (node.Kind) { // Nothing is written for an empty case RegexNodeKind.Empty: return; // A match failure doesn't need a scope. case RegexNodeKind.Nothing: Goto(doneLabel); return; // Skip atomic nodes that wrap non-backtracking children; in such a case there's nothing to be made atomic. case RegexNodeKind.Atomic when !analysis.MayBacktrack(node.Child(0)): EmitNode(node.Child(0)); return; // Concatenate is a simplification in the node tree so that a series of children can be represented as one. // We don't need its presence visible in the source. case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); return; } // Put the node's code into its own scope. If the node contains labels that may need to // be visible outside of its scope, the scope is still emitted for clarity but is commented out. using (EmitScope(writer, DescribeNode(node, analysis), faux: analysis.MayBacktrack(node))) { switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); break; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); break; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Loop: EmitLoop(node); break; case RegexNodeKind.Lazyloop: EmitLazy(node); break; case RegexNodeKind.Alternate: EmitAlternation(node); break; case RegexNodeKind.Backreference: EmitBackreference(node); break; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); break; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); break; case RegexNodeKind.Atomic when analysis.MayBacktrack(node.Child(0)): EmitAtomic(node, subsequent); return; case RegexNodeKind.Capture: EmitCapture(node, subsequent); break; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaroundAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaroundAssertion(node); break; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } } } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(analysis.MayBacktrack(node.Child(0)), "Expected child to potentially backtrack"); // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. string originalDoneLabel = doneLabel; additionalDeclarations.Add("int stackpos = 0;"); string startingStackpos = ReserveName("atomic_stackpos"); writer.WriteLine($"int {startingStackpos} = stackpos;"); writer.WriteLine(); // Emit the child. EmitNode(node.Child(0), subsequent); writer.WriteLine(); // Reset the stack position and done label. writer.WriteLine($"stackpos = {startingStackpos};"); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); TransferSliceStaticPosToPos(); using (EmitBlock(writer, "if (base.runtextpos < pos)")) { writer.WriteLine("base.runtextpos = pos;"); } } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); // Emit the code for each child one after the other. string? prevDescription = null; int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. We also want to minimize the repetition of if blocks, // and so we try to emit a series of clauses all part of the same if block rather than one if block per child. if ((node.Options & RegexOptions.RightToLeft) == 0 && emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { bool wroteClauses = true; writer.Write($"if ({SpanLengthCheck(requiredLength)}"); while (i < exclusiveEnd) { for (; i < exclusiveEnd; i++) { void WriteSingleCharChild(RegexNode child, bool includeDescription = true) { if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $" || // {prevDescription}" : " ||"); writer.Write(" "); } else { writer.Write("if ("); } EmitSingleChar(child, emitLengthCheck: false, clauseOnly: true); prevDescription = includeDescription ? DescribeNode(child, analysis) : null; wroteClauses = true; } RegexNode child = node.Child(i); if (child.Kind is RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set) { WriteSingleCharChild(child); } else if (child.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Onelazy or RegexNodeKind.Oneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloopatomic && child.M == child.N && child.M <= MaxUnrollSize) { for (int c = 0; c < child.M; c++) { WriteSingleCharChild(child, includeDescription: c == 0); } } else { break; } } if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $") // {prevDescription}" : ")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } if (i < childCount) { writer.WriteLine(); } wroteClauses = false; prevDescription = null; } if (i < exclusiveEnd) { EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: false); if (i < childCount - 1) { writer.WriteLine(); } i++; } } i--; continue; } EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: emitLengthChecksIfRequired); if (i < childCount - 1) { writer.WriteLine(); } } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequentOrDefault(int index, RegexNode node, RegexNode? defaultNode) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return defaultNode; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, string? offset = null, bool clauseOnly = false) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Debug.Assert(!rtl || offset is null); Debug.Assert(!rtl || !clauseOnly); string expr = !rtl ? $"{sliceSpan}[{Sum(sliceStaticPos, offset)}]" : "inputSpan[pos - 1]"; if (node.IsSetFamily) { expr = $"{MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: true, additionalDeclarations, ref requiredHelpers)}"; } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "!=" : "==")} {Literal(node.Ch)}"; } if (clauseOnly) { writer.Write(expr); } else { string clause = !emitLengthCheck ? $"if ({expr})" : !rtl ? $"if ({SpanLengthCheck(1, offset)} || {expr})" : $"if ((uint)(pos - 1) >= inputSpan.Length || {expr})"; using (EmitBlock(writer, clause)) { Goto(doneLabel); } } if (!rtl) { sliceStaticPos++; } else { writer.WriteLine("pos--;"); } } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); string call = node.Kind switch { RegexNodeKind.Boundary => "!IsBoundary", RegexNodeKind.NonBoundary => "IsBoundary", RegexNodeKind.ECMABoundary => "!IsECMABoundary", _ => "IsECMABoundary", }; RequiredHelperFunctions boundaryFunctionRequired = node.Kind switch { RegexNodeKind.Boundary or RegexNodeKind.NonBoundary => RequiredHelperFunctions.IsBoundary | RequiredHelperFunctions.IsWordChar, // IsBoundary internally uses IsWordChar _ => RequiredHelperFunctions.IsECMABoundary }; requiredHelpers |= boundaryFunctionRequired; using (EmitBlock(writer, $"if ({call}(inputSpan, pos{(sliceStaticPos > 0 ? $" + {sliceStaticPos}" : "")}))")) { Goto(doneLabel); } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert((node.Options & RegexOptions.RightToLeft) == 0 || sliceStaticPos == 0); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. Goto(doneLabel); } else { using (EmitBlock(writer, node.Kind == RegexNodeKind.Beginning ? "if (pos != 0)" : "if (pos != base.runtextstart)")) { Goto(doneLabel); } } break; case RegexNodeKind.Bol: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceSpan}[{sliceStaticPos - 1}] != '\\n')" : $"if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { Goto(doneLabel); } break; case RegexNodeKind.End: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos} < {sliceSpan}.Length)" : "if ((uint)pos < (uint)inputSpan.Length)")) { Goto(doneLabel); } break; case RegexNodeKind.EndZ: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos + 1} < {sliceSpan}.Length || ({sliceStaticPos} < {sliceSpan}.Length && {sliceSpan}[{sliceStaticPos}] != '\\n'))" : "if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n'))")) { Goto(doneLabel); } break; case RegexNodeKind.Eol: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos} < {sliceSpan}.Length && {sliceSpan}[{sliceStaticPos}] != '\\n')" : "if ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n')")) { Goto(doneLabel); } break; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); Debug.Assert(node.Str is not null); EmitMultiCharString(node.Str, IsCaseInsensitive(node), emitLengthCheck, (node.Options & RegexOptions.RightToLeft) != 0); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck, bool rightToLeft) { Debug.Assert(str.Length >= 2); if (rightToLeft) { Debug.Assert(emitLengthCheck); using (EmitBlock(writer, $"if ((uint)(pos - {str.Length}) >= inputSpan.Length)")) { Goto(doneLabel); } writer.WriteLine(); using (EmitBlock(writer, $"for (int i = 0; i < {str.Length}; i++)")) { using (EmitBlock(writer, $"if ({ToLowerIfNeeded(hasTextInfo, options, "inputSpan[--pos]", caseInsensitive)} != {Literal(str)}[{str.Length - 1} - i])")) { Goto(doneLabel); } } return; } if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } using (EmitBlock(writer, $"for (int i = 0; i < {Literal(str)}.Length; i++)")) { string textSpanIndex = sliceStaticPos > 0 ? $"i + {sliceStaticPos}" : "i"; using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"{sliceSpan}[{textSpanIndex}]")} != {Literal(str)}[i])")) { Goto(doneLabel); } } } else { string sourceSpan = sliceStaticPos > 0 ? $"{sliceSpan}.Slice({sliceStaticPos})" : sliceSpan; using (EmitBlock(writer, $"if (!global::System.MemoryExtensions.StartsWith({sourceSpan}, {Literal(str)}))")) { Goto(doneLabel); } } sliceStaticPos += str.Length; } void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); string backtrackingLabel = ReserveName("CharLoopBacktrack"); string endLoop = ReserveName("CharLoopEnd"); string startingPos = ReserveName("charloop_starting_pos"); string endingPos = ReserveName("charloop_ending_pos"); additionalDeclarations.Add($"int {startingPos} = 0, {endingPos} = 0;"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); EmitSingleCharAtomicLoop(node); writer.WriteLine(); TransferSliceStaticPosToPos(); writer.WriteLine($"{endingPos} = pos;"); EmitAdd(writer, startingPos, !rtl ? node.M : -node.M); Goto(endLoop); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel, emitSemicolon: false); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } EmitStackPop(endingPos, startingPos); writer.WriteLine(); if (!rtl && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { writer.WriteLine($"if ({startingPos} >= {endingPos} ||"); using (EmitBlock(writer, literal.Item2 is not null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, global::System.Math.Min(inputSpan.Length, {endingPos} + {literal.Item2.Length - 1}) - {startingPos}), {Literal(literal.Item2)})) < 0)" : literal.Item3 is null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item1)})) < 0)" : literal.Item3.Length switch { 2 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])})) < 0)", 3 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])}, {Literal(literal.Item3[2])})) < 0)", _ => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3)})) < 0)", })) { Goto(doneLabel); } writer.WriteLine($"{endingPos} += {startingPos};"); writer.WriteLine($"pos = {endingPos};"); } else { using (EmitBlock(writer, $"if ({startingPos} {(!rtl ? ">=" : "<=")} {endingPos})")) { Goto(doneLabel); } writer.WriteLine(!rtl ? $"pos = --{endingPos};" : $"pos = ++{endingPos};"); } if (!rtl) { SliceInputSpan(writer); } writer.WriteLine(); MarkLabel(endLoop, emitSemicolon: false); EmitStackPush(expressionHasCaptures ? new[] { startingPos, endingPos, "base.Crawlpos()" } : new[] { startingPos, endingPos }); doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } if (node.M > 0) { // We emitted a repeater to handle the required iterations; add a newline after it. writer.WriteLine(); } Debug.Assert(node.M < node.N); // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. string? iterationCount = null; string? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = $"{node.N - node.M}"; iterationCount = ReserveName("lazyloop_iteration"); writer.WriteLine($"int {iterationCount} = 0;"); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. string? capturePos = null; if (expressionHasCaptures) { capturePos = ReserveName("lazyloop_capturepos"); additionalDeclarations.Add($"int {capturePos} = 0;"); } // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. string startingPos = ReserveName("lazyloop_pos"); additionalDeclarations.Add($"int {startingPos} = 0;"); writer.WriteLine($"{startingPos} = pos;"); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. string endLoopLabel = ReserveName("LazyLoopEnd"); Goto(endLoopLabel); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here. string backtrackingLabel = ReserveName("LazyLoopBacktrack"); MarkLabel(backtrackingLabel, emitSemicolon: false); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturePos is not null) { EmitUncaptureUntil(capturePos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { using (EmitBlock(writer, $"if ({iterationCount} >= {maxIterations})")) { Goto(doneLabel); } writer.WriteLine($"{iterationCount}++;"); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if ((node.Options & RegexOptions.RightToLeft) == 0) { if (iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). writer.WriteLine( literal.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item2[0])});" : literal.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item1)});" : literal.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch + literal.Item3)});", }); using (EmitBlock(writer, $"if ((uint){startingPos} >= (uint){sliceSpan}.Length || {sliceSpan}[{startingPos}] == {Literal(node.Ch)})")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } else if (iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. writer.WriteLine( literal2.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item2)});" : literal2.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item1)});" : literal2.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])});", 3 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])}, {Literal(literal2.Item3[2])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3)});", }); using (EmitBlock(writer, $"if ({startingPos} < 0)")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } } // Store the position we've left off at in case we need to iterate again. writer.WriteLine($"{startingPos} = pos;"); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. string originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes writer.WriteLine(); MarkLabel(endLoopLabel); if (capturePos is not null) { writer.WriteLine($"{capturePos} = base.Crawlpos();"); } if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state var toPushPop = new List<string>(3) { startingPos }; if (capturePos is not null) { toPushPop.Add(capturePos); } if (iterationCount is not null) { toPushPop.Add(iterationCount); } string[] toPushPopArray = toPushPop.ToArray(); EmitStackPush(toPushPopArray); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("CharLazyBacktrack"); MarkLabel(backtrack, emitSemicolon: false); Array.Reverse(toPushPopArray); EmitStackPop(toPushPopArray); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; string originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } writer.WriteLine(); } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string startingPos = ReserveName("lazyloop_starting_pos"); string iterationCount = ReserveName("lazyloop_iteration"); string sawEmpty = ReserveName("lazyLoopEmptySeen"); string body = ReserveName("LazyLoopBody"); string endLoop = ReserveName("LazyLoopEnd"); writer.WriteLine($"int {iterationCount} = 0, {startingPos} = pos, {sawEmpty} = 0;"); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { Goto(endLoop); } writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos", sawEmpty } : new[] { startingPos, "pos", sawEmpty }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LazyLoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(body); } } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. using (EmitBlock(writer, $"if (pos == {startingPos})")) { writer.WriteLine($"{sawEmpty} = 1;"); } // We matched the next iteration. Jump to the subsequent code. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop(sawEmpty, "pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (doneLabel == originalDoneLabel) { Goto(originalDoneLabel); } else { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); } writer.WriteLine(); MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackPush(startingPos, iterationCount, sawEmpty); string skipBacktrack = ReserveName("SkipBacktrack"); Goto(skipBacktrack); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"LazyLoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(sawEmpty, iterationCount, startingPos); if (maxIterations == int.MaxValue) { using (EmitBlock(writer, $"if ({sawEmpty} == 0)")) { Goto(body); } } else { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, maxIterations)} && {sawEmpty} == 0)")) { Goto(body); } } Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthCheck = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthCheck); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthCheck, rtl); return; } if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position with rtl using (EmitBlock(writer, $"for (int i = 0; i < {iterations}; i++)")) { EmitTimeoutCheck(writer, hasTimeout); EmitSingleChar(node); } } else if (iterations <= MaxUnrollSize) { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length || // slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // { // goto doneLabel; // } writer.Write($"if ("); if (emitLengthCheck) { writer.WriteLine($"{SpanLengthCheck(iterations)} ||"); writer.Write(" "); } EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); for (int i = 1; i < iterations; i++) { writer.WriteLine(" ||"); writer.Write(" "); EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); } writer.WriteLine(")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } } else { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthCheck) { EmitSpanLengthCheck(iterations); } string repeaterSpan = "repeaterSlice"; // As this repeater doesn't wrap arbitrary node emits, this shouldn't conflict with anything writer.WriteLine($"global::System.ReadOnlySpan<char> {repeaterSpan} = {sliceSpan}.Slice({sliceStaticPos}, {iterations});"); using (EmitBlock(writer, $"for (int i = 0; i < {repeaterSpan}.Length; i++)")) { EmitTimeoutCheck(writer, hasTimeout); string tmpTextSpanLocal = sliceSpan; // we want EmitSingleChar to refer to this temporary int tmpSliceStaticPos = sliceStaticPos; sliceSpan = repeaterSpan; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: "i"); sliceSpan = tmpTextSpanLocal; sliceStaticPos = tmpSliceStaticPos; } sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Span<char> setChars = stackalloc char[5]; // 5 is max optimized by IndexOfAny today int numSetChars = 0; string iterationLocal = ReserveName("iteration"); if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position for rtl string expr = $"inputSpan[pos - {iterationLocal} - 1]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } writer.WriteLine($"int {iterationLocal} = 0;"); string maxClause = maxIterations != int.MaxValue ? $"{CountIsLessThan(iterationLocal, maxIterations)} && " : ""; using (EmitBlock(writer, $"while ({maxClause}pos > {iterationLocal} && {expr})")) { EmitTimeoutCheck(writer, hasTimeout); writer.WriteLine($"{iterationLocal}++;"); } writer.WriteLine(); } else if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOf({sliceSpan}"); if (sliceStaticPos > 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine($", {Literal(node.Ch)});"); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it should // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}"); if (sliceStaticPos != 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine(numSetChars switch { 2 => $", {Literal(setChars[0])}, {Literal(setChars[1])});", 3 => $", {Literal(setChars[0])}, {Literal(setChars[1])}, {Literal(setChars[2])});", _ => $", {Literal(setChars.Slice(0, numSetChars).ToString())});", }); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. TransferSliceStaticPosToPos(); writer.WriteLine($"int {iterationLocal} = inputSpan.Length - pos;"); } else { // For everything else, do a normal loop. string expr = $"{sliceSpan}[{iterationLocal}]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } if (minIterations != 0 || maxIterations != int.MaxValue) { // For any loops other than * loops, transfer text pos to pos in // order to zero it out to be able to use the single iteration variable // for both iteration count and indexer. TransferSliceStaticPosToPos(); } writer.WriteLine($"int {iterationLocal} = {sliceStaticPos};"); sliceStaticPos = 0; string maxClause = maxIterations != int.MaxValue ? $"{CountIsLessThan(iterationLocal, maxIterations)} && " : ""; using (EmitBlock(writer, $"while ({maxClause}(uint){iterationLocal} < (uint){sliceSpan}.Length && {expr})")) { EmitTimeoutCheck(writer, hasTimeout); writer.WriteLine($"{iterationLocal}++;"); } writer.WriteLine(); } // Check to ensure we've found at least min iterations. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationLocal, minIterations)})")) { Goto(doneLabel); } writer.WriteLine(); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. if (!rtl) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice({iterationLocal});"); writer.WriteLine($"pos += {iterationLocal};"); } else { writer.WriteLine($"pos -= {iterationLocal};"); } } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static pos for rtl } string expr = !rtl ? $"{sliceSpan}[{sliceStaticPos}]" : "inputSpan[pos - 1]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } string spaceAvailable = rtl ? "pos > 0" : sliceStaticPos != 0 ? $"(uint){sliceSpan}.Length > (uint){sliceStaticPos}" : $"!{sliceSpan}.IsEmpty"; using (EmitBlock(writer, $"if ({spaceAvailable} && {expr})")) { if (!rtl) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice(1);"); writer.WriteLine($"pos++;"); } else { writer.WriteLine($"pos--;"); } } } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. string i = ReserveName("loop_iteration"); using (EmitBlock(writer, $"for (int {i} = 0; {i} < {node.M}; {i}++)")) { EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs } } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string originalDoneLabel = doneLabel; string startingPos = ReserveName("loop_starting_pos"); string iterationCount = ReserveName("loop_iteration"); string body = ReserveName("LoopBody"); string endLoop = ReserveName("LoopEnd"); additionalDeclarations.Add($"int {iterationCount} = 0, {startingPos} = 0;"); writer.WriteLine($"{iterationCount} = 0;"); writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos" } : new[] { startingPos, "pos" }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); writer.WriteLine(); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. using (EmitBlock(writer, (minIterations > 0, maxIterations == int.MaxValue) switch { (true, true) => $"if (pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)})", (true, false) => $"if ((pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)}) && {CountIsLessThan(iterationCount, maxIterations)})", (false, true) => $"if (pos != {startingPos})", (false, false) => $"if (pos != {startingPos} && {CountIsLessThan(iterationCount, maxIterations)})", })) { Goto(body); } // We've matched as many iterations as we can with this configuration. Jump to what comes after the loop. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop("pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (minIterations > 0) { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(childBacktracks ? doneLabel : originalDoneLabel); } } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { Goto(endLoop); writer.WriteLine(); string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state EmitStackPush(startingPos, iterationCount); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(iterationCount, startingPos); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } } // Gets a comparison for whether the value is less than the upper bound. static string CountIsLessThan(string value, int exclusiveUpper) => exclusiveUpper == 1 ? $"{value} == 0" : $"{value} < {exclusiveUpper}"; // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(string capturepos) { string name = "UncaptureUntil"; if (!additionalLocalFunctions.ContainsKey(name)) { var lines = new string[9]; lines[0] = "// <summary>Undo captures until we reach the specified capture position.</summary>"; lines[1] = "[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"void {name}(int capturepos)"; lines[3] = "{"; lines[4] = " while (base.Crawlpos() > capturepos)"; lines[5] = " {"; lines[6] = " base.Uncapture();"; lines[7] = " }"; lines[8] = "}"; additionalLocalFunctions.Add(name, lines); } writer.WriteLine($"{name}({capturepos});"); } /// <summary>Pushes values on to the backtracking stack.</summary> void EmitStackPush(params string[] args) { Debug.Assert(args.Length is >= 1); string function = $"StackPush{args.Length}"; additionalDeclarations.Add("int stackpos = 0;"); if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[24 + args.Length]; lines[0] = $"// <summary>Push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[3] = $"{{"; lines[4] = $" // If there's space available for {(args.Length > 1 ? $"all {args.Length} values, store them" : "the value, store it")}."; lines[5] = $" int[] s = stack;"; lines[6] = $" int p = pos;"; lines[7] = $" if ((uint){(args.Length > 1 ? $"(p + {args.Length - 1})" : "p")} < (uint)s.Length)"; lines[8] = $" {{"; for (int i = 0; i < args.Length; i++) { lines[9 + i] = $" s[p{(i == 0 ? "" : $" + {i}")}] = arg{i};"; } lines[9 + args.Length] = args.Length > 1 ? $" pos += {args.Length};" : " pos++;"; lines[10 + args.Length] = $" return;"; lines[11 + args.Length] = $" }}"; lines[12 + args.Length] = $""; lines[13 + args.Length] = $" // Otherwise, resize the stack to make room and try again."; lines[14 + args.Length] = $" WithResize(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[15 + args.Length] = $""; lines[16 + args.Length] = $" // <summary>Resize the backtracking stack array and push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the stack.</summary>"; lines[17 + args.Length] = $" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]"; lines[18 + args.Length] = $" static void WithResize(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[19 + args.Length] = $" {{"; lines[20 + args.Length] = $" global::System.Array.Resize(ref stack, (pos + {args.Length - 1}) * 2);"; lines[21 + args.Length] = $" {function}(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[22 + args.Length] = $" }}"; lines[23 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(ref base.runstack!, ref stackpos, {string.Join(", ", args)});"); } /// <summary>Pops values from the backtracking stack into the specified locations.</summary> void EmitStackPop(params string[] args) { Debug.Assert(args.Length is >= 1); if (args.Length == 1) { writer.WriteLine($"{args[0]} = {StackPop()};"); return; } string function = $"StackPop{args.Length}"; if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[5 + args.Length]; lines[0] = $"// <summary>Pop {args.Length} value{(args.Length == 1 ? "" : "s")} from the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(int[] stack, ref int pos{FormatN(", out int arg{0}", args.Length)})"; lines[3] = $"{{"; for (int i = 0; i < args.Length; i++) { lines[4 + i] = $" arg{i} = stack[--pos];"; } lines[4 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(base.runstack, ref stackpos, out {string.Join(", out ", args)});"); } /// <summary>Expression for popping the next item from the backtracking stack.</summary> string StackPop() => "base.runstack![--stackpos]"; /// <summary>Concatenates the strings resulting from formatting the format string with the values [0, count).</summary> static string FormatN(string format, int count) => string.Concat(from i in Enumerable.Range(0, count) select string.Format(format, i)); } private static bool EmitLoopTimeoutCounterIfNeeded(IndentedTextWriter writer, RegexMethod rm) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("int loopTimeoutCounter = 0;"); return true; } return false; } /// <summary>Emits a timeout check.</summary> private static void EmitTimeoutCheck(IndentedTextWriter writer, bool hasTimeout) { const int LoopTimeoutCheckCount = 2048; // A conservative value to guarantee the correct timeout handling. if (hasTimeout) { // Increment counter for each loop iteration. // Emit code to check the timeout every 2048th iteration. using (EmitBlock(writer, $"if (++loopTimeoutCounter == {LoopTimeoutCheckCount})")) { writer.WriteLine("loopTimeoutCounter = 0;"); writer.WriteLine("base.CheckTimeout();"); } writer.WriteLine(); } } private static bool EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(IndentedTextWriter writer, RegexMethod rm, AnalysisResults analysis) { if (analysis.HasIgnoreCase && ((RegexOptions)rm.Options & RegexOptions.CultureInvariant) == 0) { writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); return true; } return false; } private static bool UseToLowerInvariant(bool hasTextInfo, RegexOptions options) => !hasTextInfo || (options & RegexOptions.CultureInvariant) != 0; private static string ToLower(bool hasTextInfo, RegexOptions options, string expression) => UseToLowerInvariant(hasTextInfo, options) ? $"char.ToLowerInvariant({expression})" : $"textInfo.ToLower({expression})"; private static string ToLowerIfNeeded(bool hasTextInfo, RegexOptions options, string expression, bool toLower) => toLower ? ToLower(hasTextInfo, options, expression) : expression; private static string MatchCharacterClass(bool hasTextInfo, RegexOptions options, string chExpr, string charClass, bool caseInsensitive, bool negate, HashSet<string> additionalDeclarations, ref RequiredHelperFunctions requiredHelpers) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // ideally this could just be "return true;", but we need to evaluate the expression for its side effects return $"({chExpr} {(negate ? "<" : ">=")} 0)"; // a char is unsigned and thus won't ever be negative case RegexCharClass.DigitClass: case RegexCharClass.NotDigitClass: negate ^= charClass == RegexCharClass.NotDigitClass; return $"{(negate ? "!" : "")}char.IsDigit({chExpr})"; case RegexCharClass.SpaceClass: case RegexCharClass.NotSpaceClass: negate ^= charClass == RegexCharClass.NotSpaceClass; return $"{(negate ? "!" : "")}char.IsWhiteSpace({chExpr})"; case RegexCharClass.WordClass: case RegexCharClass.NotWordClass: requiredHelpers |= RequiredHelperFunctions.IsWordChar; negate ^= charClass == RegexCharClass.NotWordClass; return $"{(negate ? "!" : "")}IsWordChar({chExpr})"; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant(hasTextInfo, options); if (!invariant) { chExpr = ToLower(hasTextInfo, options, chExpr); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { negate ^= RegexCharClass.IsNegated(charClass); return lowInclusive == highInclusive ? $"({chExpr} {(negate ? "!=" : "==")} {Literal(lowInclusive)})" : $"(((uint){chExpr}) - {Literal(lowInclusive)} {(negate ? ">" : "<=")} (uint)({Literal(highInclusive)} - {Literal(lowInclusive)}))"; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { negate ^= negated; return $"(char.GetUnicodeCategory({chExpr}) {(negate ? "!=" : "==")} global::System.Globalization.UnicodeCategory.{category})"; } // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it may be cheaper and smaller to compare against each than it is to use a lookup table. We can also special-case // the very common case with case insensitivity of two characters next to each other being the upper and lowercase // ASCII variants of each other, in which case we can use bit manipulation to avoid a comparison. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int mask; switch (RegexCharClass.GetSetChars(charClass, setChars)) { case 2: if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) { return $"(({chExpr} | 0x{mask:X}) {(negate ? "!=" : "==")} {Literal((char)(setChars[1] | mask))})"; } additionalDeclarations.Add("char ch;"); return negate ? $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}))" : $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}))"; case 3: additionalDeclarations.Add("char ch;"); return (negate, RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) switch { (false, false) => $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}) | (ch == {Literal(setChars[2])}))", (true, false) => $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}) & (ch != {Literal(setChars[2])}))", (false, true) => $"((((ch = {chExpr}) | 0x{mask:X}) == {Literal((char)(setChars[1] | mask))}) | (ch == {Literal(setChars[2])}))", (true, true) => $"((((ch = {chExpr}) | 0x{mask:X}) != {Literal((char)(setChars[1] | mask))}) & (ch != {Literal(setChars[2])}))", }; } } // All options after this point require a ch local. additionalDeclarations.Add("char ch;"); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) return negate ? $"((ch = {chExpr}) < 128 || !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) >= 128 && global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. return negate ? $"((ch = {chExpr}) >= 128 && !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) < 128 || global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = StringExtensions.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. return negate ? $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. return negate ? $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. return (negate, invariant) switch { (false, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (true, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (false, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", (true, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", }; } /// <summary> /// Replaces <see cref="AdditionalDeclarationsPlaceholder"/> in <paramref name="writer"/> with /// all of the variable declarations in <paramref name="declarations"/>. /// </summary> /// <param name="writer">The writer around a StringWriter to have additional declarations inserted into.</param> /// <param name="declarations">The additional declarations to insert.</param> /// <param name="position">The position into the writer at which to insert the additional declarations.</param> /// <param name="indent">The indentation to use for the additional declarations.</param> private static void ReplaceAdditionalDeclarations(IndentedTextWriter writer, HashSet<string> declarations, int position, int indent) { if (declarations.Count != 0) { var tmp = new StringBuilder(); foreach (string decl in declarations.OrderBy(s => s)) { for (int i = 0; i < indent; i++) { tmp.Append(IndentedTextWriter.DefaultTabString); } tmp.AppendLine(decl); } ((StringWriter)writer.InnerWriter).GetStringBuilder().Insert(position, tmp.ToString()); } } /// <summary>Formats the character as valid C#.</summary> private static string Literal(char c) => SymbolDisplay.FormatLiteral(c, quote: true); /// <summary>Formats the string as valid C#.</summary> private static string Literal(string s) => SymbolDisplay.FormatLiteral(s, quote: true); private static string Literal(RegexOptions options) { string s = options.ToString(); if (int.TryParse(s, out _)) { // The options were formatted as an int, which means the runtime couldn't // produce a textual representation. So just output casting the value as an int. return $"(global::System.Text.RegularExpressions.RegexOptions)({(int)options})"; } // Parse the runtime-generated "Option1, Option2" into each piece and then concat // them back together. string[] parts = s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parts.Length; i++) { parts[i] = "global::System.Text.RegularExpressions.RegexOptions." + parts[i].Trim(); } return string.Join(" | ", parts); } /// <summary>Gets a textual description of the node fit for rendering in a comment in source.</summary> private static string DescribeNode(RegexNode node, AnalysisResults analysis) { bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; return node.Kind switch { RegexNodeKind.Alternate => $"Match with {node.ChildCount()} alternative expressions{(analysis.IsAtomicByAncestor(node) ? ", atomically" : "")}.", RegexNodeKind.Atomic => $"Atomic group.", RegexNodeKind.Beginning => "Match if at the beginning of the string.", RegexNodeKind.Bol => "Match if at the beginning of a line.", RegexNodeKind.Boundary => $"Match if at a word boundary.", RegexNodeKind.Capture when node.M == -1 && node.N != -1 => $"Non-capturing balancing group. Uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N != -1 => $"Balancing group. Captures the {DescribeCapture(node.M, analysis)} and uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N == -1 => $"{DescribeCapture(node.M, analysis)}.", RegexNodeKind.Concatenate => "Match a sequence of expressions.", RegexNodeKind.ECMABoundary => $"Match if at a word boundary (according to ECMAScript rules).", RegexNodeKind.Empty => $"Match an empty string.", RegexNodeKind.End => "Match if at the end of the string.", RegexNodeKind.EndZ => "Match if at the end of the string or if before an ending newline.", RegexNodeKind.Eol => "Match if at the end of a line.", RegexNodeKind.Loop or RegexNodeKind.Lazyloop => node.M == 0 && node.N == 1 ? $"Optional ({(node.Kind is RegexNodeKind.Loop ? "greedy" : "lazy")})." : $"Loop {DescribeLoop(node, analysis)}.", RegexNodeKind.Multi => $"Match the string {Literal(node.Str!)}{(rtl ? " backwards" : "")}.", RegexNodeKind.NonBoundary => $"Match if at anything other than a word boundary.", RegexNodeKind.NonECMABoundary => $"Match if at anything other than a word boundary (according to ECMAScript rules).", RegexNodeKind.Nothing => $"Fail to match.", RegexNodeKind.Notone => $"Match any character other than {Literal(node.Ch)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy => $"Match a character other than {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.One => $"Match {Literal(node.Ch)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy => $"Match {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.NegativeLookaround => $"Zero-width negative {(rtl ? "lookbehind" : "lookahead")}.", RegexNodeKind.Backreference => $"Match the same text as matched by the {DescribeCapture(node.M, analysis)}.", RegexNodeKind.PositiveLookaround => $"Zero-width positive {(rtl ? "lookbehind" : "lookahead")}.", RegexNodeKind.Set => $"Match {DescribeSet(node.Str!)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy => $"Match {DescribeSet(node.Str!)} {DescribeLoop(node, analysis)}.", RegexNodeKind.Start => "Match if at the start position.", RegexNodeKind.ExpressionConditional => $"Conditionally match one of two expressions depending on whether an initial expression matches.", RegexNodeKind.BackreferenceConditional => $"Conditionally match one of two expressions depending on whether the {DescribeCapture(node.M, analysis)} matched.", RegexNodeKind.UpdateBumpalong => $"Advance the next matching position.", _ => $"Unknown node type {node.Kind}", }; } /// <summary>Gets an identifer to describe a capture group.</summary> private static string DescribeCapture(int capNum, AnalysisResults analysis) { // If we can get a capture name from the captures collection and it's not just a numerical representation of the group, use it. string name = RegexParser.GroupNameFromNumber(analysis.RegexTree.CaptureNumberSparseMapping, analysis.RegexTree.CaptureNames, analysis.RegexTree.CaptureCount, capNum); if (!string.IsNullOrEmpty(name) && (!int.TryParse(name, out int id) || id != capNum)) { name = Literal(name); } else { // Otherwise, create a numerical description of the capture group. int tens = capNum % 10; name = tens is >= 1 and <= 3 && capNum % 100 is < 10 or > 20 ? // Ends in 1, 2, 3 but not 11, 12, or 13 tens switch { 1 => $"{capNum}st", 2 => $"{capNum}nd", _ => $"{capNum}rd", } : $"{capNum}th"; } return $"{name} capture group"; } /// <summary>Gets a textual description of what characters match a set.</summary> private static string DescribeSet(string charClass) => charClass switch { RegexCharClass.AnyClass => "any character", RegexCharClass.DigitClass => "a Unicode digit", RegexCharClass.ECMADigitClass => "'0' through '9'", RegexCharClass.ECMASpaceClass => "a whitespace character (ECMA)", RegexCharClass.ECMAWordClass => "a word character (ECMA)", RegexCharClass.NotDigitClass => "any character other than a Unicode digit", RegexCharClass.NotECMADigitClass => "any character other than '0' through '9'", RegexCharClass.NotECMASpaceClass => "any character other than a space character (ECMA)", RegexCharClass.NotECMAWordClass => "any character other than a word character (ECMA)", RegexCharClass.NotSpaceClass => "any character other than a space character", RegexCharClass.NotWordClass => "any character other than a word character", RegexCharClass.SpaceClass => "a whitespace character", RegexCharClass.WordClass => "a word character", _ => $"a character in the set {RegexCharClass.DescribeSet(charClass)}", }; /// <summary>Writes a textual description of the node tree fit for rending in source.</summary> /// <param name="writer">The writer to which the description should be written.</param> /// <param name="node">The node being written.</param> /// <param name="prefix">The prefix to write at the beginning of every line, including a "//" for a comment.</param> /// <param name="analyses">Analysis of the tree</param> /// <param name="depth">The depth of the current node.</param> private static void DescribeExpression(TextWriter writer, RegexNode node, string prefix, AnalysisResults analysis, int depth = 0) { bool skip = node.Kind switch { // For concatenations, flatten the contents into the parent, but only if the parent isn't a form of alternation, // where each branch is considered to be independent rather than a concatenation. RegexNodeKind.Concatenate when node.Parent is not { Kind: RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional } => true, // For atomic, skip the node if we'll instead render the atomic label as part of rendering the child. RegexNodeKind.Atomic when node.Child(0).Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop or RegexNodeKind.Alternate => true, // Don't skip anything else. _ => false, }; if (!skip) { string tag = node.Parent?.Kind switch { RegexNodeKind.ExpressionConditional when node.Parent.Child(0) == node => "Condition: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(1) == node => "Matched: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(2) == node => "Not Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(0) == node => "Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(1) == node => "Not Matched: ", _ => "", }; // Write out the line for the node. const char BulletPoint = '\u25CB'; writer.WriteLine($"{prefix}{new string(' ', depth * 4)}{BulletPoint} {tag}{DescribeNode(node, analysis)}"); } // Recur into each of its children. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { int childDepth = skip ? depth : depth + 1; DescribeExpression(writer, node.Child(i), prefix, analysis, childDepth); } } /// <summary>Gets a textual description of a loop's style and bounds.</summary> private static string DescribeLoop(RegexNode node, AnalysisResults analysis) { string style = node.Kind switch { _ when node.M == node.N => "exactly", RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic => "atomically", RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop => "greedily", RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy => "lazily", RegexNodeKind.Loop => analysis.IsAtomicByAncestor(node) ? "greedily and atomically" : "greedily", _ /* RegexNodeKind.Lazyloop */ => analysis.IsAtomicByAncestor(node) ? "lazily and atomically" : "lazily", }; string bounds = node.M == node.N ? $" {node.M} times" : (node.M, node.N) switch { (0, int.MaxValue) => " any number of times", (1, int.MaxValue) => " at least once", (2, int.MaxValue) => " at least twice", (_, int.MaxValue) => $" at least {node.M} times", (0, 1) => ", optionally", (0, _) => $" at most {node.N} times", _ => $" at least {node.M} and at most {node.N} times" }; return style + bounds; } private static FinishEmitScope EmitScope(IndentedTextWriter writer, string title, bool faux = false) => EmitBlock(writer, $"// {title}", faux: faux); private static FinishEmitScope EmitBlock(IndentedTextWriter writer, string? clause, bool faux = false) { if (clause is not null) { writer.WriteLine(clause); } writer.WriteLine(faux ? "//{" : "{"); writer.Indent++; return new FinishEmitScope(writer, faux); } private static void EmitAdd(IndentedTextWriter writer, string variable, int value) { if (value == 0) { return; } writer.WriteLine( value == 1 ? $"{variable}++;" : value == -1 ? $"{variable}--;" : value > 0 ? $"{variable} += {value};" : value < 0 && value > int.MinValue ? $"{variable} -= {-value};" : $"{variable} += {value.ToString(CultureInfo.InvariantCulture)};"); } private readonly struct FinishEmitScope : IDisposable { private readonly IndentedTextWriter _writer; private readonly bool _faux; public FinishEmitScope(IndentedTextWriter writer, bool faux) { _writer = writer; _faux = faux; } public void Dispose() { if (_writer is not null) { _writer.Indent--; _writer.WriteLine(_faux ? "//}" : "}"); } } } /// <summary>Bit flags indicating which additional helpers should be emitted into the regex class.</summary> [Flags] private enum RequiredHelperFunctions { /// <summary>No additional functions are required.</summary> None = 0b0, /// <summary>The IsWordChar helper is required.</summary> IsWordChar = 0b1, /// <summary>The IsBoundary helper is required.</summary> IsBoundary = 0b10, /// <summary>The IsECMABoundary helper is required.</summary> IsECMABoundary = 0b100 } } }
// 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; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; // NOTE: The logic in this file is largely a copy of logic in RegexCompiler, emitting C# instead of MSIL. // Most changes made to this file should be kept in sync, so far as bug fixes and relevant optimizations // are concerned. namespace System.Text.RegularExpressions.Generator { public partial class RegexGenerator { /// <summary>Code for a [GeneratedCode] attribute to put on the top-level generated members.</summary> private static readonly string s_generatedCodeAttribute = $"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{typeof(RegexGenerator).Assembly.GetName().Name}\", \"{typeof(RegexGenerator).Assembly.GetName().Version}\")]"; /// <summary>Header comments and usings to include at the top of every generated file.</summary> private static readonly string[] s_headers = new string[] { "// <auto-generated/>", "#nullable enable", "#pragma warning disable CS0162 // Unreachable code", "#pragma warning disable CS0164 // Unreferenced label", "#pragma warning disable CS0219 // Variable assigned but never used", "", }; /// <summary>Generates the code for one regular expression class.</summary> private static (string, ImmutableArray<Diagnostic>) EmitRegexType(RegexType regexClass, bool allowUnsafe) { var sb = new StringBuilder(1024); var writer = new IndentedTextWriter(new StringWriter(sb)); // Emit the namespace if (!string.IsNullOrWhiteSpace(regexClass.Namespace)) { writer.WriteLine($"namespace {regexClass.Namespace}"); writer.WriteLine("{"); writer.Indent++; } // Emit containing types RegexType? parent = regexClass.ParentClass; var parentClasses = new Stack<string>(); while (parent is not null) { parentClasses.Push($"partial {parent.Keyword} {parent.Name}"); parent = parent.ParentClass; } while (parentClasses.Count != 0) { writer.WriteLine($"{parentClasses.Pop()}"); writer.WriteLine("{"); writer.Indent++; } // Emit the direct parent type writer.WriteLine($"partial {regexClass.Keyword} {regexClass.Name}"); writer.WriteLine("{"); writer.Indent++; // Generate a name to describe the regex instance. This includes the method name // the user provided and a non-randomized (for determinism) hash of it to try to make // the name that much harder to predict. Debug.Assert(regexClass.Method is not null); string generatedName = $"GeneratedRegex_{regexClass.Method.MethodName}_"; generatedName += ComputeStringHash(generatedName).ToString("X"); // Generate the regex type ImmutableArray<Diagnostic> diagnostics = EmitRegexMethod(writer, regexClass.Method, generatedName, allowUnsafe); while (writer.Indent != 0) { writer.Indent--; writer.WriteLine("}"); } writer.Flush(); return (sb.ToString(), diagnostics); // FNV-1a hash function. The actual algorithm used doesn't matter; just something simple // to create a deterministic, pseudo-random value that's based on input text. static uint ComputeStringHash(string s) { uint hashCode = 2166136261; foreach (char c in s) { hashCode = (c ^ hashCode) * 16777619; } return hashCode; } } /// <summary>Generates the code for a regular expression method.</summary> private static ImmutableArray<Diagnostic> EmitRegexMethod(IndentedTextWriter writer, RegexMethod rm, string id, bool allowUnsafe) { string patternExpression = Literal(rm.Pattern); string optionsExpression = Literal(rm.Options); string timeoutExpression = rm.MatchTimeout == Timeout.Infinite ? "global::System.Threading.Timeout.InfiniteTimeSpan" : $"global::System.TimeSpan.FromMilliseconds({rm.MatchTimeout.ToString(CultureInfo.InvariantCulture)})"; writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine($"{rm.Modifiers} global::System.Text.RegularExpressions.Regex {rm.MethodName}() => {id}.Instance;"); writer.WriteLine(); writer.WriteLine(s_generatedCodeAttribute); writer.WriteLine("[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]"); writer.WriteLine($"{(writer.Indent != 0 ? "private" : "internal")} sealed class {id} : global::System.Text.RegularExpressions.Regex"); writer.WriteLine("{"); writer.Write(" public static global::System.Text.RegularExpressions.Regex Instance { get; } = "); // If we can't support custom generation for this regex, spit out a Regex constructor call. if (!rm.Tree.Root.SupportsCompilation(out string? reason)) { writer.WriteLine(); writer.WriteLine($" // Cannot generate Regex-derived implementation because {reason}."); writer.WriteLine($" new global::System.Text.RegularExpressions.Regex({patternExpression}, {optionsExpression}, {timeoutExpression});"); writer.WriteLine("}"); return ImmutableArray.Create(Diagnostic.Create(DiagnosticDescriptors.LimitedSourceGeneration, rm.MethodSyntax.GetLocation())); } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(rm.Tree); writer.WriteLine($"new {id}();"); writer.WriteLine(); writer.WriteLine($" private {id}()"); writer.WriteLine($" {{"); writer.WriteLine($" base.pattern = {patternExpression};"); writer.WriteLine($" base.roptions = {optionsExpression};"); writer.WriteLine($" base.internalMatchTimeout = {timeoutExpression};"); writer.WriteLine($" base.factory = new RunnerFactory();"); if (rm.Tree.CaptureNumberSparseMapping is not null) { writer.Write(" base.Caps = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNumberSparseMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNameToNumberMapping is not null) { writer.Write(" base.CapNames = new global::System.Collections.Hashtable {"); AppendHashtableContents(writer, rm.Tree.CaptureNameToNumberMapping); writer.WriteLine(" };"); } if (rm.Tree.CaptureNames is not null) { writer.Write(" base.capslist = new string[] {"); string separator = ""; foreach (string s in rm.Tree.CaptureNames) { writer.Write(separator); writer.Write(Literal(s)); separator = ", "; } writer.WriteLine(" };"); } writer.WriteLine($" base.capsize = {rm.Tree.CaptureCount};"); writer.WriteLine($" }}"); writer.WriteLine(" "); writer.WriteLine($" private sealed class RunnerFactory : global::System.Text.RegularExpressions.RegexRunnerFactory"); writer.WriteLine($" {{"); writer.WriteLine($" protected override global::System.Text.RegularExpressions.RegexRunner CreateInstance() => new Runner();"); writer.WriteLine(); writer.WriteLine($" private sealed class Runner : global::System.Text.RegularExpressions.RegexRunner"); writer.WriteLine($" {{"); // Main implementation methods writer.WriteLine(" // Description:"); DescribeExpression(writer, rm.Tree.Root.Child(0), " // ", analysis); // skip implicit root capture writer.WriteLine(); writer.WriteLine($" protected override void Scan(global::System.ReadOnlySpan<char> text)"); writer.WriteLine($" {{"); writer.Indent += 4; EmitScan(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); writer.WriteLine($" private bool TryFindNextPossibleStartingPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; RequiredHelperFunctions requiredHelpers = EmitTryFindNextPossibleStartingPosition(writer, rm, id); writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); if (allowUnsafe) { writer.WriteLine($" [global::System.Runtime.CompilerServices.SkipLocalsInit]"); } writer.WriteLine($" private bool TryMatchAtCurrentPosition(global::System.ReadOnlySpan<char> inputSpan)"); writer.WriteLine($" {{"); writer.Indent += 4; requiredHelpers |= EmitTryMatchAtCurrentPosition(writer, rm, id, analysis); writer.Indent -= 4; writer.WriteLine($" }}"); if ((requiredHelpers & RequiredHelperFunctions.IsWordChar) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character is part of the [\\w] set.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsWordChar(char ch)"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.ReadOnlySpan<byte> ascii = new byte[]"); writer.WriteLine($" {{"); writer.WriteLine($" 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03,"); writer.WriteLine($" 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07"); writer.WriteLine($" }};"); writer.WriteLine(); writer.WriteLine($" int chDiv8 = ch >> 3;"); writer.WriteLine($" return (uint)chDiv8 < (uint)ascii.Length ?"); writer.WriteLine($" (ascii[chDiv8] & (1 << (ch & 0x7))) != 0 :"); writer.WriteLine($" global::System.Globalization.CharUnicodeInfo.GetUnicodeCategory(ch) switch"); writer.WriteLine($" {{"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.UppercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.LowercaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.TitlecaseLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ModifierLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.OtherLetter or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.NonSpacingMark or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.DecimalDigitNumber or"); writer.WriteLine($" global::System.Globalization.UnicodeCategory.ConnectorPunctuation => true,"); writer.WriteLine($" _ => false,"); writer.WriteLine($" }};"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsBoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsBoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsBoundaryWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsBoundaryWordChar(char ch) =>"); writer.WriteLine($" IsWordChar(ch) || (ch == '\\u200C' | ch == '\\u200D');"); writer.WriteLine($" }}"); } if ((requiredHelpers & RequiredHelperFunctions.IsECMABoundary) != 0) { writer.WriteLine(); writer.WriteLine($" /// <summary>Determines whether the character at the specified index is a boundary.</summary>"); writer.WriteLine($" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"); writer.WriteLine($" private static bool IsECMABoundary(global::System.ReadOnlySpan<char> inputSpan, int index)"); writer.WriteLine($" {{"); writer.WriteLine($" int indexM1 = index - 1;"); writer.WriteLine($" return ((uint)indexM1 < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[indexM1])) !="); writer.WriteLine($" ((uint)index < (uint)inputSpan.Length && IsECMAWordChar(inputSpan[index]));"); writer.WriteLine(); writer.WriteLine($" static bool IsECMAWordChar(char ch) =>"); writer.WriteLine($" ((((uint)ch - 'A') & ~0x20) < 26) || // ASCII letter"); writer.WriteLine($" (((uint)ch - '0') < 10) || // digit"); writer.WriteLine($" ch == '_' || // underscore"); writer.WriteLine($" ch == '\\u0130'; // latin capital letter I with dot above"); writer.WriteLine($" }}"); } writer.WriteLine($" }}"); writer.WriteLine($" }}"); writer.WriteLine("}"); return ImmutableArray<Diagnostic>.Empty; static void AppendHashtableContents(IndentedTextWriter writer, Hashtable ht) { IDictionaryEnumerator en = ht.GetEnumerator(); string separator = ""; while (en.MoveNext()) { writer.Write(separator); separator = ", "; writer.Write(" { "); if (en.Key is int key) { writer.Write(key); } else { writer.Write($"\"{en.Key}\""); } writer.Write($", {en.Value} }} "); } } } /// <summary>Emits the body of the Scan method override.</summary> private static void EmitScan(IndentedTextWriter writer, RegexMethod rm, string id) { bool rtl = (rm.Options & RegexOptions.RightToLeft) != 0; using (EmitBlock(writer, "while (TryFindNextPossibleStartingPosition(text))")) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("base.CheckTimeout();"); writer.WriteLine(); } writer.WriteLine("// If we find a match on the current position, or we have reached the end of the input, we are done."); using (EmitBlock(writer, $"if (TryMatchAtCurrentPosition(text) || base.runtextpos == {(!rtl ? "text.Length" : "0")})")) { writer.WriteLine("return;"); } writer.WriteLine(); writer.WriteLine($"base.runtextpos{(!rtl ? "++" : "--")};"); } } /// <summary>Emits the body of the TryFindNextPossibleStartingPosition.</summary> private static RequiredHelperFunctions EmitTryFindNextPossibleStartingPosition(IndentedTextWriter writer, RegexMethod rm, string id) { RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; bool hasTextInfo = false; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; bool rtl = (options & RegexOptions.RightToLeft) != 0; // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); // Emit locals initialization writer.WriteLine("int pos = base.runtextpos;"); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; writer.WriteLine(); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = rm.Tree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); string clause = (minRequiredLength, rtl) switch { (0, false) => "if (pos <= inputSpan.Length)", (1, false) => "if (pos < inputSpan.Length)", (_, false) => $"if (pos <= inputSpan.Length - {minRequiredLength})", (0, true) => "if (pos >= 0)", (1, true) => "if (pos > 0)", (_, true) => $"if (pos >= {minRequiredLength})", }; using (EmitBlock(writer, clause)) { // Emit any anchors. if (!EmitAnchors()) { // Either anchors weren't specified, or they don't completely root all matches to a specific location. // If whatever search operation we need to perform entails case-insensitive operations // that weren't already handled via creation of sets, we need to get an store the // TextInfo object to use (unless RegexOptions.CultureInvariant was specified). EmitTextInfo(writer, ref hasTextInfo, rm); // Emit the code for whatever find mode has been determined. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_LeftToRight(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_RightToLeft(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_LeftToRight(); break; case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_RightToLeft(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: writer.WriteLine("return true;"); break; } } } writer.WriteLine(); const string NoStartingPositionFound = "NoStartingPositionFound"; writer.WriteLine("// No starting position found"); writer.WriteLine($"{NoStartingPositionFound}:"); writer.WriteLine($"base.runtextpos = {(!rtl ? "inputSpan.Length" : "0")};"); writer.WriteLine("return false;"); // We're done. Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); return requiredHelpers; // Emit a goto for the specified label. void Goto(string label) => writer.WriteLine($"goto {label};"); // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool EmitAnchors() { // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: writer.WriteLine("// Beginning \\A anchor"); using (EmitBlock(writer, "if (pos != 0)")) { // If we're not currently at the beginning, we'll never be, so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: writer.WriteLine("// Start \\G anchor"); using (EmitBlock(writer, "if (pos != base.runtextstart)")) { // For both left-to-right and right-to-left, if we're not currently at the starting (because // we've already moved beyond it), then we'll never be, so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: writer.WriteLine("// Leading end \\Z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length - 1)")) { // If we're not currently at the end (or a newline just before it), skip ahead // since nothing until then can possibly match. writer.WriteLine("base.runtextpos = inputSpan.Length - 1;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: writer.WriteLine("// Leading end \\z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length)")) { // If we're not currently at the end (or a newline just before it), skip ahead // since nothing until then can possibly match. writer.WriteLine("base.runtextpos = inputSpan.Length;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: writer.WriteLine("// Beginning \\A anchor"); using (EmitBlock(writer, "if (pos != 0)")) { // If we're not currently at the beginning, skip ahead (or, rather, backwards) // since nothing until then can possibly match. (We're iterating from the end // to the beginning in RightToLeft mode.) writer.WriteLine("base.runtextpos = 0;"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: writer.WriteLine("// Leading end \\Z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n'))")) { // If we're not currently at the end, we'll never be (we're iterating from end to beginning), // so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: writer.WriteLine("// Leading end \\z anchor"); using (EmitBlock(writer, "if (pos < inputSpan.Length)")) { // If we're not currently at the end, we'll never be (we're iterating from end to beginning), // so fail immediately. Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length, minus 1 (for a possible ending \n). writer.WriteLine("// Trailing end \\Z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength + 1};"); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: // Jump to the end, minus the min required length, which in this case is actually the fixed length. writer.WriteLine("// Trailing end \\z anchor with fixed-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength})")) { writer.WriteLine($"base.runtextpos = inputSpan.Length - {regexTree.FindOptimizations.MinRequiredLength};"); } writer.WriteLine("return true;"); return true; } // Now handle anchors that boost the position but may not determine immediate success or failure. switch (regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. writer.WriteLine("// Beginning-of-line anchor"); using (EmitBlock(writer, "if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { writer.WriteLine("int newlinePos = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), '\\n');"); using (EmitBlock(writer, "if ((uint)newlinePos > inputSpan.Length - pos - 1)")) { Goto(NoStartingPositionFound); } writer.WriteLine("pos = newlinePos + pos + 1;"); // We've updated the position. Make sure there's still enough room in the input for a possible match. using (EmitBlock(writer, minRequiredLength switch { 0 => "if (pos > inputSpan.Length)", 1 => "if (pos >= inputSpan.Length)", _ => $"if (pos > inputSpan.Length - {minRequiredLength})" })) { Goto(NoStartingPositionFound); } } writer.WriteLine(); break; } switch (regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength};"); } writer.WriteLine(); break; case RegexNodeKind.EndZ when regexTree.FindOptimizations.MaxPossibleLength is int maxLength: writer.WriteLine("// End \\Z anchor with maximum-length match"); using (EmitBlock(writer, $"if (pos < inputSpan.Length - {maxLength + 1})")) { writer.WriteLine($"pos = inputSpan.Length - {maxLength + 1};"); } writer.WriteLine(); break; } return false; } // Emits a case-sensitive prefix search for a string at the beginning of the pattern. void EmitIndexOf_LeftToRight(string prefix) { writer.WriteLine($"int i = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), {Literal(prefix)});"); writer.WriteLine("if (i >= 0)"); writer.WriteLine("{"); writer.WriteLine(" base.runtextpos = pos + i;"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } // Emits a case-sensitive right-to-left prefix search for a string at the beginning of the pattern. void EmitIndexOf_RightToLeft(string prefix) { writer.WriteLine($"pos = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice(0, pos), {Literal(prefix)});"); writer.WriteLine("if (pos >= 0)"); writer.WriteLine("{"); writer.WriteLine($" base.runtextpos = pos + {prefix.Length};"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } // Emits a search for a set at a fixed position from the start of the pattern, // and potentially other sets at other fixed positions in the pattern. void EmitFixedSet_LeftToRight() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; FinishEmitScope loopBlock = default; if (needLoop) { writer.WriteLine("global::System.ReadOnlySpan<char> span = inputSpan.Slice(pos);"); string upperBound = "span.Length" + (setsToUse > 1 || primarySet.Distance != 0 ? $" - {minRequiredLength - 1}" : ""); loopBlock = EmitBlock(writer, $"for (int i = 0; i < {upperBound}; i++)"); } if (canUseIndexOf) { string span = needLoop ? "span" : "inputSpan.Slice(pos)"; span = (needLoop, primarySet.Distance) switch { (false, 0) => span, (true, 0) => $"{span}.Slice(i)", (false, _) => $"{span}.Slice({primarySet.Distance})", (true, _) => $"{span}.Slice(i + {primarySet.Distance})", }; string indexOf = primarySet.Chars!.Length switch { 1 => $"global::System.MemoryExtensions.IndexOf({span}, {Literal(primarySet.Chars[0])})", 2 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])})", 3 => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(primarySet.Chars[0])}, {Literal(primarySet.Chars[1])}, {Literal(primarySet.Chars[2])})", _ => $"global::System.MemoryExtensions.IndexOfAny({span}, {Literal(new string(primarySet.Chars))})", }; if (needLoop) { writer.WriteLine($"int indexOfPos = {indexOf};"); using (EmitBlock(writer, "if (indexOfPos < 0)")) { Goto(NoStartingPositionFound); } writer.WriteLine("i += indexOfPos;"); writer.WriteLine(); if (setsToUse > 1) { using (EmitBlock(writer, $"if (i >= span.Length - {minRequiredLength - 1})")) { Goto(NoStartingPositionFound); } writer.WriteLine(); } } else { writer.WriteLine($"int i = {indexOf};"); using (EmitBlock(writer, "if (i >= 0)")) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } setIndex = 1; } if (needLoop) { Debug.Assert(setIndex == 0 || setIndex == 1); bool hasCharClassConditions = false; if (setIndex < setsToUse) { // if (CharInClass(textSpan[i + charClassIndex], prefix[0], "...") && // ...) Debug.Assert(needLoop); int start = setIndex; for (; setIndex < setsToUse; setIndex++) { string spanIndex = $"span[i{(sets[setIndex].Distance > 0 ? $" + {sets[setIndex].Distance}" : "")}]"; string charInClassExpr = MatchCharacterClass(hasTextInfo, options, spanIndex, sets[setIndex].Set, sets[setIndex].CaseInsensitive, negate: false, additionalDeclarations, ref requiredHelpers); if (setIndex == start) { writer.Write($"if ({charInClassExpr}"); } else { writer.WriteLine(" &&"); writer.Write($" {charInClassExpr}"); } } writer.WriteLine(")"); hasCharClassConditions = true; } using (hasCharClassConditions ? EmitBlock(writer, null) : default) { writer.WriteLine("base.runtextpos = pos + i;"); writer.WriteLine("return true;"); } } loopBlock.Dispose(); } // Emits a right-to-left search for a set at a fixed position from the start of the pattern. // (Currently that position will always be a distance of 0, meaning the start of the pattern itself.) void EmitFixedSet_RightToLeft() { (char[]? Chars, string Set, int Distance, bool CaseInsensitive) set = regexTree.FindOptimizations.FixedDistanceSets![0]; Debug.Assert(set.Distance == 0); if (set.Chars is { Length: 1 } && !set.CaseInsensitive) { writer.WriteLine($"pos = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice(0, pos), {Literal(set.Chars[0])});"); writer.WriteLine("if (pos >= 0)"); writer.WriteLine("{"); writer.WriteLine(" base.runtextpos = pos + 1;"); writer.WriteLine(" return true;"); writer.WriteLine("}"); } else { using (EmitBlock(writer, "while ((uint)--pos < (uint)inputSpan.Length)")) { using (EmitBlock(writer, $"if ({MatchCharacterClass(hasTextInfo, options, "inputSpan[pos]", set.Set, set.CaseInsensitive, negate: false, additionalDeclarations, ref requiredHelpers)})")) { writer.WriteLine("base.runtextpos = pos + 1;"); writer.WriteLine("return true;"); } } } } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); using (EmitBlock(writer, "while (true)")) { writer.WriteLine($"global::System.ReadOnlySpan<char> slice = inputSpan.Slice(pos);"); writer.WriteLine(); // Find the literal. If we can't find it, we're done searching. writer.Write("int i = global::System.MemoryExtensions."); writer.WriteLine( target.Literal.String is string literalString ? $"IndexOf(slice, {Literal(literalString)});" : target.Literal.Chars is not char[] literalChars ? $"IndexOf(slice, {Literal(target.Literal.Char)});" : literalChars.Length switch { 2 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])});", 3 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])}, {Literal(literalChars[2])});", _ => $"IndexOfAny(slice, {Literal(new string(literalChars))});", }); using (EmitBlock(writer, $"if (i < 0)")) { writer.WriteLine("break;"); } writer.WriteLine(); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. writer.WriteLine("int prev = i;"); writer.WriteLine($"while ((uint)--prev < (uint)slice.Length && {MatchCharacterClass(hasTextInfo, options, "slice[prev]", target.LoopNode.Str!, caseInsensitive: false, negate: false, additionalDeclarations, ref requiredHelpers)});"); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. writer.WriteLine($"if ((i - prev - 1) < {target.LoopNode.M})"); writer.WriteLine("{"); writer.WriteLine(" pos += i + 1;"); writer.WriteLine(" continue;"); writer.WriteLine("}"); } writer.WriteLine(); // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. writer.WriteLine("base.runtextpos = pos + prev + 1;"); writer.WriteLine("return true;"); } } // If a TextInfo is needed to perform ToLower operations, emits a local initialized to the TextInfo to use. static void EmitTextInfo(IndentedTextWriter writer, ref bool hasTextInfo, RegexMethod rm) { // Emit local to store current culture if needed if ((rm.Options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = rm.Tree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when rm.Tree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { hasTextInfo = true; writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); } } } } /// <summary>Emits the body of the TryMatchAtCurrentPosition.</summary> private static RequiredHelperFunctions EmitTryMatchAtCurrentPosition(IndentedTextWriter writer, RegexMethod rm, string id, AnalysisResults analysis) { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; RegexOptions options = (RegexOptions)rm.Options; RegexTree regexTree = rm.Tree; RequiredHelperFunctions requiredHelpers = RequiredHelperFunctions.None; // Helper to define names. Names start unadorned, but as soon as there's repetition, // they begin to have a numbered suffix. var usedNames = new Dictionary<string, int>(); // Every RegexTree is rooted in the implicit Capture for the whole expression. // Skip the Capture node. We handle the implicit root capture specially. RegexNode node = regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. writer.WriteLine($"int start = base.runtextpos;"); writer.WriteLine($"int end = start {((node.Options & RegexOptions.RightToLeft) == 0 ? "+" : "-")} {(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1)};"); writer.WriteLine("base.Capture(0, start, end);"); writer.WriteLine("base.runtextpos = end;"); writer.WriteLine("return true;"); return requiredHelpers; case RegexNodeKind.Empty: // This case isn't common in production, but it's very common when first getting started with the // source generator and seeing what happens as you add more to expressions. When approaching // it from a learning perspective, this is very common, as it's the empty string you start with. writer.WriteLine("base.Capture(0, base.runtextpos, base.runtextpos);"); writer.WriteLine("return true;"); return requiredHelpers; } // In some cases, we need to emit declarations at the beginning of the method, but we only discover we need them later. // To handle that, we build up a collection of all the declarations to include, track where they should be inserted, // and then insert them at that position once everything else has been output. var additionalDeclarations = new HashSet<string>(); var additionalLocalFunctions = new Dictionary<string, string[]>(); // Declare some locals. string sliceSpan = "slice"; writer.WriteLine("int pos = base.runtextpos;"); writer.WriteLine($"int original_pos = pos;"); bool hasTimeout = EmitLoopTimeoutCounterIfNeeded(writer, rm); bool hasTextInfo = EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(writer, rm, analysis); writer.Flush(); int additionalDeclarationsPosition = ((StringWriter)writer.InnerWriter).GetStringBuilder().Length; int additionalDeclarationsIndent = writer.Indent; // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(writer, defineLocal: true); writer.WriteLine(); // doneLabel starts out as the top-level label for the whole expression failing to match. However, // it may be changed by the processing of a node to point to whereever subsequent match failures // should jump to, in support of backtracking or other constructs. For example, before emitting // the code for a branch N, an alternation will set the the doneLabel to point to the label for // processing the next branch N+1: that way, any failures in the branch N's processing will // implicitly end up jumping to the right location without needing to know in what context it's used. string doneLabel = ReserveName("NoMatch"); string topLevelDoneLabel = doneLabel; // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // If we fall through to this place in the code, we've successfully matched the expression. writer.WriteLine(); writer.WriteLine("// The input matched."); if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); // TransferSliceStaticPosToPos would also slice, which isn't needed here } writer.WriteLine("base.runtextpos = pos;"); writer.WriteLine("base.Capture(0, original_pos, pos);"); writer.WriteLine("return true;"); // We're done with the match. // Patch up any additional declarations. ReplaceAdditionalDeclarations(writer, additionalDeclarations, additionalDeclarationsPosition, additionalDeclarationsIndent); // And emit any required helpers. if (additionalLocalFunctions.Count != 0) { foreach (KeyValuePair<string, string[]> localFunctions in additionalLocalFunctions.OrderBy(k => k.Key)) { writer.WriteLine(); foreach (string line in localFunctions.Value) { writer.WriteLine(line); } } } return requiredHelpers; // Helper to create a name guaranteed to be unique within the function. string ReserveName(string prefix) { usedNames.TryGetValue(prefix, out int count); usedNames[prefix] = count + 1; return count == 0 ? prefix : $"{prefix}{count}"; } // Helper to emit a label. As of C# 10, labels aren't statements of their own and need to adorn a following statement; // if a label appears just before a closing brace, then, it's a compilation error. To avoid issues there, this by // default implements a blank statement (a semicolon) after each label, but individual uses can opt-out of the semicolon // when it's known the label will always be followed by a statement. void MarkLabel(string label, bool emitSemicolon = true) => writer.WriteLine($"{label}:{(emitSemicolon ? ";" : "")}"); // Emits a goto to jump to the specified label. However, if the specified label is the top-level done label indicating // that the entire match has failed, we instead emit our epilogue, uncapturing if necessary and returning out of TryMatchAtCurrentPosition. void Goto(string label) { if (label == topLevelDoneLabel) { // We only get here in the code if the whole expression fails to match and jumps to // the original value of doneLabel. if (expressionHasCaptures) { EmitUncaptureUntil("0"); } writer.WriteLine("return false; // The input didn't match."); } else { writer.WriteLine($"goto {label};"); } } // Emits a case or default line followed by an indented body. void CaseGoto(string clause, string label) { writer.WriteLine(clause); writer.Indent++; Goto(label); writer.Indent--; } // Whether the node has RegexOptions.IgnoreCase set. static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan(IndentedTextWriter writer, bool defineLocal = false) { if (defineLocal) { writer.Write("global::System.ReadOnlySpan<char> "); } writer.WriteLine($"{sliceSpan} = inputSpan.Slice(pos);"); } // Emits the sum of a constant and a value from a local. string Sum(int constant, string? local = null) => local is null ? constant.ToString(CultureInfo.InvariantCulture) : constant == 0 ? local : $"{constant} + {local}"; // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) { Debug.Assert(requiredLength > 0); using (EmitBlock(writer, $"if ({SpanLengthCheck(requiredLength, dynamicRequiredLength)})")) { Goto(doneLabel); } } // Returns a length check for the current span slice. The check returns true if // the span isn't long enough for the specified length. string SpanLengthCheck(int requiredLength, string? dynamicRequiredLength = null) => dynamicRequiredLength is null && sliceStaticPos + requiredLength == 1 ? $"{sliceSpan}.IsEmpty" : $"(uint){sliceSpan}.Length < {Sum(sliceStaticPos + requiredLength, dynamicRequiredLength)}"; // Adds the value of sliceStaticPos into the pos local, slices slice by the corresponding amount, // and zeros out sliceStaticPos. void TransferSliceStaticPosToPos(bool forceSliceReload = false) { if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); sliceStaticPos = 0; SliceInputSpan(writer); } else if (forceSliceReload) { SliceInputSpan(writer); } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); string originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // If no child branch overlaps with another child branch, we can emit more streamlined code // that avoids checking unnecessary branches, e.g. with abc|def|ghi if the next character in // the input is 'a', we needn't try the def or ghi branches. A simple, relatively common case // of this is if every branch begins with a specific, unique character, in which case // the whole alternation can be treated as a simple switch, so we special-case that. However, // we can't goto _into_ switch cases, which means we can't use this approach if there's any // possibility of backtracking into the alternation. bool useSwitchedBranches = false; if ((node.Options & RegexOptions.RightToLeft) == 0) { useSwitchedBranches = isAtomic; if (!useSwitchedBranches) { useSwitchedBranches = true; for (int i = 0; i < childCount; i++) { if (analysis.MayBacktrack(node.Child(i))) { useSwitchedBranches = false; break; } } } } // Detect whether every branch begins with one or more unique characters. const int SetCharsSize = 5; // arbitrary limit (for IgnoreCase, we want this to be at least 3 to handle the vast majority of values) Span<char> setChars = stackalloc char[SetCharsSize]; if (useSwitchedBranches) { // Iterate through every branch, seeing if we can easily find a starting One, Multi, or small Set. // If we can, extract its starting char (or multiple in the case of a set), validate that all such // starting characters are unique relative to all the branches. var seenChars = new HashSet<char>(); for (int i = 0; i < childCount && useSwitchedBranches; i++) { // If it's not a One, Multi, or Set, we can't apply this optimization. // If it's IgnoreCase (and wasn't reduced to a non-IgnoreCase set), also ignore it to keep the logic simple. if (node.Child(i).FindBranchOneMultiOrSetStart() is not RegexNode oneMultiOrSet || (oneMultiOrSet.Options & RegexOptions.IgnoreCase) != 0) // TODO: https://github.com/dotnet/runtime/issues/61048 { useSwitchedBranches = false; break; } // If it's a One or a Multi, get the first character and add it to the set. // If it was already in the set, we can't apply this optimization. if (oneMultiOrSet.Kind is RegexNodeKind.One or RegexNodeKind.Multi) { if (!seenChars.Add(oneMultiOrSet.FirstCharOfOneOrMulti())) { useSwitchedBranches = false; break; } } else { // The branch begins with a set. Make sure it's a set of only a few characters // and get them. If we can't, we can't apply this optimization. Debug.Assert(oneMultiOrSet.Kind is RegexNodeKind.Set); int numChars; if (RegexCharClass.IsNegated(oneMultiOrSet.Str!) || (numChars = RegexCharClass.GetSetChars(oneMultiOrSet.Str!, setChars)) == 0) { useSwitchedBranches = false; break; } // Check to make sure each of the chars is unique relative to all other branches examined. foreach (char c in setChars.Slice(0, numChars)) { if (!seenChars.Add(c)) { useSwitchedBranches = false; break; } } } } } if (useSwitchedBranches) { // Note: This optimization does not exist with RegexOptions.Compiled. Here we rely on the // C# compiler to lower the C# switch statement with appropriate optimizations. In some // cases there are enough branches that the compiler will emit a jump table. In others // it'll optimize the order of checks in order to minimize the total number in the worst // case. In any case, we get easier to read and reason about C#. EmitSwitchedBranches(); } else { EmitAllBranches(); } return; // Emits the code for a switch-based alternation of non-overlapping branches. void EmitSwitchedBranches() { // We need at least 1 remaining character in the span, for the char to switch on. EmitSpanLengthCheck(1); writer.WriteLine(); // Emit a switch statement on the first char of each branch. using (EmitBlock(writer, $"switch ({sliceSpan}[{sliceStaticPos++}])")) { Span<char> setChars = stackalloc char[SetCharsSize]; // needs to be same size as detection check in caller int startingSliceStaticPos = sliceStaticPos; // Emit a case for each branch. for (int i = 0; i < childCount; i++) { sliceStaticPos = startingSliceStaticPos; RegexNode child = node.Child(i); Debug.Assert(child.Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set or RegexNodeKind.Concatenate, DescribeNode(child, analysis)); Debug.Assert(child.Kind is not RegexNodeKind.Concatenate || (child.ChildCount() >= 2 && child.Child(0).Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set)); RegexNode? childStart = child.FindBranchOneMultiOrSetStart(); Debug.Assert(childStart is not null, "Unexpectedly couldn't find the branch starting node."); Debug.Assert((childStart.Options & RegexOptions.IgnoreCase) == 0, "Expected only to find non-IgnoreCase branch starts"); if (childStart.Kind is RegexNodeKind.Set) { int numChars = RegexCharClass.GetSetChars(childStart.Str!, setChars); Debug.Assert(numChars != 0); writer.WriteLine($"case {string.Join(" or ", setChars.Slice(0, numChars).ToArray().Select(c => Literal(c)))}:"); } else { writer.WriteLine($"case {Literal(childStart.FirstCharOfOneOrMulti())}:"); } writer.Indent++; // Emit the code for the branch, without the first character that was already matched in the switch. switch (child.Kind) { case RegexNodeKind.Multi: EmitNode(CloneMultiWithoutFirstChar(child)); writer.WriteLine(); break; case RegexNodeKind.Concatenate: var newConcat = new RegexNode(RegexNodeKind.Concatenate, child.Options); if (childStart.Kind == RegexNodeKind.Multi) { newConcat.AddChild(CloneMultiWithoutFirstChar(childStart)); } int concatChildCount = child.ChildCount(); for (int j = 1; j < concatChildCount; j++) { newConcat.AddChild(child.Child(j)); } EmitNode(newConcat.Reduce()); writer.WriteLine(); break; static RegexNode CloneMultiWithoutFirstChar(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Multi); Debug.Assert(node.Str!.Length >= 2); return node.Str!.Length == 2 ? new RegexNode(RegexNodeKind.One, node.Options, node.Str![1]) : new RegexNode(RegexNodeKind.Multi, node.Options, node.Str!.Substring(1)); } } // This is only ever used for atomic alternations, so we can simply reset the doneLabel // after emitting the child, as nothing will backtrack here (and we need to reset it // so that all branches see the original). doneLabel = originalDoneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); writer.WriteLine($"break;"); writer.WriteLine(); writer.Indent--; } // Default branch if the character didn't match the start of any branches. CaseGoto("default:", doneLabel); } } void EmitAllBranches() { // Label to jump to when any branch completes successfully. string matchLabel = ReserveName("AlternationMatch"); // Save off pos. We'll need to reset this each time a branch fails. string startingPos = ReserveName("alternation_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. string? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { startingCapturePos = ReserveName("alternation_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } writer.WriteLine(); // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new string[childCount]; string backtrackLabel = ReserveName("AlternationBacktrack"); for (int i = 0; i < childCount; i++) { // If the alternation isn't atomic, backtracking may require our jump table jumping back // into these branches, so we can't use actual scopes, as that would hide the labels. using (EmitScope(writer, $"Branch {i}", faux: !isAtomic)) { bool isLastBranch = i == childCount - 1; string? nextBranch = null; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = ReserveName("AlternationBranch"); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); writer.WriteLine(); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { EmitStackPush(startingCapturePos is not null ? new[] { i.ToString(), startingPos, startingCapturePos } : new[] { i.ToString(), startingPos }); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. TransferSliceStaticPosToPos(); if (!isLastBranch || !isAtomic) { // If this isn't the last branch, we're about to output a reset section, // and if this isn't atomic, there will be a backtracking section before // the end of the method. In both of those cases, we've successfully // matched and need to skip over that code. If, however, this is the // last branch and this is an atomic alternation, we can just fall // through to the successfully matched location. Goto(matchLabel); } // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { writer.WriteLine(); MarkLabel(nextBranch!, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } writer.WriteLine(); } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel, emitSemicolon: false); EmitStackPop(startingCapturePos is not null ? new[] { startingCapturePos, startingPos } : new[] { startingPos}); using (EmitBlock(writer, $"switch ({StackPop()})")) { for (int i = 0; i < labelMap.Length; i++) { CaseGoto($"case {i}:", labelMap[i]); } } writer.WriteLine(); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); if (sliceStaticPos > 0) { TransferSliceStaticPosToPos(); writer.WriteLine(); } // If the specified capture hasn't yet captured anything, fail to match... except when using RegexOptions.ECMAScript, // in which case per ECMA 262 section 21.2.2.9 the backreference should succeed. if ((node.Options & RegexOptions.ECMAScript) != 0) { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference matches with RegexOptions.ECMAScript rules."); using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { EmitWhenHasCapture(); } } else { writer.WriteLine($"// If the {DescribeCapture(node.M, analysis)} hasn't matched, the backreference doesn't match."); using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(doneLabel); } writer.WriteLine(); EmitWhenHasCapture(); } void EmitWhenHasCapture() { writer.WriteLine("// Get the captured text. If it doesn't match at the current position, the backreference doesn't match."); additionalDeclarations.Add("int matchLength = 0;"); writer.WriteLine($"matchLength = base.MatchLength({capnum});"); bool caseInsensitive = IsCaseInsensitive(node); if ((node.Options & RegexOptions.RightToLeft) == 0) { if (!caseInsensitive) { // If we're case-sensitive, we can simply validate that the remaining length of the slice is sufficient // to possibly match, and then do a SequenceEqual against the matched text. writer.WriteLine($"if ({sliceSpan}.Length < matchLength || "); using (EmitBlock(writer, $" !global::System.MemoryExtensions.SequenceEqual(inputSpan.Slice(base.MatchIndex({capnum}), matchLength), {sliceSpan}.Slice(0, matchLength)))")) { Goto(doneLabel); } } else { // For case-insensitive, we have to walk each character individually. using (EmitBlock(writer, $"if ({sliceSpan}.Length < matchLength)")) { Goto(doneLabel); } writer.WriteLine(); additionalDeclarations.Add("int matchIndex = 0;"); writer.WriteLine($"matchIndex = base.MatchIndex({capnum});"); using (EmitBlock(writer, $"for (int i = 0; i < matchLength; i++)")) { using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"inputSpan[matchIndex + i]")} != {ToLower(hasTextInfo, options, $"{sliceSpan}[i]")})")) { Goto(doneLabel); } } } writer.WriteLine(); writer.WriteLine($"pos += matchLength;"); SliceInputSpan(writer); } else { using (EmitBlock(writer, $"if (pos < matchLength)")) { Goto(doneLabel); } writer.WriteLine(); additionalDeclarations.Add("int matchIndex = 0;"); writer.WriteLine($"matchIndex = base.MatchIndex({capnum});"); using (EmitBlock(writer, $"for (int i = 0; i < matchLength; i++)")) { using (EmitBlock(writer, $"if ({ToLowerIfNeeded(hasTextInfo, options, $"inputSpan[matchIndex + i]", caseInsensitive)} != {ToLowerIfNeeded(hasTextInfo, options, $"inputSpan[pos - matchLength + i]", caseInsensitive)})")) { Goto(doneLabel); } } writer.WriteLine(); writer.WriteLine($"pos -= matchLength;"); } } } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; // If the child branches might backtrack, we can't emit the branches inside constructs that // require braces, e.g. if/else, even though that would yield more idiomatic output. // But if we know for certain they won't backtrack, we can output the nicer code. if (analysis.IsAtomicByAncestor(node) || (!analysis.MayBacktrack(yesBranch) && (noBranch is null || !analysis.MayBacktrack(noBranch)))) { using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { writer.WriteLine($"// The {DescribeCapture(node.M, analysis)} captured a value. Match the first branch."); EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } if (noBranch is not null) { using (EmitBlock(writer, $"else")) { writer.WriteLine($"// Otherwise, match the second branch."); EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch } } doneLabel = originalDoneLabel; // atomicity return; } string refNotMatched = ReserveName("ConditionalBackreferenceNotMatched"); string endConditional = ReserveName("ConditionalBackreferenceEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalbackreference_branch"); writer.WriteLine($"int {resumeAt} = 0;"); // While it would be nicely readable to use an if/else block, if the branches contain // anything that triggers backtracking, labels will end up being defined, and if they're // inside the scope block for the if or else, that will prevent jumping to them from // elsewhere. So we implement the if/else with labels and gotos manually. // Check to see if the specified capture number was captured. using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { Goto(refNotMatched); } writer.WriteLine(); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { Goto(endConditional); writer.WriteLine(); } MarkLabel(refNotMatched); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. bool hasBacktracking = postYesDoneLabel != originalDoneLabel || postNoDoneLabel != originalDoneLabel; if (hasBacktracking) { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); // Backtrack section string backtrack = ReserveName("ConditionalBackreferenceBacktrack"); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } } if (needsEndConditional) { MarkLabel(endConditional); } if (hasBacktracking) { // We're not atomic and at least one of the yes or no branches contained backtracking constructs, // so finish outputting our backtracking logic, which involves pushing onto the stack which // branch to backtrack into. EmitStackPush(resumeAt); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookaround. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; string originalDoneLabel = doneLabel; string expressionNotMatched = ReserveName("ConditionalExpressionNotMatched"); string endConditional = ReserveName("ConditionalExpressionEnd"); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. string resumeAt = ReserveName("conditionalexpression_branch"); if (!isAtomic) { writer.WriteLine($"int {resumeAt} = 0;"); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. string? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { startingCapturePos = ReserveName("conditionalexpression_starting_capturepos"); writer.WriteLine($"int {startingCapturePos} = base.Crawlpos();"); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookaround; however, a positive lookaround only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("conditionalexpression_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. writer.WriteLine("// Condition:"); EmitNode(condition); writer.WriteLine(); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. writer.WriteLine("// Condition matched:"); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; writer.WriteLine(); // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch string postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 0;"); } Goto(endConditional); writer.WriteLine(); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. writer.WriteLine("// Condition did not match:"); MarkLabel(expressionNotMatched, emitSemicolon: false); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } writer.WriteLine(); string postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 1;"); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { writer.WriteLine($"{resumeAt} = 2;"); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { // Skip the backtracking section. Goto(endConditional); writer.WriteLine(); string backtrack = ReserveName("ConditionalExpressionBacktrack"); doneLabel = backtrack; MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(resumeAt); using (EmitBlock(writer, $"switch ({resumeAt})")) { if (postYesDoneLabel != originalDoneLabel) { CaseGoto("case 0:", postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { CaseGoto("case 1:", postNoDoneLabel); } CaseGoto("default:", originalDoneLabel); } MarkLabel(endConditional, emitSemicolon: false); EmitStackPush(resumeAt); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, rm.Tree.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, rm.Tree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); TransferSliceStaticPosToPos(); string startingPos = ReserveName("capture_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); RegexNode child = node.Child(0); if (uncapnum != -1) { using (EmitBlock(writer, $"if (!base.IsMatched({uncapnum}))")) { Goto(doneLabel); } writer.WriteLine(); } // Emit child node. string originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; writer.WriteLine(); TransferSliceStaticPosToPos(); if (uncapnum == -1) { writer.WriteLine($"base.Capture({capnum}, {startingPos}, pos);"); } else { writer.WriteLine($"base.TransferCapture({capnum}, {uncapnum}, {startingPos}, pos);"); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. writer.WriteLine(); EmitStackPush(startingPos); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"CaptureBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(startingPos); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } // Emits the code to handle a positive lookaround assertion. This is a positive lookahead // for left-to-right and a positive lookbehind for right-to-left. void EmitPositiveLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("positivelookaround_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); writer.WriteLine(); int startingSliceStaticPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. writer.WriteLine(); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; } // Emits the code to handle a negative lookaround assertion. This is a negative lookahead // for left-to-right and a negative lookbehind for right-to-left. void EmitNegativeLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } string originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookaround. string startingPos = ReserveName("negativelookaround_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; string negativeLookaroundDoneLabel = ReserveName("NegativeLookaroundMatch"); doneLabel = negativeLookaroundDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookaround, which actually // means failure for a _negative_ lookaround, so we need to jump to the original done. writer.WriteLine(); Goto(originalDoneLabel); writer.WriteLine(); // Failures (success for a negative lookaround) jump here. MarkLabel(negativeLookaroundDoneLabel, emitSemicolon: false); // After the child completes in failure (success for negative lookaround), reset the text positions. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } if ((node.Options & RegexOptions.RightToLeft) != 0) { // RightToLeft doesn't take advantage of static positions. While RightToLeft won't update static // positions, a previous operation may have left us with a non-zero one. Make sure it's zero'd out // such that pos and slice are up-to-date. Note that RightToLeft also shouldn't use the slice span, // as it's not kept up-to-date; any RightToLeft implementation that wants to use it must first update // it from pos. TransferSliceStaticPosToPos(); } // Separate out several node types that, for conciseness, don't need a header and scope written into the source. switch (node.Kind) { // Nothing is written for an empty case RegexNodeKind.Empty: return; // A match failure doesn't need a scope. case RegexNodeKind.Nothing: Goto(doneLabel); return; // Skip atomic nodes that wrap non-backtracking children; in such a case there's nothing to be made atomic. case RegexNodeKind.Atomic when !analysis.MayBacktrack(node.Child(0)): EmitNode(node.Child(0)); return; // Concatenate is a simplification in the node tree so that a series of children can be represented as one. // We don't need its presence visible in the source. case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); return; } // Put the node's code into its own scope. If the node contains labels that may need to // be visible outside of its scope, the scope is still emitted for clarity but is commented out. using (EmitScope(writer, DescribeNode(node, analysis), faux: analysis.MayBacktrack(node))) { switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); break; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); break; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Loop: EmitLoop(node); break; case RegexNodeKind.Lazyloop: EmitLazy(node); break; case RegexNodeKind.Alternate: EmitAlternation(node); break; case RegexNodeKind.Backreference: EmitBackreference(node); break; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); break; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); break; case RegexNodeKind.Atomic: Debug.Assert(analysis.MayBacktrack(node.Child(0))); EmitAtomic(node, subsequent); return; case RegexNodeKind.Capture: EmitCapture(node, subsequent); break; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaroundAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaroundAssertion(node); break; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } } } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(analysis.MayBacktrack(node.Child(0)), "Expected child to potentially backtrack"); // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. string originalDoneLabel = doneLabel; additionalDeclarations.Add("int stackpos = 0;"); string startingStackpos = ReserveName("atomic_stackpos"); writer.WriteLine($"int {startingStackpos} = stackpos;"); writer.WriteLine(); // Emit the child. EmitNode(node.Child(0), subsequent); writer.WriteLine(); // Reset the stack position and done label. writer.WriteLine($"stackpos = {startingStackpos};"); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); TransferSliceStaticPosToPos(); using (EmitBlock(writer, "if (base.runtextpos < pos)")) { writer.WriteLine("base.runtextpos = pos;"); } } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); // Emit the code for each child one after the other. string? prevDescription = null; int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. We also want to minimize the repetition of if blocks, // and so we try to emit a series of clauses all part of the same if block rather than one if block per child. if ((node.Options & RegexOptions.RightToLeft) == 0 && emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { bool wroteClauses = true; writer.Write($"if ({SpanLengthCheck(requiredLength)}"); while (i < exclusiveEnd) { for (; i < exclusiveEnd; i++) { void WriteSingleCharChild(RegexNode child, bool includeDescription = true) { if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $" || // {prevDescription}" : " ||"); writer.Write(" "); } else { writer.Write("if ("); } EmitSingleChar(child, emitLengthCheck: false, clauseOnly: true); prevDescription = includeDescription ? DescribeNode(child, analysis) : null; wroteClauses = true; } RegexNode child = node.Child(i); if (child.Kind is RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set) { WriteSingleCharChild(child); } else if (child.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Onelazy or RegexNodeKind.Oneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloopatomic && child.M == child.N && child.M <= MaxUnrollSize) { for (int c = 0; c < child.M; c++) { WriteSingleCharChild(child, includeDescription: c == 0); } } else { break; } } if (wroteClauses) { writer.WriteLine(prevDescription is not null ? $") // {prevDescription}" : ")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } if (i < childCount) { writer.WriteLine(); } wroteClauses = false; prevDescription = null; } if (i < exclusiveEnd) { EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: false); if (i < childCount - 1) { writer.WriteLine(); } i++; } } i--; continue; } EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: emitLengthChecksIfRequired); if (i < childCount - 1) { writer.WriteLine(); } } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequentOrDefault(int index, RegexNode node, RegexNode? defaultNode) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return defaultNode; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, string? offset = null, bool clauseOnly = false) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Debug.Assert(!rtl || offset is null); Debug.Assert(!rtl || !clauseOnly); string expr = !rtl ? $"{sliceSpan}[{Sum(sliceStaticPos, offset)}]" : "inputSpan[pos - 1]"; if (node.IsSetFamily) { expr = $"{MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: true, additionalDeclarations, ref requiredHelpers)}"; } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "!=" : "==")} {Literal(node.Ch)}"; } if (clauseOnly) { writer.Write(expr); } else { string clause = !emitLengthCheck ? $"if ({expr})" : !rtl ? $"if ({SpanLengthCheck(1, offset)} || {expr})" : $"if ((uint)(pos - 1) >= inputSpan.Length || {expr})"; using (EmitBlock(writer, clause)) { Goto(doneLabel); } } if (!rtl) { sliceStaticPos++; } else { writer.WriteLine("pos--;"); } } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); string call = node.Kind switch { RegexNodeKind.Boundary => "!IsBoundary", RegexNodeKind.NonBoundary => "IsBoundary", RegexNodeKind.ECMABoundary => "!IsECMABoundary", _ => "IsECMABoundary", }; RequiredHelperFunctions boundaryFunctionRequired = node.Kind switch { RegexNodeKind.Boundary or RegexNodeKind.NonBoundary => RequiredHelperFunctions.IsBoundary | RequiredHelperFunctions.IsWordChar, // IsBoundary internally uses IsWordChar _ => RequiredHelperFunctions.IsECMABoundary }; requiredHelpers |= boundaryFunctionRequired; using (EmitBlock(writer, $"if ({call}(inputSpan, pos{(sliceStaticPos > 0 ? $" + {sliceStaticPos}" : "")}))")) { Goto(doneLabel); } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert((node.Options & RegexOptions.RightToLeft) == 0 || sliceStaticPos == 0); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. Goto(doneLabel); } else { using (EmitBlock(writer, node.Kind == RegexNodeKind.Beginning ? "if (pos != 0)" : "if (pos != base.runtextstart)")) { Goto(doneLabel); } } break; case RegexNodeKind.Bol: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceSpan}[{sliceStaticPos - 1}] != '\\n')" : $"if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { Goto(doneLabel); } break; case RegexNodeKind.End: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos} < {sliceSpan}.Length)" : "if ((uint)pos < (uint)inputSpan.Length)")) { Goto(doneLabel); } break; case RegexNodeKind.EndZ: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos + 1} < {sliceSpan}.Length || ({sliceStaticPos} < {sliceSpan}.Length && {sliceSpan}[{sliceStaticPos}] != '\\n'))" : "if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n'))")) { Goto(doneLabel); } break; case RegexNodeKind.Eol: using (EmitBlock(writer, sliceStaticPos > 0 ? $"if ({sliceStaticPos} < {sliceSpan}.Length && {sliceSpan}[{sliceStaticPos}] != '\\n')" : "if ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\\n')")) { Goto(doneLabel); } break; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); Debug.Assert(node.Str is not null); EmitMultiCharString(node.Str, IsCaseInsensitive(node), emitLengthCheck, (node.Options & RegexOptions.RightToLeft) != 0); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck, bool rightToLeft) { Debug.Assert(str.Length >= 2); if (rightToLeft) { Debug.Assert(emitLengthCheck); using (EmitBlock(writer, $"if ((uint)(pos - {str.Length}) >= inputSpan.Length)")) { Goto(doneLabel); } writer.WriteLine(); using (EmitBlock(writer, $"for (int i = 0; i < {str.Length}; i++)")) { using (EmitBlock(writer, $"if ({ToLowerIfNeeded(hasTextInfo, options, "inputSpan[--pos]", caseInsensitive)} != {Literal(str)}[{str.Length - 1} - i])")) { Goto(doneLabel); } } return; } if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } using (EmitBlock(writer, $"for (int i = 0; i < {Literal(str)}.Length; i++)")) { string textSpanIndex = sliceStaticPos > 0 ? $"i + {sliceStaticPos}" : "i"; using (EmitBlock(writer, $"if ({ToLower(hasTextInfo, options, $"{sliceSpan}[{textSpanIndex}]")} != {Literal(str)}[i])")) { Goto(doneLabel); } } } else { string sourceSpan = sliceStaticPos > 0 ? $"{sliceSpan}.Slice({sliceStaticPos})" : sliceSpan; using (EmitBlock(writer, $"if (!global::System.MemoryExtensions.StartsWith({sourceSpan}, {Literal(str)}))")) { Goto(doneLabel); } } sliceStaticPos += str.Length; } void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); string backtrackingLabel = ReserveName("CharLoopBacktrack"); string endLoop = ReserveName("CharLoopEnd"); string startingPos = ReserveName("charloop_starting_pos"); string endingPos = ReserveName("charloop_ending_pos"); additionalDeclarations.Add($"int {startingPos} = 0, {endingPos} = 0;"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); EmitSingleCharAtomicLoop(node); writer.WriteLine(); TransferSliceStaticPosToPos(); writer.WriteLine($"{endingPos} = pos;"); EmitAdd(writer, startingPos, !rtl ? node.M : -node.M); Goto(endLoop); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel, emitSemicolon: false); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } EmitStackPop(endingPos, startingPos); writer.WriteLine(); if (!rtl && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { writer.WriteLine($"if ({startingPos} >= {endingPos} ||"); using (EmitBlock(writer, literal.Item2 is not null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, global::System.Math.Min(inputSpan.Length, {endingPos} + {literal.Item2.Length - 1}) - {startingPos}), {Literal(literal.Item2)})) < 0)" : literal.Item3 is null ? $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item1)})) < 0)" : literal.Item3.Length switch { 2 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])})) < 0)", 3 => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])}, {Literal(literal.Item3[2])})) < 0)", _ => $" ({endingPos} = global::System.MemoryExtensions.LastIndexOfAny(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item3)})) < 0)", })) { Goto(doneLabel); } writer.WriteLine($"{endingPos} += {startingPos};"); writer.WriteLine($"pos = {endingPos};"); } else { using (EmitBlock(writer, $"if ({startingPos} {(!rtl ? ">=" : "<=")} {endingPos})")) { Goto(doneLabel); } writer.WriteLine(!rtl ? $"pos = --{endingPos};" : $"pos = ++{endingPos};"); } if (!rtl) { SliceInputSpan(writer); } writer.WriteLine(); MarkLabel(endLoop, emitSemicolon: false); EmitStackPush(expressionHasCaptures ? new[] { startingPos, endingPos, "base.Crawlpos()" } : new[] { startingPos, endingPos }); doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } if (node.M > 0) { // We emitted a repeater to handle the required iterations; add a newline after it. writer.WriteLine(); } Debug.Assert(node.M < node.N); // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. string? iterationCount = null; string? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = $"{node.N - node.M}"; iterationCount = ReserveName("lazyloop_iteration"); writer.WriteLine($"int {iterationCount} = 0;"); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. string? capturePos = null; if (expressionHasCaptures) { capturePos = ReserveName("lazyloop_capturepos"); additionalDeclarations.Add($"int {capturePos} = 0;"); } // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. string startingPos = ReserveName("lazyloop_pos"); additionalDeclarations.Add($"int {startingPos} = 0;"); writer.WriteLine($"{startingPos} = pos;"); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. string endLoopLabel = ReserveName("LazyLoopEnd"); Goto(endLoopLabel); writer.WriteLine(); // Backtracking section. Subsequent failures will jump to here. string backtrackingLabel = ReserveName("LazyLoopBacktrack"); MarkLabel(backtrackingLabel, emitSemicolon: false); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturePos is not null) { EmitUncaptureUntil(capturePos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { using (EmitBlock(writer, $"if ({iterationCount} >= {maxIterations})")) { Goto(doneLabel); } writer.WriteLine($"{iterationCount}++;"); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if ((node.Options & RegexOptions.RightToLeft) == 0) { if (iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). writer.WriteLine( literal.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item2[0])});" : literal.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item1)});" : literal.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item3[0])}, {Literal(literal.Item3[1])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch + literal.Item3)});", }); using (EmitBlock(writer, $"if ((uint){startingPos} >= (uint){sliceSpan}.Length || {sliceSpan}[{startingPos}] == {Literal(node.Ch)})")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } else if (iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. writer.WriteLine( literal2.Item2 is not null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item2)});" : literal2.Item3 is null ? $"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {Literal(literal2.Item1)});" : literal2.Item3.Length switch { 2 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])});", 3 => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3[0])}, {Literal(literal2.Item3[1])}, {Literal(literal2.Item3[2])});", _ => $"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(literal2.Item3)});", }); using (EmitBlock(writer, $"if ({startingPos} < 0)")) { Goto(doneLabel); } writer.WriteLine($"pos += {startingPos};"); SliceInputSpan(writer); } } // Store the position we've left off at in case we need to iterate again. writer.WriteLine($"{startingPos} = pos;"); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. string originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes writer.WriteLine(); MarkLabel(endLoopLabel); if (capturePos is not null) { writer.WriteLine($"{capturePos} = base.Crawlpos();"); } if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state var toPushPop = new List<string>(3) { startingPos }; if (capturePos is not null) { toPushPop.Add(capturePos); } if (iterationCount is not null) { toPushPop.Add(iterationCount); } string[] toPushPopArray = toPushPop.ToArray(); EmitStackPush(toPushPopArray); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("CharLazyBacktrack"); MarkLabel(backtrack, emitSemicolon: false); Array.Reverse(toPushPopArray); EmitStackPop(toPushPopArray); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; string originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } writer.WriteLine(); } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string startingPos = ReserveName("lazyloop_starting_pos"); string iterationCount = ReserveName("lazyloop_iteration"); string sawEmpty = ReserveName("lazyLoopEmptySeen"); string body = ReserveName("LazyLoopBody"); string endLoop = ReserveName("LazyLoopEnd"); writer.WriteLine($"int {iterationCount} = 0, {startingPos} = pos, {sawEmpty} = 0;"); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { Goto(endLoop); } writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos", sawEmpty } : new[] { startingPos, "pos", sawEmpty }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LazyLoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(body); } } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. using (EmitBlock(writer, $"if (pos == {startingPos})")) { writer.WriteLine($"{sawEmpty} = 1;"); } // We matched the next iteration. Jump to the subsequent code. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop(sawEmpty, "pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (doneLabel == originalDoneLabel) { Goto(originalDoneLabel); } else { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); } writer.WriteLine(); MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackPush(startingPos, iterationCount, sawEmpty); string skipBacktrack = ReserveName("SkipBacktrack"); Goto(skipBacktrack); writer.WriteLine(); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label string backtrack = ReserveName($"LazyLoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(sawEmpty, iterationCount, startingPos); if (maxIterations == int.MaxValue) { using (EmitBlock(writer, $"if ({sawEmpty} == 0)")) { Goto(body); } } else { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, maxIterations)} && {sawEmpty} == 0)")) { Goto(body); } } Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthCheck = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthCheck); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthCheck, rtl); return; } if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position with rtl using (EmitBlock(writer, $"for (int i = 0; i < {iterations}; i++)")) { EmitTimeoutCheck(writer, hasTimeout); EmitSingleChar(node); } } else if (iterations <= MaxUnrollSize) { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length || // slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // { // goto doneLabel; // } writer.Write($"if ("); if (emitLengthCheck) { writer.WriteLine($"{SpanLengthCheck(iterations)} ||"); writer.Write(" "); } EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); for (int i = 1; i < iterations; i++) { writer.WriteLine(" ||"); writer.Write(" "); EmitSingleChar(node, emitLengthCheck: false, clauseOnly: true); } writer.WriteLine(")"); using (EmitBlock(writer, null)) { Goto(doneLabel); } } else { // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthCheck) { EmitSpanLengthCheck(iterations); } string repeaterSpan = "repeaterSlice"; // As this repeater doesn't wrap arbitrary node emits, this shouldn't conflict with anything writer.WriteLine($"global::System.ReadOnlySpan<char> {repeaterSpan} = {sliceSpan}.Slice({sliceStaticPos}, {iterations});"); using (EmitBlock(writer, $"for (int i = 0; i < {repeaterSpan}.Length; i++)")) { EmitTimeoutCheck(writer, hasTimeout); string tmpTextSpanLocal = sliceSpan; // we want EmitSingleChar to refer to this temporary int tmpSliceStaticPos = sliceStaticPos; sliceSpan = repeaterSpan; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: "i"); sliceSpan = tmpTextSpanLocal; sliceStaticPos = tmpSliceStaticPos; } sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Span<char> setChars = stackalloc char[5]; // 5 is max optimized by IndexOfAny today int numSetChars = 0; string iterationLocal = ReserveName("iteration"); if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position for rtl string expr = $"inputSpan[pos - {iterationLocal} - 1]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } writer.WriteLine($"int {iterationLocal} = 0;"); string maxClause = maxIterations != int.MaxValue ? $"{CountIsLessThan(iterationLocal, maxIterations)} && " : ""; using (EmitBlock(writer, $"while ({maxClause}pos > {iterationLocal} && {expr})")) { EmitTimeoutCheck(writer, hasTimeout); writer.WriteLine($"{iterationLocal}++;"); } writer.WriteLine(); } else if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOf({sliceSpan}"); if (sliceStaticPos > 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine($", {Literal(node.Ch)});"); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it should // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); writer.Write($"int {iterationLocal} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}"); if (sliceStaticPos != 0) { writer.Write($".Slice({sliceStaticPos})"); } writer.WriteLine(numSetChars switch { 2 => $", {Literal(setChars[0])}, {Literal(setChars[1])});", 3 => $", {Literal(setChars[0])}, {Literal(setChars[1])}, {Literal(setChars[2])});", _ => $", {Literal(setChars.Slice(0, numSetChars).ToString())});", }); using (EmitBlock(writer, $"if ({iterationLocal} < 0)")) { writer.WriteLine(sliceStaticPos > 0 ? $"{iterationLocal} = {sliceSpan}.Length - {sliceStaticPos};" : $"{iterationLocal} = {sliceSpan}.Length;"); } writer.WriteLine(); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. TransferSliceStaticPosToPos(); writer.WriteLine($"int {iterationLocal} = inputSpan.Length - pos;"); } else { // For everything else, do a normal loop. string expr = $"{sliceSpan}[{iterationLocal}]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } if (minIterations != 0 || maxIterations != int.MaxValue) { // For any loops other than * loops, transfer text pos to pos in // order to zero it out to be able to use the single iteration variable // for both iteration count and indexer. TransferSliceStaticPosToPos(); } writer.WriteLine($"int {iterationLocal} = {sliceStaticPos};"); sliceStaticPos = 0; string maxClause = maxIterations != int.MaxValue ? $"{CountIsLessThan(iterationLocal, maxIterations)} && " : ""; using (EmitBlock(writer, $"while ({maxClause}(uint){iterationLocal} < (uint){sliceSpan}.Length && {expr})")) { EmitTimeoutCheck(writer, hasTimeout); writer.WriteLine($"{iterationLocal}++;"); } writer.WriteLine(); } // Check to ensure we've found at least min iterations. if (minIterations > 0) { using (EmitBlock(writer, $"if ({CountIsLessThan(iterationLocal, minIterations)})")) { Goto(doneLabel); } writer.WriteLine(); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. if (!rtl) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice({iterationLocal});"); writer.WriteLine($"pos += {iterationLocal};"); } else { writer.WriteLine($"pos -= {iterationLocal};"); } } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static pos for rtl } string expr = !rtl ? $"{sliceSpan}[{sliceStaticPos}]" : "inputSpan[pos - 1]"; if (node.IsSetFamily) { expr = MatchCharacterClass(hasTextInfo, options, expr, node.Str!, IsCaseInsensitive(node), negate: false, additionalDeclarations, ref requiredHelpers); } else { expr = ToLowerIfNeeded(hasTextInfo, options, expr, IsCaseInsensitive(node)); expr = $"{expr} {(node.IsOneFamily ? "==" : "!=")} {Literal(node.Ch)}"; } string spaceAvailable = rtl ? "pos > 0" : sliceStaticPos != 0 ? $"(uint){sliceSpan}.Length > (uint){sliceStaticPos}" : $"!{sliceSpan}.IsEmpty"; using (EmitBlock(writer, $"if ({spaceAvailable} && {expr})")) { if (!rtl) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice(1);"); writer.WriteLine($"pos++;"); } else { writer.WriteLine($"pos--;"); } } } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. string i = ReserveName("loop_iteration"); using (EmitBlock(writer, $"for (int {i} = 0; {i} < {node.M}; {i}++)")) { EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs } } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); string originalDoneLabel = doneLabel; string startingPos = ReserveName("loop_starting_pos"); string iterationCount = ReserveName("loop_iteration"); string body = ReserveName("LoopBody"); string endLoop = ReserveName("LoopEnd"); additionalDeclarations.Add($"int {iterationCount} = 0, {startingPos} = 0;"); writer.WriteLine($"{iterationCount} = 0;"); writer.WriteLine($"{startingPos} = pos;"); writer.WriteLine(); // Iteration body MarkLabel(body, emitSemicolon: false); EmitTimeoutCheck(writer, hasTimeout); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackPush(expressionHasCaptures ? new[] { "base.Crawlpos()", startingPos, "pos" } : new[] { startingPos, "pos" }); writer.WriteLine(); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. writer.WriteLine($"{startingPos} = pos;"); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. writer.WriteLine($"{iterationCount}++;"); writer.WriteLine(); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. string iterationFailedLabel = ReserveName("LoopIterationNoMatch"); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); writer.WriteLine(); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. using (EmitBlock(writer, (minIterations > 0, maxIterations == int.MaxValue) switch { (true, true) => $"if (pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)})", (true, false) => $"if ((pos != {startingPos} || {CountIsLessThan(iterationCount, minIterations)}) && {CountIsLessThan(iterationCount, maxIterations)})", (false, true) => $"if (pos != {startingPos})", (false, false) => $"if (pos != {startingPos} && {CountIsLessThan(iterationCount, maxIterations)})", })) { Goto(body); } // We've matched as many iterations as we can with this configuration. Jump to what comes after the loop. Goto(endLoop); writer.WriteLine(); // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel, emitSemicolon: false); writer.WriteLine($"{iterationCount}--;"); using (EmitBlock(writer, $"if ({iterationCount} < 0)")) { Goto(originalDoneLabel); } EmitStackPop("pos", startingPos); if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); } SliceInputSpan(writer); if (minIterations > 0) { using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } using (EmitBlock(writer, $"if ({CountIsLessThan(iterationCount, minIterations)})")) { Goto(childBacktracks ? doneLabel : originalDoneLabel); } } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { Goto(endLoop); writer.WriteLine(); string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); using (EmitBlock(writer, $"if ({iterationCount} == 0)")) { Goto(originalDoneLabel); } Goto(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { writer.WriteLine(); // Store the loop's state EmitStackPush(startingPos, iterationCount); // Skip past the backtracking section string end = ReserveName("SkipBacktrack"); Goto(end); writer.WriteLine(); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label string backtrack = ReserveName("LoopBacktrack"); MarkLabel(backtrack, emitSemicolon: false); EmitStackPop(iterationCount, startingPos); Goto(doneLabel); writer.WriteLine(); doneLabel = backtrack; MarkLabel(end); } } } // Gets a comparison for whether the value is less than the upper bound. static string CountIsLessThan(string value, int exclusiveUpper) => exclusiveUpper == 1 ? $"{value} == 0" : $"{value} < {exclusiveUpper}"; // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(string capturepos) { string name = "UncaptureUntil"; if (!additionalLocalFunctions.ContainsKey(name)) { var lines = new string[9]; lines[0] = "// <summary>Undo captures until we reach the specified capture position.</summary>"; lines[1] = "[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"void {name}(int capturepos)"; lines[3] = "{"; lines[4] = " while (base.Crawlpos() > capturepos)"; lines[5] = " {"; lines[6] = " base.Uncapture();"; lines[7] = " }"; lines[8] = "}"; additionalLocalFunctions.Add(name, lines); } writer.WriteLine($"{name}({capturepos});"); } /// <summary>Pushes values on to the backtracking stack.</summary> void EmitStackPush(params string[] args) { Debug.Assert(args.Length is >= 1); string function = $"StackPush{args.Length}"; additionalDeclarations.Add("int stackpos = 0;"); if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[24 + args.Length]; lines[0] = $"// <summary>Push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[3] = $"{{"; lines[4] = $" // If there's space available for {(args.Length > 1 ? $"all {args.Length} values, store them" : "the value, store it")}."; lines[5] = $" int[] s = stack;"; lines[6] = $" int p = pos;"; lines[7] = $" if ((uint){(args.Length > 1 ? $"(p + {args.Length - 1})" : "p")} < (uint)s.Length)"; lines[8] = $" {{"; for (int i = 0; i < args.Length; i++) { lines[9 + i] = $" s[p{(i == 0 ? "" : $" + {i}")}] = arg{i};"; } lines[9 + args.Length] = args.Length > 1 ? $" pos += {args.Length};" : " pos++;"; lines[10 + args.Length] = $" return;"; lines[11 + args.Length] = $" }}"; lines[12 + args.Length] = $""; lines[13 + args.Length] = $" // Otherwise, resize the stack to make room and try again."; lines[14 + args.Length] = $" WithResize(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[15 + args.Length] = $""; lines[16 + args.Length] = $" // <summary>Resize the backtracking stack array and push {args.Length} value{(args.Length == 1 ? "" : "s")} onto the stack.</summary>"; lines[17 + args.Length] = $" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]"; lines[18 + args.Length] = $" static void WithResize(ref int[] stack, ref int pos{FormatN(", int arg{0}", args.Length)})"; lines[19 + args.Length] = $" {{"; lines[20 + args.Length] = $" global::System.Array.Resize(ref stack, (pos + {args.Length - 1}) * 2);"; lines[21 + args.Length] = $" {function}(ref stack, ref pos{FormatN(", arg{0}", args.Length)});"; lines[22 + args.Length] = $" }}"; lines[23 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(ref base.runstack!, ref stackpos, {string.Join(", ", args)});"); } /// <summary>Pops values from the backtracking stack into the specified locations.</summary> void EmitStackPop(params string[] args) { Debug.Assert(args.Length is >= 1); if (args.Length == 1) { writer.WriteLine($"{args[0]} = {StackPop()};"); return; } string function = $"StackPop{args.Length}"; if (!additionalLocalFunctions.ContainsKey(function)) { var lines = new string[5 + args.Length]; lines[0] = $"// <summary>Pop {args.Length} value{(args.Length == 1 ? "" : "s")} from the backtracking stack.</summary>"; lines[1] = $"[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]"; lines[2] = $"static void {function}(int[] stack, ref int pos{FormatN(", out int arg{0}", args.Length)})"; lines[3] = $"{{"; for (int i = 0; i < args.Length; i++) { lines[4 + i] = $" arg{i} = stack[--pos];"; } lines[4 + args.Length] = $"}}"; additionalLocalFunctions.Add(function, lines); } writer.WriteLine($"{function}(base.runstack, ref stackpos, out {string.Join(", out ", args)});"); } /// <summary>Expression for popping the next item from the backtracking stack.</summary> string StackPop() => "base.runstack![--stackpos]"; /// <summary>Concatenates the strings resulting from formatting the format string with the values [0, count).</summary> static string FormatN(string format, int count) => string.Concat(from i in Enumerable.Range(0, count) select string.Format(format, i)); } private static bool EmitLoopTimeoutCounterIfNeeded(IndentedTextWriter writer, RegexMethod rm) { if (rm.MatchTimeout != Timeout.Infinite) { writer.WriteLine("int loopTimeoutCounter = 0;"); return true; } return false; } /// <summary>Emits a timeout check.</summary> private static void EmitTimeoutCheck(IndentedTextWriter writer, bool hasTimeout) { const int LoopTimeoutCheckCount = 2048; // A conservative value to guarantee the correct timeout handling. if (hasTimeout) { // Increment counter for each loop iteration. // Emit code to check the timeout every 2048th iteration. using (EmitBlock(writer, $"if (++loopTimeoutCounter == {LoopTimeoutCheckCount})")) { writer.WriteLine("loopTimeoutCounter = 0;"); writer.WriteLine("base.CheckTimeout();"); } writer.WriteLine(); } } private static bool EmitInitializeCultureForTryMatchAtCurrentPositionIfNecessary(IndentedTextWriter writer, RegexMethod rm, AnalysisResults analysis) { if (analysis.HasIgnoreCase && ((RegexOptions)rm.Options & RegexOptions.CultureInvariant) == 0) { writer.WriteLine("global::System.Globalization.TextInfo textInfo = global::System.Globalization.CultureInfo.CurrentCulture.TextInfo;"); return true; } return false; } private static bool UseToLowerInvariant(bool hasTextInfo, RegexOptions options) => !hasTextInfo || (options & RegexOptions.CultureInvariant) != 0; private static string ToLower(bool hasTextInfo, RegexOptions options, string expression) => UseToLowerInvariant(hasTextInfo, options) ? $"char.ToLowerInvariant({expression})" : $"textInfo.ToLower({expression})"; private static string ToLowerIfNeeded(bool hasTextInfo, RegexOptions options, string expression, bool toLower) => toLower ? ToLower(hasTextInfo, options, expression) : expression; private static string MatchCharacterClass(bool hasTextInfo, RegexOptions options, string chExpr, string charClass, bool caseInsensitive, bool negate, HashSet<string> additionalDeclarations, ref RequiredHelperFunctions requiredHelpers) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // ideally this could just be "return true;", but we need to evaluate the expression for its side effects return $"({chExpr} {(negate ? "<" : ">=")} 0)"; // a char is unsigned and thus won't ever be negative case RegexCharClass.DigitClass: case RegexCharClass.NotDigitClass: negate ^= charClass == RegexCharClass.NotDigitClass; return $"{(negate ? "!" : "")}char.IsDigit({chExpr})"; case RegexCharClass.SpaceClass: case RegexCharClass.NotSpaceClass: negate ^= charClass == RegexCharClass.NotSpaceClass; return $"{(negate ? "!" : "")}char.IsWhiteSpace({chExpr})"; case RegexCharClass.WordClass: case RegexCharClass.NotWordClass: requiredHelpers |= RequiredHelperFunctions.IsWordChar; negate ^= charClass == RegexCharClass.NotWordClass; return $"{(negate ? "!" : "")}IsWordChar({chExpr})"; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant(hasTextInfo, options); if (!invariant) { chExpr = ToLower(hasTextInfo, options, chExpr); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { negate ^= RegexCharClass.IsNegated(charClass); return lowInclusive == highInclusive ? $"({chExpr} {(negate ? "!=" : "==")} {Literal(lowInclusive)})" : $"(((uint){chExpr}) - {Literal(lowInclusive)} {(negate ? ">" : "<=")} (uint)({Literal(highInclusive)} - {Literal(lowInclusive)}))"; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { negate ^= negated; return $"(char.GetUnicodeCategory({chExpr}) {(negate ? "!=" : "==")} global::System.Globalization.UnicodeCategory.{category})"; } // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it may be cheaper and smaller to compare against each than it is to use a lookup table. We can also special-case // the very common case with case insensitivity of two characters next to each other being the upper and lowercase // ASCII variants of each other, in which case we can use bit manipulation to avoid a comparison. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int mask; switch (RegexCharClass.GetSetChars(charClass, setChars)) { case 2: if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) { return $"(({chExpr} | 0x{mask:X}) {(negate ? "!=" : "==")} {Literal((char)(setChars[1] | mask))})"; } additionalDeclarations.Add("char ch;"); return negate ? $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}))" : $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}))"; case 3: additionalDeclarations.Add("char ch;"); return (negate, RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out mask)) switch { (false, false) => $"(((ch = {chExpr}) == {Literal(setChars[0])}) | (ch == {Literal(setChars[1])}) | (ch == {Literal(setChars[2])}))", (true, false) => $"(((ch = {chExpr}) != {Literal(setChars[0])}) & (ch != {Literal(setChars[1])}) & (ch != {Literal(setChars[2])}))", (false, true) => $"((((ch = {chExpr}) | 0x{mask:X}) == {Literal((char)(setChars[1] | mask))}) | (ch == {Literal(setChars[2])}))", (true, true) => $"((((ch = {chExpr}) | 0x{mask:X}) != {Literal((char)(setChars[1] | mask))}) & (ch != {Literal(setChars[2])}))", }; } } // All options after this point require a ch local. additionalDeclarations.Add("char ch;"); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) return negate ? $"((ch = {chExpr}) < 128 || !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) >= 128 && global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. return negate ? $"((ch = {chExpr}) >= 128 && !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))" : $"((ch = {chExpr}) < 128 || global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))"; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = StringExtensions.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. return negate ? $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. return negate ? $"((ch = {chExpr}) < 128 && ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0)" : $"((ch = {chExpr}) >= 128 || ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0)"; } // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. return (negate, invariant) switch { (false, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (true, false) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass((char)ch, {Literal(charClass)}))", (false, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) != 0 : global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", (true, true) => $"((ch = {chExpr}) < 128 ? ({Literal(bitVectorString)}[ch >> 4] & (1 << (ch & 0xF))) == 0 : !global::System.Text.RegularExpressions.RegexRunner.CharInClass(char.ToLowerInvariant((char)ch), {Literal(charClass)}))", }; } /// <summary> /// Replaces <see cref="AdditionalDeclarationsPlaceholder"/> in <paramref name="writer"/> with /// all of the variable declarations in <paramref name="declarations"/>. /// </summary> /// <param name="writer">The writer around a StringWriter to have additional declarations inserted into.</param> /// <param name="declarations">The additional declarations to insert.</param> /// <param name="position">The position into the writer at which to insert the additional declarations.</param> /// <param name="indent">The indentation to use for the additional declarations.</param> private static void ReplaceAdditionalDeclarations(IndentedTextWriter writer, HashSet<string> declarations, int position, int indent) { if (declarations.Count != 0) { var tmp = new StringBuilder(); foreach (string decl in declarations.OrderBy(s => s)) { for (int i = 0; i < indent; i++) { tmp.Append(IndentedTextWriter.DefaultTabString); } tmp.AppendLine(decl); } ((StringWriter)writer.InnerWriter).GetStringBuilder().Insert(position, tmp.ToString()); } } /// <summary>Formats the character as valid C#.</summary> private static string Literal(char c) => SymbolDisplay.FormatLiteral(c, quote: true); /// <summary>Formats the string as valid C#.</summary> private static string Literal(string s) => SymbolDisplay.FormatLiteral(s, quote: true); private static string Literal(RegexOptions options) { string s = options.ToString(); if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) { // The options were formatted as an int, which means the runtime couldn't // produce a textual representation. So just output casting the value as an int. Debug.Fail("This shouldn't happen, as we should only get to the point of emitting code if RegexOptions was valid."); return $"(global::System.Text.RegularExpressions.RegexOptions)({(int)options})"; } // Parse the runtime-generated "Option1, Option2" into each piece and then concat // them back together. string[] parts = s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parts.Length; i++) { parts[i] = "global::System.Text.RegularExpressions.RegexOptions." + parts[i].Trim(); } return string.Join(" | ", parts); } /// <summary>Gets a textual description of the node fit for rendering in a comment in source.</summary> private static string DescribeNode(RegexNode node, AnalysisResults analysis) { bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; return node.Kind switch { RegexNodeKind.Alternate => $"Match with {node.ChildCount()} alternative expressions{(analysis.IsAtomicByAncestor(node) ? ", atomically" : "")}.", RegexNodeKind.Atomic => $"Atomic group.", RegexNodeKind.Beginning => "Match if at the beginning of the string.", RegexNodeKind.Bol => "Match if at the beginning of a line.", RegexNodeKind.Boundary => $"Match if at a word boundary.", RegexNodeKind.Capture when node.M == -1 && node.N != -1 => $"Non-capturing balancing group. Uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N != -1 => $"Balancing group. Captures the {DescribeCapture(node.M, analysis)} and uncaptures the {DescribeCapture(node.N, analysis)}.", RegexNodeKind.Capture when node.N == -1 => $"{DescribeCapture(node.M, analysis)}.", RegexNodeKind.Concatenate => "Match a sequence of expressions.", RegexNodeKind.ECMABoundary => $"Match if at a word boundary (according to ECMAScript rules).", RegexNodeKind.Empty => $"Match an empty string.", RegexNodeKind.End => "Match if at the end of the string.", RegexNodeKind.EndZ => "Match if at the end of the string or if before an ending newline.", RegexNodeKind.Eol => "Match if at the end of a line.", RegexNodeKind.Loop or RegexNodeKind.Lazyloop => node.M == 0 && node.N == 1 ? $"Optional ({(node.Kind is RegexNodeKind.Loop ? "greedy" : "lazy")})." : $"Loop {DescribeLoop(node, analysis)}.", RegexNodeKind.Multi => $"Match the string {Literal(node.Str!)}{(rtl ? " backwards" : "")}.", RegexNodeKind.NonBoundary => $"Match if at anything other than a word boundary.", RegexNodeKind.NonECMABoundary => $"Match if at anything other than a word boundary (according to ECMAScript rules).", RegexNodeKind.Nothing => $"Fail to match.", RegexNodeKind.Notone => $"Match any character other than {Literal(node.Ch)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy => $"Match a character other than {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.One => $"Match {Literal(node.Ch)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy => $"Match {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.NegativeLookaround => $"Zero-width negative {(rtl ? "lookbehind" : "lookahead")}.", RegexNodeKind.Backreference => $"Match the same text as matched by the {DescribeCapture(node.M, analysis)}.", RegexNodeKind.PositiveLookaround => $"Zero-width positive {(rtl ? "lookbehind" : "lookahead")}.", RegexNodeKind.Set => $"Match {DescribeSet(node.Str!)}{(rtl ? " backwards" : "")}.", RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy => $"Match {DescribeSet(node.Str!)} {DescribeLoop(node, analysis)}.", RegexNodeKind.Start => "Match if at the start position.", RegexNodeKind.ExpressionConditional => $"Conditionally match one of two expressions depending on whether an initial expression matches.", RegexNodeKind.BackreferenceConditional => $"Conditionally match one of two expressions depending on whether the {DescribeCapture(node.M, analysis)} matched.", RegexNodeKind.UpdateBumpalong => $"Advance the next matching position.", _ => $"Unknown node type {node.Kind}", }; } /// <summary>Gets an identifer to describe a capture group.</summary> private static string DescribeCapture(int capNum, AnalysisResults analysis) { // If we can get a capture name from the captures collection and it's not just a numerical representation of the group, use it. string name = RegexParser.GroupNameFromNumber(analysis.RegexTree.CaptureNumberSparseMapping, analysis.RegexTree.CaptureNames, analysis.RegexTree.CaptureCount, capNum); if (!string.IsNullOrEmpty(name) && (!int.TryParse(name, out int id) || id != capNum)) { name = Literal(name); } else { // Otherwise, create a numerical description of the capture group. int tens = capNum % 10; name = tens is >= 1 and <= 3 && capNum % 100 is < 10 or > 20 ? // Ends in 1, 2, 3 but not 11, 12, or 13 tens switch { 1 => $"{capNum}st", 2 => $"{capNum}nd", _ => $"{capNum}rd", } : $"{capNum}th"; } return $"{name} capture group"; } /// <summary>Gets a textual description of what characters match a set.</summary> private static string DescribeSet(string charClass) => charClass switch { RegexCharClass.AnyClass => "any character", RegexCharClass.DigitClass => "a Unicode digit", RegexCharClass.ECMADigitClass => "'0' through '9'", RegexCharClass.ECMASpaceClass => "a whitespace character (ECMA)", RegexCharClass.ECMAWordClass => "a word character (ECMA)", RegexCharClass.NotDigitClass => "any character other than a Unicode digit", RegexCharClass.NotECMADigitClass => "any character other than '0' through '9'", RegexCharClass.NotECMASpaceClass => "any character other than a space character (ECMA)", RegexCharClass.NotECMAWordClass => "any character other than a word character (ECMA)", RegexCharClass.NotSpaceClass => "any character other than a space character", RegexCharClass.NotWordClass => "any character other than a word character", RegexCharClass.SpaceClass => "a whitespace character", RegexCharClass.WordClass => "a word character", _ => $"a character in the set {RegexCharClass.DescribeSet(charClass)}", }; /// <summary>Writes a textual description of the node tree fit for rending in source.</summary> /// <param name="writer">The writer to which the description should be written.</param> /// <param name="node">The node being written.</param> /// <param name="prefix">The prefix to write at the beginning of every line, including a "//" for a comment.</param> /// <param name="analyses">Analysis of the tree</param> /// <param name="depth">The depth of the current node.</param> private static void DescribeExpression(TextWriter writer, RegexNode node, string prefix, AnalysisResults analysis, int depth = 0) { bool skip = node.Kind switch { // For concatenations, flatten the contents into the parent, but only if the parent isn't a form of alternation, // where each branch is considered to be independent rather than a concatenation. RegexNodeKind.Concatenate when node.Parent is not { Kind: RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional } => true, // For atomic, skip the node if we'll instead render the atomic label as part of rendering the child. RegexNodeKind.Atomic when node.Child(0).Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop or RegexNodeKind.Alternate => true, // Don't skip anything else. _ => false, }; if (!skip) { string tag = node.Parent?.Kind switch { RegexNodeKind.ExpressionConditional when node.Parent.Child(0) == node => "Condition: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(1) == node => "Matched: ", RegexNodeKind.ExpressionConditional when node.Parent.Child(2) == node => "Not Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(0) == node => "Matched: ", RegexNodeKind.BackreferenceConditional when node.Parent.Child(1) == node => "Not Matched: ", _ => "", }; // Write out the line for the node. const char BulletPoint = '\u25CB'; writer.WriteLine($"{prefix}{new string(' ', depth * 4)}{BulletPoint} {tag}{DescribeNode(node, analysis)}"); } // Recur into each of its children. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { int childDepth = skip ? depth : depth + 1; DescribeExpression(writer, node.Child(i), prefix, analysis, childDepth); } } /// <summary>Gets a textual description of a loop's style and bounds.</summary> private static string DescribeLoop(RegexNode node, AnalysisResults analysis) { string style = node.Kind switch { _ when node.M == node.N => "exactly", RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic => "atomically", RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop => "greedily", RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy => "lazily", RegexNodeKind.Loop => analysis.IsAtomicByAncestor(node) ? "greedily and atomically" : "greedily", _ /* RegexNodeKind.Lazyloop */ => analysis.IsAtomicByAncestor(node) ? "lazily and atomically" : "lazily", }; string bounds = node.M == node.N ? $" {node.M} times" : (node.M, node.N) switch { (0, int.MaxValue) => " any number of times", (1, int.MaxValue) => " at least once", (2, int.MaxValue) => " at least twice", (_, int.MaxValue) => $" at least {node.M} times", (0, 1) => ", optionally", (0, _) => $" at most {node.N} times", _ => $" at least {node.M} and at most {node.N} times" }; return style + bounds; } private static FinishEmitScope EmitScope(IndentedTextWriter writer, string title, bool faux = false) => EmitBlock(writer, $"// {title}", faux: faux); private static FinishEmitScope EmitBlock(IndentedTextWriter writer, string? clause, bool faux = false) { if (clause is not null) { writer.WriteLine(clause); } writer.WriteLine(faux ? "//{" : "{"); writer.Indent++; return new FinishEmitScope(writer, faux); } private static void EmitAdd(IndentedTextWriter writer, string variable, int value) { if (value == 0) { return; } writer.WriteLine( value == 1 ? $"{variable}++;" : value == -1 ? $"{variable}--;" : value > 0 ? $"{variable} += {value};" : value < 0 && value > int.MinValue ? $"{variable} -= {-value};" : $"{variable} += {value.ToString(CultureInfo.InvariantCulture)};"); } private readonly struct FinishEmitScope : IDisposable { private readonly IndentedTextWriter _writer; private readonly bool _faux; public FinishEmitScope(IndentedTextWriter writer, bool faux) { _writer = writer; _faux = faux; } public void Dispose() { if (_writer is not null) { _writer.Indent--; _writer.WriteLine(_faux ? "//}" : "}"); } } } /// <summary>Bit flags indicating which additional helpers should be emitted into the regex class.</summary> [Flags] private enum RequiredHelperFunctions { /// <summary>No additional functions are required.</summary> None = 0b0, /// <summary>The IsWordChar helper is required.</summary> IsWordChar = 0b1, /// <summary>The IsBoundary helper is required.</summary> IsBoundary = 0b10, /// <summary>The IsECMABoundary helper is required.</summary> IsECMABoundary = 0b100 } } }
1
dotnet/runtime
66,321
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug
Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
stephentoub
2022-03-08T01:37:40Z
2022-03-08T19:24:48Z
446a0d610d4479fa9ba58ec14a89132a18ed33c4
b6c5a12cfa92e06734286bd991e7cca87ded1e24
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug. Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.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.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions { /// <summary> /// RegexCompiler translates a block of RegexCode to MSIL, and creates a subclass of the RegexRunner type. /// </summary> internal abstract class RegexCompiler { private static readonly FieldInfo s_runtextstartField = RegexRunnerField("runtextstart"); private static readonly FieldInfo s_runtextposField = RegexRunnerField("runtextpos"); private static readonly FieldInfo s_runstackField = RegexRunnerField("runstack"); private static readonly MethodInfo s_captureMethod = RegexRunnerMethod("Capture"); private static readonly MethodInfo s_transferCaptureMethod = RegexRunnerMethod("TransferCapture"); private static readonly MethodInfo s_uncaptureMethod = RegexRunnerMethod("Uncapture"); private static readonly MethodInfo s_isMatchedMethod = RegexRunnerMethod("IsMatched"); private static readonly MethodInfo s_matchLengthMethod = RegexRunnerMethod("MatchLength"); private static readonly MethodInfo s_matchIndexMethod = RegexRunnerMethod("MatchIndex"); private static readonly MethodInfo s_isBoundaryMethod = typeof(RegexRunner).GetMethod("IsBoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_isWordCharMethod = RegexRunnerMethod("IsWordChar"); private static readonly MethodInfo s_isECMABoundaryMethod = typeof(RegexRunner).GetMethod("IsECMABoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_crawlposMethod = RegexRunnerMethod("Crawlpos"); private static readonly MethodInfo s_charInClassMethod = RegexRunnerMethod("CharInClass"); private static readonly MethodInfo s_checkTimeoutMethod = RegexRunnerMethod("CheckTimeout"); private static readonly MethodInfo s_charIsDigitMethod = typeof(char).GetMethod("IsDigit", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charIsWhiteSpaceMethod = typeof(char).GetMethod("IsWhiteSpace", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charGetUnicodeInfo = typeof(char).GetMethod("GetUnicodeCategory", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charToLowerInvariantMethod = typeof(char).GetMethod("ToLowerInvariant", new Type[] { typeof(char) })!; private static readonly MethodInfo s_cultureInfoGetCurrentCultureMethod = typeof(CultureInfo).GetMethod("get_CurrentCulture")!; private static readonly MethodInfo s_cultureInfoGetTextInfoMethod = typeof(CultureInfo).GetMethod("get_TextInfo")!; private static readonly MethodInfo s_spanGetItemMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Item", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanGetLengthMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Length")!; private static readonly MethodInfo s_memoryMarshalGetReference = typeof(MemoryMarshal).GetMethod("GetReference", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfChar = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfSpan = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfChar = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfSpan = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanSliceIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanSliceIntIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int), typeof(int) })!; private static readonly MethodInfo s_spanStartsWith = typeof(MemoryExtensions).GetMethod("StartsWith", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_stringAsSpanMethod = typeof(MemoryExtensions).GetMethod("AsSpan", new Type[] { typeof(string) })!; private static readonly MethodInfo s_stringGetCharsMethod = typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) })!; private static readonly MethodInfo s_textInfoToLowerMethod = typeof(TextInfo).GetMethod("ToLower", new Type[] { typeof(char) })!; private static readonly MethodInfo s_arrayResize = typeof(Array).GetMethod("Resize")!.MakeGenericMethod(typeof(int)); private static readonly MethodInfo s_mathMinIntInt = typeof(Math).GetMethod("Min", new Type[] { typeof(int), typeof(int) })!; /// <summary>The ILGenerator currently in use.</summary> protected ILGenerator? _ilg; /// <summary>The options for the expression.</summary> protected RegexOptions _options; /// <summary>The <see cref="RegexTree"/> written for the expression.</summary> protected RegexTree? _regexTree; /// <summary>Whether this expression has a non-infinite timeout.</summary> protected bool _hasTimeout; /// <summary>Pool of Int32 LocalBuilders.</summary> private Stack<LocalBuilder>? _int32LocalsPool; /// <summary>Pool of ReadOnlySpan of char locals.</summary> private Stack<LocalBuilder>? _readOnlySpanCharLocalsPool; /// <summary>Local representing a cached TextInfo for the culture to use for all case-insensitive operations.</summary> private LocalBuilder? _textInfo; /// <summary>Local representing a timeout counter for loops (set loops and node loops).</summary> private LocalBuilder? _loopTimeoutCounter; /// <summary>A frequency with which the timeout should be validated.</summary> private const int LoopTimeoutCheckCount = 2048; private static FieldInfo RegexRunnerField(string fieldname) => typeof(RegexRunner).GetField(fieldname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; private static MethodInfo RegexRunnerMethod(string methname) => typeof(RegexRunner).GetMethod(methname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; /// <summary> /// Entry point to dynamically compile a regular expression. The expression is compiled to /// an in-memory assembly. /// </summary> internal static RegexRunnerFactory? Compile(string pattern, RegexTree regexTree, RegexOptions options, bool hasTimeout) => new RegexLWCGCompiler().FactoryInstanceFromCode(pattern, regexTree, options, hasTimeout); /// <summary>A macro for _ilg.DefineLabel</summary> private Label DefineLabel() => _ilg!.DefineLabel(); /// <summary>A macro for _ilg.MarkLabel</summary> private void MarkLabel(Label l) => _ilg!.MarkLabel(l); /// <summary>A macro for _ilg.Emit(Opcodes.Ldstr, str)</summary> protected void Ldstr(string str) => _ilg!.Emit(OpCodes.Ldstr, str); /// <summary>A macro for the various forms of Ldc.</summary> protected void Ldc(int i) => _ilg!.Emit(OpCodes.Ldc_I4, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ldc_I8).</summary> protected void LdcI8(long i) => _ilg!.Emit(OpCodes.Ldc_I8, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ret).</summary> protected void Ret() => _ilg!.Emit(OpCodes.Ret); /// <summary>A macro for _ilg.Emit(OpCodes.Dup).</summary> protected void Dup() => _ilg!.Emit(OpCodes.Dup); /// <summary>A macro for _ilg.Emit(OpCodes.Rem_Un).</summary> private void RemUn() => _ilg!.Emit(OpCodes.Rem_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Ceq).</summary> private void Ceq() => _ilg!.Emit(OpCodes.Ceq); /// <summary>A macro for _ilg.Emit(OpCodes.Cgt_Un).</summary> private void CgtUn() => _ilg!.Emit(OpCodes.Cgt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Clt_Un).</summary> private void CltUn() => _ilg!.Emit(OpCodes.Clt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Pop).</summary> private void Pop() => _ilg!.Emit(OpCodes.Pop); /// <summary>A macro for _ilg.Emit(OpCodes.Add).</summary> private void Add() => _ilg!.Emit(OpCodes.Add); /// <summary>A macro for _ilg.Emit(OpCodes.Sub).</summary> private void Sub() => _ilg!.Emit(OpCodes.Sub); /// <summary>A macro for _ilg.Emit(OpCodes.Mul).</summary> private void Mul() => _ilg!.Emit(OpCodes.Mul); /// <summary>A macro for _ilg.Emit(OpCodes.And).</summary> private void And() => _ilg!.Emit(OpCodes.And); /// <summary>A macro for _ilg.Emit(OpCodes.Or).</summary> private void Or() => _ilg!.Emit(OpCodes.Or); /// <summary>A macro for _ilg.Emit(OpCodes.Shl).</summary> private void Shl() => _ilg!.Emit(OpCodes.Shl); /// <summary>A macro for _ilg.Emit(OpCodes.Shr).</summary> private void Shr() => _ilg!.Emit(OpCodes.Shr); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloca).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloca(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloca, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_U2).</summary> private void LdindU2() => _ilg!.Emit(OpCodes.Ldind_U2); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I4).</summary> private void LdindI4() => _ilg!.Emit(OpCodes.Ldind_I4); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I8).</summary> private void LdindI8() => _ilg!.Emit(OpCodes.Ldind_I8); /// <summary>A macro for _ilg.Emit(OpCodes.Unaligned).</summary> private void Unaligned(byte alignment) => _ilg!.Emit(OpCodes.Unaligned, alignment); /// <summary>A macro for _ilg.Emit(OpCodes.Stloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Stloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Stloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldarg_0).</summary> protected void Ldthis() => _ilg!.Emit(OpCodes.Ldarg_0); /// <summary>A macro for _ilgEmit(OpCodes.Ldarg_1) </summary> private void Ldarg_1() => _ilg!.Emit(OpCodes.Ldarg_1); /// <summary>A macro for Ldthis(); Ldfld();</summary> protected void Ldthisfld(FieldInfo ft) { Ldthis(); _ilg!.Emit(OpCodes.Ldfld, ft); } /// <summary>Fetches the address of argument in passed in <paramref name="position"/></summary> /// <param name="position">The position of the argument which address needs to be fetched.</param> private void Ldarga_s(int position) => _ilg!.Emit(OpCodes.Ldarga_S, position); /// <summary>A macro for Ldthis(); Ldfld(); Stloc();</summary> private void Mvfldloc(FieldInfo ft, LocalBuilder lt) { Ldthisfld(ft); Stloc(lt); } /// <summary>A macro for _ilg.Emit(OpCodes.Stfld).</summary> protected void Stfld(FieldInfo ft) => _ilg!.Emit(OpCodes.Stfld, ft); /// <summary>A macro for _ilg.Emit(OpCodes.Callvirt, mt).</summary> protected void Callvirt(MethodInfo mt) => _ilg!.Emit(OpCodes.Callvirt, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Call, mt).</summary> protected void Call(MethodInfo mt) => _ilg!.Emit(OpCodes.Call, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (short jump).</summary> private void Brfalse(Label l) => _ilg!.Emit(OpCodes.Brfalse_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (long form).</summary> private void BrfalseFar(Label l) => _ilg!.Emit(OpCodes.Brfalse, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue) (long form).</summary> private void BrtrueFar(Label l) => _ilg!.Emit(OpCodes.Brtrue, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br) (long form).</summary> private void BrFar(Label l) => _ilg!.Emit(OpCodes.Br, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble) (long form).</summary> private void BleFar(Label l) => _ilg!.Emit(OpCodes.Ble, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt) (long form).</summary> private void BltFar(Label l) => _ilg!.Emit(OpCodes.Blt, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_Un) (long form).</summary> private void BltUnFar(Label l) => _ilg!.Emit(OpCodes.Blt_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge) (long form).</summary> private void BgeFar(Label l) => _ilg!.Emit(OpCodes.Bge, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un) (long form).</summary> private void BgeUnFar(Label l) => _ilg!.Emit(OpCodes.Bge_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne) (long form).</summary> private void BneFar(Label l) => _ilg!.Emit(OpCodes.Bne_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq) (long form).</summary> private void BeqFar(Label l) => _ilg!.Emit(OpCodes.Beq, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue_S) (short jump).</summary> private void Brtrue(Label l) => _ilg!.Emit(OpCodes.Brtrue_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br_S) (short jump).</summary> private void Br(Label l) => _ilg!.Emit(OpCodes.Br_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble_S) (short jump).</summary> private void Ble(Label l) => _ilg!.Emit(OpCodes.Ble_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_S) (short jump).</summary> private void Blt(Label l) => _ilg!.Emit(OpCodes.Blt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_S) (short jump).</summary> private void Bge(Label l) => _ilg!.Emit(OpCodes.Bge_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un_S) (short jump).</summary> private void BgeUn(Label l) => _ilg!.Emit(OpCodes.Bge_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bgt_S) (short jump).</summary> private void Bgt(Label l) => _ilg!.Emit(OpCodes.Bgt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne_S) (short jump).</summary> private void Bne(Label l) => _ilg!.Emit(OpCodes.Bne_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq_S) (short jump).</summary> private void Beq(Label l) => _ilg!.Emit(OpCodes.Beq_S, l); /// <summary>A macro for the Ldlen instruction.</summary> private void Ldlen() => _ilg!.Emit(OpCodes.Ldlen); /// <summary>A macro for the Ldelem_I4 instruction.</summary> private void LdelemI4() => _ilg!.Emit(OpCodes.Ldelem_I4); /// <summary>A macro for the Stelem_I4 instruction.</summary> private void StelemI4() => _ilg!.Emit(OpCodes.Stelem_I4); private void Switch(Label[] table) => _ilg!.Emit(OpCodes.Switch, table); /// <summary>Declares a local bool.</summary> private LocalBuilder DeclareBool() => _ilg!.DeclareLocal(typeof(bool)); /// <summary>Declares a local int.</summary> private LocalBuilder DeclareInt32() => _ilg!.DeclareLocal(typeof(int)); /// <summary>Declares a local CultureInfo.</summary> private LocalBuilder? DeclareTextInfo() => _ilg!.DeclareLocal(typeof(TextInfo)); /// <summary>Declares a local string.</summary> private LocalBuilder DeclareString() => _ilg!.DeclareLocal(typeof(string)); private LocalBuilder DeclareReadOnlySpanChar() => _ilg!.DeclareLocal(typeof(ReadOnlySpan<char>)); /// <summary>Rents an Int32 local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentInt32Local() => new RentedLocalBuilder( _int32LocalsPool ??= new Stack<LocalBuilder>(), _int32LocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareInt32()); /// <summary>Rents a ReadOnlySpan(char) local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentReadOnlySpanCharLocal() => new RentedLocalBuilder( _readOnlySpanCharLocalsPool ??= new Stack<LocalBuilder>(1), // capacity == 1 as we currently don't expect overlapping instances _readOnlySpanCharLocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareReadOnlySpanChar()); /// <summary>Returned a rented local to the pool.</summary> private struct RentedLocalBuilder : IDisposable { private readonly Stack<LocalBuilder> _pool; private readonly LocalBuilder _local; internal RentedLocalBuilder(Stack<LocalBuilder> pool, LocalBuilder local) { _local = local; _pool = pool; } public static implicit operator LocalBuilder(RentedLocalBuilder local) => local._local; public void Dispose() { Debug.Assert(_pool != null); Debug.Assert(_local != null); Debug.Assert(!_pool.Contains(_local)); _pool.Push(_local); this = default; } } /// <summary>Sets the culture local to CultureInfo.CurrentCulture.</summary> private void InitLocalCultureInfo() { Debug.Assert(_textInfo != null); Call(s_cultureInfoGetCurrentCultureMethod); Callvirt(s_cultureInfoGetTextInfoMethod); Stloc(_textInfo); } /// <summary>Whether ToLower operations should be performed with the invariant culture as opposed to the one in <see cref="_textInfo"/>.</summary> private bool UseToLowerInvariant => _textInfo == null || (_options & RegexOptions.CultureInvariant) != 0; /// <summary>Invokes either char.ToLowerInvariant(c) or _textInfo.ToLower(c).</summary> private void CallToLower() { if (UseToLowerInvariant) { Call(s_charToLowerInvariantMethod); } else { using RentedLocalBuilder currentCharLocal = RentInt32Local(); Stloc(currentCharLocal); Ldloc(_textInfo!); Ldloc(currentCharLocal); Callvirt(s_textInfoToLowerMethod); } } /// <summary>Generates the implementation for TryFindNextPossibleStartingPosition.</summary> protected void EmitTryFindNextPossibleStartingPosition() { Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder pos = DeclareInt32(); bool rtl = (_options & RegexOptions.RightToLeft) != 0; _textInfo = null; if ((_options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = _regexTree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when _regexTree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } // Load necessary locals // int pos = base.runtextpos; // ReadOnlySpan<char> inputSpan = dynamicMethodArg; // TODO: We can reference the arg directly rather than using another local. Mvfldloc(s_runtextposField, pos); Ldarg_1(); Stloc(inputSpan); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = _regexTree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); Label returnFalse = DefineLabel(); Label finishedLengthCheck = DefineLabel(); // if (pos > inputSpan.Length - minRequiredLength) // or pos < minRequiredLength for rtl // { // base.runtextpos = inputSpan.Length; // or 0 for rtl // return false; // } Ldloc(pos); if (!rtl) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength > 0) { Ldc(minRequiredLength); Sub(); } Ble(finishedLengthCheck); } else { Ldc(minRequiredLength); Bge(finishedLengthCheck); } MarkLabel(returnFalse); Ldthis(); if (!rtl) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); } else { Ldc(0); } Stfld(s_runtextposField); Ldc(0); Ret(); MarkLabel(finishedLengthCheck); // Emit any anchors. if (EmitAnchors()) { return; } // Either anchors weren't specified, or they don't completely root all matches to a specific location. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_LeftToRight(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_RightToLeft(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: Debug.Assert(_regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_LeftToRight(); break; case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: Debug.Assert(_regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_RightToLeft(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {_regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: // return true; Ldc(1); Ret(); break; } // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool EmitAnchors() { Label label; // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: // if (pos != 0) goto returnFalse; // return true; Ldloc(pos); Ldc(0); Bne(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: // if (pos != base.runtextstart) goto returnFalse; // return true; Ldloc(pos); Ldthisfld(s_runtextstartField); Bne(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: // if (pos < inputSpan.Length - 1) base.runtextpos = inputSpan.Length - 1; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: // if (pos < inputSpan.Length) base.runtextpos = inputSpan.Length; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: // if (pos != 0) base.runtextpos = 0; // return true; label = DefineLabel(); Ldloc(pos); Ldc(0); Beq(label); Ldthis(); Ldc(0); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: // if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\n') goto returnFalse; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Blt(returnFalse); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUn(label); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); Bne(returnFalse); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: // if (pos < inputSpan.Length) goto returnFalse; // return true; Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Blt(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; } } // Now handle anchors that boost the position but don't determine immediate success or failure. if (!rtl) // we haven't done the work to validate these optimizations for RightToLeft { switch (_regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: { // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any prefix or char class searches. label = DefineLabel(); // if (pos > 0... Ldloc(pos!); Ldc(0); Ble(label); // ... && inputSpan[pos - 1] != '\n') { ... } Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); Beq(label); // int tmp = inputSpan.Slice(pos).IndexOf('\n'); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldc('\n'); Call(s_spanIndexOfChar); using (RentedLocalBuilder newlinePos = RentInt32Local()) { Stloc(newlinePos); // if (newlinePos < 0 || newlinePos + pos + 1 > inputSpan.Length) // { // base.runtextpos = inputSpan.Length; // return false; // } Ldloc(newlinePos); Ldc(0); Blt(returnFalse); Ldloc(newlinePos); Ldloc(pos); Add(); Ldc(1); Add(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bgt(returnFalse); // pos += newlinePos + 1; Ldloc(pos); Ldloc(newlinePos); Add(); Ldc(1); Add(); Stloc(pos); // We've updated the position. Make sure there's still enough room in the input for a possible match. // if (pos > inputSpan.Length - minRequiredLength) returnFalse; Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength != 0) { Ldc(minRequiredLength); Sub(); } Ldloc(pos); BltFar(returnFalse); } MarkLabel(label); } break; } switch (_regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End or RegexNodeKind.EndZ when _regexTree.FindOptimizations.MaxPossibleLength is int maxLength: // Jump to the end, minus the max allowed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Bge(label); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Stloc(pos); MarkLabel(label); break; } } } return false; } // Emits a case-sensitive prefix search for a string at the beginning of the pattern. void EmitIndexOf_LeftToRight(string prefix) { using RentedLocalBuilder i = RentInt32Local(); // int i = inputSpan.Slice(pos).IndexOf(prefix); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldstr(prefix); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); Stloc(i); // if (i < 0) goto ReturnFalse; Ldloc(i); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(i); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } // Emits a case-sensitive right-to-left prefix search for a string at the beginning of the pattern. void EmitIndexOf_RightToLeft(string prefix) { // pos = inputSpan.Slice(0, pos).LastIndexOf(prefix); Ldloca(inputSpan); Ldc(0); Ldloc(pos); Call(s_spanSliceIntIntMethod); Ldstr(prefix); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfSpan); Stloc(pos); // if (pos < 0) goto ReturnFalse; Ldloc(pos); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + prefix.Length; // return true; Ldthis(); Ldloc(pos); Ldc(prefix.Length); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } // Emits a search for a set at a fixed position from the start of the pattern, // and potentially other sets at other fixed positions in the pattern. void EmitFixedSet_LeftToRight() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = _regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); using RentedLocalBuilder iLocal = RentInt32Local(); using RentedLocalBuilder textSpanLocal = RentReadOnlySpanCharLocal(); // ReadOnlySpan<char> span = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(textSpanLocal); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; Label checkSpanLengthLabel = default; Label charNotInClassLabel = default; Label loopBody = default; if (needLoop) { checkSpanLengthLabel = DefineLabel(); charNotInClassLabel = DefineLabel(); loopBody = DefineLabel(); // for (int i = 0; Ldc(0); Stloc(iLocal); BrFar(checkSpanLengthLabel); MarkLabel(loopBody); } if (canUseIndexOf) { setIndex = 1; if (needLoop) { // slice.Slice(iLocal + primarySet.Distance); Ldloca(textSpanLocal); Ldloc(iLocal); if (primarySet.Distance != 0) { Ldc(primarySet.Distance); Add(); } Call(s_spanSliceIntMethod); } else if (primarySet.Distance != 0) { // slice.Slice(primarySet.Distance) Ldloca(textSpanLocal); Ldc(primarySet.Distance); Call(s_spanSliceIntMethod); } else { // slice Ldloc(textSpanLocal); } switch (primarySet.Chars!.Length) { case 1: // tmp = ...IndexOf(setChars[0]); Ldc(primarySet.Chars[0]); Call(s_spanIndexOfChar); break; case 2: // tmp = ...IndexOfAny(setChars[0], setChars[1]); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: // tmp = ...IndexOfAny(setChars[0], setChars[1], setChars[2]}); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Ldc(primarySet.Chars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(primarySet.Chars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } if (needLoop) { // i += tmp; // if (tmp < 0) goto returnFalse; using (RentedLocalBuilder tmp = RentInt32Local()) { Stloc(tmp); Ldloc(iLocal); Ldloc(tmp); Add(); Stloc(iLocal); Ldloc(tmp); Ldc(0); BltFar(returnFalse); } } else { // i = tmp; // if (i < 0) goto returnFalse; Stloc(iLocal); Ldloc(iLocal); Ldc(0); BltFar(returnFalse); } // if (i >= slice.Length - (minRequiredLength - 1)) goto returnFalse; if (sets.Count > 1) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); Ldc(minRequiredLength - 1); Sub(); Ldloc(iLocal); BleFar(returnFalse); } } // if (!CharInClass(slice[i], prefix[0], "...")) continue; // if (!CharInClass(slice[i + 1], prefix[1], "...")) continue; // if (!CharInClass(slice[i + 2], prefix[2], "...")) continue; // ... Debug.Assert(setIndex is 0 or 1); for ( ; setIndex < sets.Count; setIndex++) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Ldloc(iLocal); if (sets[setIndex].Distance != 0) { Ldc(sets[setIndex].Distance); Add(); } Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(sets[setIndex].Set, sets[setIndex].CaseInsensitive); BrfalseFar(charNotInClassLabel); } // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(iLocal); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); if (needLoop) { MarkLabel(charNotInClassLabel); // for (...; ...; i++) Ldloc(iLocal); Ldc(1); Add(); Stloc(iLocal); // for (...; i < span.Length - (minRequiredLength - 1); ...); MarkLabel(checkSpanLengthLabel); Ldloc(iLocal); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); if (setsToUse > 1 || primarySet.Distance != 0) { Ldc(minRequiredLength - 1); Sub(); } BltFar(loopBody); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } // Emits a right-to-left search for a set at a fixed position from the start of the pattern. // (Currently that position will always be a distance of 0, meaning the start of the pattern itself.) void EmitFixedSet_RightToLeft() { (char[]? Chars, string Set, int Distance, bool CaseInsensitive) set = _regexTree.FindOptimizations.FixedDistanceSets![0]; Debug.Assert(set.Distance == 0); if (set.Chars is { Length: 1 } && !set.CaseInsensitive) { // pos = inputSpan.Slice(0, pos).LastIndexOf(set.Chars[0]); Ldloca(inputSpan); Ldc(0); Ldloc(pos); Call(s_spanSliceIntIntMethod); Ldc(set.Chars[0]); Call(s_spanLastIndexOfChar); Stloc(pos); // if (pos < 0) goto returnFalse; Ldloc(pos); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + 1; // return true; Ldthis(); Ldloc(pos); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } else { Label condition = DefineLabel(); // while ((uint)--pos < (uint)inputSpan.Length) MarkLabel(condition); Ldloc(pos); Ldc(1); Sub(); Stloc(pos); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(returnFalse); // if (!MatchCharacterClass(inputSpan[i], set.Set, set.CaseInsensitive)) goto condition; Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(set.Set, set.CaseInsensitive); Brfalse(condition); // base.runtextpos = pos + 1; // return true; Ldthis(); Ldloc(pos); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = _regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); // while (true) Label loopBody = DefineLabel(); Label loopEnd = DefineLabel(); MarkLabel(loopBody); // ReadOnlySpan<char> slice = inputSpan.Slice(pos); using RentedLocalBuilder slice = RentReadOnlySpanCharLocal(); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); // Find the literal. If we can't find it, we're done searching. // int i = slice.IndexOf(literal); // if (i < 0) break; using RentedLocalBuilder i = RentInt32Local(); Ldloc(slice); if (target.Literal.String is string literalString) { Ldstr(literalString); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (target.Literal.Chars is not char[] literalChars) { Ldc(target.Literal.Char); Call(s_spanIndexOfChar); } else { switch (literalChars.Length) { case 2: Ldc(literalChars[0]); Ldc(literalChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literalChars[0]); Ldc(literalChars[1]); Ldc(literalChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(literalChars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } Stloc(i); Ldloc(i); Ldc(0); BltFar(loopEnd); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. // int prev = i; using RentedLocalBuilder prev = RentInt32Local(); Ldloc(i); Stloc(prev); // while ((uint)--prev < (uint)slice.Length) && MatchCharClass(slice[prev])); Label innerLoopBody = DefineLabel(); Label innerLoopEnd = DefineLabel(); MarkLabel(innerLoopBody); Ldloc(prev); Ldc(1); Sub(); Stloc(prev); Ldloc(prev); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(innerLoopEnd); Ldloca(slice); Ldloc(prev); Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(target.LoopNode.Str!, caseInsensitive: false); BrtrueFar(innerLoopBody); MarkLabel(innerLoopEnd); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. // if ((i - prev - 1) < target.LoopNode.M) // { // pos += i + 1; // continue; // } Label metMinimum = DefineLabel(); Ldloc(i); Ldloc(prev); Sub(); Ldc(1); Sub(); Ldc(target.LoopNode.M); Bge(metMinimum); Ldloc(pos); Ldloc(i); Add(); Ldc(1); Add(); Stloc(pos); BrFar(loopBody); MarkLabel(metMinimum); } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. // base.runtextpos = pos + prev + 1; // return true; Ldthis(); Ldloc(pos); Ldloc(prev); Add(); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); // } MarkLabel(loopEnd); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } /// <summary>Generates the implementation for TryMatchAtCurrentPosition.</summary> protected void EmitTryMatchAtCurrentPosition() { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); // Get the root Capture node of the tree. RegexNode node = _regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); // Skip the Capture node. We handle the implicit root capture specially. node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. // base.Capture(0, base.runtextpos, base.runtextpos + node.Str.Length); // base.runtextpos = base.runtextpos + node.Str.Length; // return true; int length = node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1; if ((node.Options & RegexOptions.RightToLeft) != 0) { length = -length; } Ldthis(); Dup(); Ldc(0); Ldthisfld(s_runtextposField); Dup(); Ldc(length); Add(); Call(s_captureMethod); Ldthisfld(s_runtextposField); Ldc(length); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); return; // The source generator special-cases RegexNode.Empty, for purposes of code learning rather than // performance. Since that's not applicable to RegexCompiler, that code isn't mirrored here. } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(_regexTree); // Initialize the main locals used throughout the implementation. LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder originalPos = DeclareInt32(); LocalBuilder pos = DeclareInt32(); LocalBuilder slice = DeclareReadOnlySpanChar(); Label doneLabel = DefineLabel(); Label originalDoneLabel = doneLabel; if (_hasTimeout) { _loopTimeoutCounter = DeclareInt32(); } // CultureInfo culture = CultureInfo.CurrentCulture; // only if the whole expression or any subportion is ignoring case, and we're not using invariant InitializeCultureForTryMatchAtCurrentPositionIfNecessary(analysis); // ReadOnlySpan<char> inputSpan = input; Ldarg_1(); Stloc(inputSpan); // int pos = base.runtextpos; // int originalpos = pos; Ldthisfld(s_runtextposField); Stloc(pos); Ldloc(pos); Stloc(originalPos); // int stackpos = 0; LocalBuilder stackpos = DeclareInt32(); Ldc(0); Stloc(stackpos); // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(); // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // pos += sliceStaticPos; // base.runtextpos = pos; // Capture(0, originalpos, pos); // return true; Ldthis(); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); Stloc(pos); Ldloc(pos); } Stfld(s_runtextposField); Ldthis(); Ldc(0); Ldloc(originalPos); Ldloc(pos); Call(s_captureMethod); Ldc(1); Ret(); // NOTE: The following is a difference from the source generator. The source generator emits: // UncaptureUntil(0); // return false; // at every location where the all-up match is known to fail. In contrast, the compiler currently // emits this uncapture/return code in one place and jumps to it upon match failure. The difference // stems primarily from the return-at-each-location pattern resulting in cleaner / easier to read // source code, which is not an issue for RegexCompiler emitting IL instead of C#. // If the graph contained captures, undo any remaining to handle failed matches. if (expressionHasCaptures) { // while (base.Crawlpos() != 0) base.Uncapture(); Label finalReturnLabel = DefineLabel(); Br(finalReturnLabel); MarkLabel(originalDoneLabel); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Brtrue(body); // Done: MarkLabel(finalReturnLabel); } else { // Done: MarkLabel(originalDoneLabel); } // return false; Ldc(0); Ret(); // Generated code successfully. return; static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan() { // slice = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); } // Emits the sum of a constant and a value from a local. void EmitSum(int constant, LocalBuilder? local) { if (local == null) { Ldc(constant); } else if (constant == 0) { Ldloc(local); } else { Ldloc(local); Ldc(constant); Add(); } } // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, LocalBuilder? dynamicRequiredLength = null) { // if ((uint)(sliceStaticPos + requiredLength + dynamicRequiredLength - 1) >= (uint)slice.Length) goto Done; Debug.Assert(requiredLength > 0); EmitSum(sliceStaticPos + requiredLength - 1, dynamicRequiredLength); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); } // Emits code to get ref slice[sliceStaticPos] void EmitTextSpanOffset() { Ldloc(slice); Call(s_memoryMarshalGetReference); if (sliceStaticPos > 0) { Ldc(sliceStaticPos * sizeof(char)); Add(); } } // Adds the value of sliceStaticPos into the pos local, zeros out sliceStaticPos, // and resets slice to be inputSpan.Slice(pos). void TransferSliceStaticPosToPos(bool forceSliceReload = false) { if (sliceStaticPos > 0) { // pos += sliceStaticPos; // sliceStaticPos = 0; Ldloc(pos); Ldc(sliceStaticPos); Add(); Stloc(pos); sliceStaticPos = 0; // slice = inputSpan.Slice(pos); SliceInputSpan(); } else if (forceSliceReload) { // slice = inputSpan.Slice(pos); SliceInputSpan(); } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); Label originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // Label to jump to when any branch completes successfully. Label matchLabel = DefineLabel(); // Save off pos. We'll need to reset this each time a branch fails. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. LocalBuilder? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { // startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new Label[childCount]; Label backtrackLabel = DefineLabel(); for (int i = 0; i < childCount; i++) { bool isLastBranch = i == childCount - 1; Label nextBranch = default; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = DefineLabel(); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { // if (stackpos + 3 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = i; // base.runstack[stackpos++] = startingCapturePos; // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldc(i)); if (startingCapturePos is not null) { EmitStackPush(() => Ldloc(startingCapturePos)); } EmitStackPush(() => Ldloc(startingPos)); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. // pos += sliceStaticPos; // sliceStaticPos = 0; // goto matchLabel; TransferSliceStaticPosToPos(); BrFar(matchLabel); // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { // NextBranch: // pos = startingPos; // slice = inputSpan.Slice(pos); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); MarkLabel(nextBranch); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel); // startingPos = base.runstack[--stackpos]; // startingCapturePos = base.runstack[--stackpos]; // switch (base.runstack[--stackpos]) { ... } // branch number EmitStackPop(); Stloc(startingPos); if (startingCapturePos is not null) { EmitStackPop(); Stloc(startingCapturePos); } EmitStackPop(); Switch(labelMap); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; TransferSliceStaticPosToPos(); Label backreferenceEnd = DefineLabel(); // if (!base.IsMatched(capnum)) goto (ecmascript ? end : doneLabel); Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar((node.Options & RegexOptions.ECMAScript) == 0 ? doneLabel : backreferenceEnd); using RentedLocalBuilder matchLength = RentInt32Local(); using RentedLocalBuilder matchIndex = RentInt32Local(); using RentedLocalBuilder i = RentInt32Local(); // int matchLength = base.MatchLength(capnum); Ldthis(); Ldc(capnum); Call(s_matchLengthMethod); Stloc(matchLength); if (!rtl) { // if (slice.Length < matchLength) goto doneLabel; Ldloca(slice); Call(s_spanGetLengthMethod); } else { // if (pos < matchLength) goto doneLabel; Ldloc(pos); } Ldloc(matchLength); BltFar(doneLabel); // int matchIndex = base.MatchIndex(capnum); Ldthis(); Ldc(capnum); Call(s_matchIndexMethod); Stloc(matchIndex); Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) Ldc(0); Stloc(i); Br(condition); MarkLabel(body); // if (inputSpan[matchIndex + i] != slice[i]) goto doneLabel; // for rtl, instead of slice[i] using inputSpan[pos - matchLength + i] Ldloca(inputSpan); Ldloc(matchIndex); Ldloc(i); Add(); Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } if (!rtl) { Ldloca(slice); Ldloc(i); } else { Ldloca(inputSpan); Ldloc(pos); Ldloc(matchLength); Sub(); Ldloc(i); Add(); } Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } BneFar(doneLabel); // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < matchLength; ...) MarkLabel(condition); Ldloc(i); Ldloc(matchLength); Blt(body); // pos += matchLength; // or -= for rtl Ldloc(pos); Ldloc(matchLength); if (!rtl) { Add(); } else { Sub(); } Stloc(pos); if (!rtl) { SliceInputSpan(); } MarkLabel(backreferenceEnd); } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label refNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder resumeAt = DeclareInt32(); // if (!base.IsMatched(capnum)) goto refNotMatched; Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar(refNotMatched); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { // goto endConditional; BrFar(endConditional); } MarkLabel(refNotMatched); Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt); } } if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // We're atomic by our parent, so even if either child branch has backtracking constructs, // we don't need to emit any backtracking logic in support, as nothing will backtrack in. // Instead, we just ensure we revert back to the original done label so that any backtracking // skips over this node. doneLabel = originalDoneLabel; if (needsEndConditional) { MarkLabel(endConditional); } } else { // Subsequent expressions might try to backtrack to here, so output a backtracking map based on resumeAt. // Skip the backtracking section // goto endConditional; Debug.Assert(needsEndConditional); Br(endConditional); // Backtrack section Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. // resumeAt = base.runstack[--stackpos]; EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postIfDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto originalDoneLabel; BrFar(originalDoneLabel); if (needsEndConditional) { MarkLabel(endConditional); } // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt)); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookaround. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label expressionNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder? resumeAt = null; if (!isAtomic) { resumeAt = DeclareInt32(); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. LocalBuilder? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { // int startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookaround; however, a positive lookaround only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. EmitNode(condition); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt!); } // goto endConditional; BrFar(endConditional); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. // pos = startingPos; MarkLabel(expressionNotMatched); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt!); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt!); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // EndConditional: doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { Debug.Assert(resumeAt is not null); // Skip the backtracking section. BrFar(endConditional); Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // resumeAt = StackPop(); EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postYesDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto postConditionalDoneLabel; BrFar(originalDoneLabel); // EndConditional: MarkLabel(endConditional); // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt!)); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, _regexTree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); // startingPos = pos; TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); RegexNode child = node.Child(0); if (uncapnum != -1) { // if (!IsMatched(uncapnum)) goto doneLabel; Ldthis(); Ldc(uncapnum); Call(s_isMatchedMethod); BrfalseFar(doneLabel); } // Emit child node. Label originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); TransferSliceStaticPosToPos(); if (uncapnum == -1) { // Capture(capnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldloc(startingPos); Ldloc(pos); Call(s_captureMethod); } else { // TransferCapture(capnum, uncapnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldc(uncapnum); Ldloc(startingPos); Ldloc(pos); Call(s_transferCaptureMethod); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(startingPos)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); Br(backtrackingEnd); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); EmitStackPop(); Stloc(startingPos); if (!childBacktracks) { // pos = startingPos Ldloc(startingPos); Stloc(pos); SliceInputSpan(); } // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(LocalBuilder startingCapturePos) { Debug.Assert(startingCapturePos != null); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Ldloc(startingCapturePos); Bgt(body); } // Emits the code to handle a positive lookaround assertion. This is a positive lookahead // for left-to-right and a positive lookbehind for right-to-left. void EmitPositiveLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; } // Emits the code to handle a negative lookaround assertion. This is a negative lookahead // for left-to-right and a negative lookbehind for right-to-left. void EmitNegativeLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } Label originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; Label negativeLookaheadDoneLabel = DefineLabel(); doneLabel = negativeLookaheadDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookaround, which actually // means failure for a _negative_ lookaround, so we need to jump to the original done. // goto originalDoneLabel; BrFar(originalDoneLabel); // Failures (success for a negative lookaround) jump here. MarkLabel(negativeLookaheadDoneLabel); if (doneLabel == negativeLookaheadDoneLabel) { doneLabel = originalDoneLabel; } // After the child completes in failure (success for negative lookaround), reset the text positions. // pos = startingPos; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } // RightToLeft doesn't take advantage of static positions. While RightToLeft won't update static // positions, a previous operation may have left us with a non-zero one. Make sure it's zero'd out // such that pos and slice are up-to-date. Note that RightToLeft also shouldn't use the slice span, // as it's not kept up-to-date; any RightToLeft implementation that wants to use it must first update // it from pos. if ((node.Options & RegexOptions.RightToLeft) != 0) { TransferSliceStaticPosToPos(); } switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); break; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); break; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node); break; case RegexNodeKind.Loop: EmitLoop(node); break; case RegexNodeKind.Lazyloop: EmitLazy(node); break; case RegexNodeKind.Alternate: EmitAlternation(node); break; case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Atomic: EmitAtomic(node, subsequent); break; case RegexNodeKind.Backreference: EmitBackreference(node); break; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); break; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); break; case RegexNodeKind.Capture: EmitCapture(node, subsequent); break; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaroundAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaroundAssertion(node); break; case RegexNodeKind.Nothing: BrFar(doneLabel); break; case RegexNodeKind.Empty: // Emit nothing. break; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); RegexNode child = node.Child(0); if (!analysis.MayBacktrack(child)) { // If the child has no backtracking, the atomic is a nop and we can just skip it. // Note that the source generator equivalent for this is in the top-level EmitNode, in order to avoid // outputting some extra comments and scopes. As such formatting isn't a concern for the compiler, // the logic is instead here in EmitAtomic. EmitNode(child, subsequent); return; } // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. Label originalDoneLabel = doneLabel; // int startingStackpos = stackpos; using RentedLocalBuilder startingStackpos = RentInt32Local(); Ldloc(stackpos); Stloc(startingStackpos); // Emit the child. EmitNode(child, subsequent); // Reset the stack position and done label. // stackpos = startingStackpos; Ldloc(startingStackpos); Stloc(stackpos); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); // if (base.runtextpos < pos) // { // base.runtextpos = pos; // } TransferSliceStaticPosToPos(); Ldthisfld(s_runtextposField); Ldloc(pos); Label skipUpdate = DefineLabel(); Bge(skipUpdate); Ldthis(); Ldloc(pos); Stfld(s_runtextposField); MarkLabel(skipUpdate); } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // Emit the code for each child one after the other. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. if (!rtl && emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { EmitSpanLengthCheck(requiredLength); for (; i < exclusiveEnd; i++) { EmitNode(node.Child(i), GetSubsequent(i, node, subsequent), emitLengthChecksIfRequired: false); } i--; continue; } EmitNode(node.Child(i), GetSubsequent(i, node, subsequent)); } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequent(int index, RegexNode node, RegexNode? subsequent) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return subsequent; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, LocalBuilder? offset = null) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Debug.Assert(!rtl || offset is null); if (emitLengthCheck) { if (!rtl) { // if ((uint)(sliceStaticPos + offset) >= slice.Length) goto Done; EmitSpanLengthCheck(1, offset); } else { // if ((uint)(pos - 1) >= inputSpan.Length) goto Done; Ldloc(pos); Ldc(1); Sub(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); } } if (!rtl) { // slice[staticPos + offset] Ldloca(slice); EmitSum(sliceStaticPos, offset); } else { // inputSpan[pos - 1] Ldloca(inputSpan); EmitSum(-1, pos); } Call(s_spanGetItemMethod); LdindU2(); // if (loadedChar != ch) goto doneLabel; if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(doneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(doneLabel); } else // IsNotoneFamily { BeqFar(doneLabel); } } if (!rtl) { sliceStaticPos++; } else { // pos--; Ldloc(pos); Ldc(1); Sub(); Stloc(pos); } } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); if ((node.Options & RegexOptions.RightToLeft) != 0) { // RightToLeft doesn't use static position. This ensures it's 0. TransferSliceStaticPosToPos(); } // if (!IsBoundary(inputSpan, pos + sliceStaticPos)) goto doneLabel; Ldthis(); Ldloc(inputSpan); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); } switch (node.Kind) { case RegexNodeKind.Boundary: Call(s_isBoundaryMethod); BrfalseFar(doneLabel); break; case RegexNodeKind.NonBoundary: Call(s_isBoundaryMethod); BrtrueFar(doneLabel); break; case RegexNodeKind.ECMABoundary: Call(s_isECMABoundaryMethod); BrfalseFar(doneLabel); break; default: Debug.Assert(node.Kind == RegexNodeKind.NonECMABoundary); Call(s_isECMABoundaryMethod); BrtrueFar(doneLabel); break; } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert((node.Options & RegexOptions.RightToLeft) == 0 || sliceStaticPos == 0); Debug.Assert(sliceStaticPos >= 0); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. BrFar(doneLabel); } else { // if (pos > 0/start) goto doneLabel; Ldloc(pos); if (node.Kind == RegexNodeKind.Beginning) { Ldc(0); } else { Ldthisfld(s_runtextstartField); } BneFar(doneLabel); } break; case RegexNodeKind.Bol: if (sliceStaticPos > 0) { // if (slice[sliceStaticPos - 1] != '\n') goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos - 1); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); } else { // We can't use our slice in this case, because we'd need to access slice[-1], so we access the inputSpan directly: // if (pos > 0 && inputSpan[pos - 1] != '\n') goto doneLabel; Label success = DefineLabel(); Ldloc(pos); Ldc(0); Ble(success); Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; case RegexNodeKind.End: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); } else { // if (pos < inputSpan.Length) goto doneLabel; Ldloc(pos); Ldloca(inputSpan); } Call(s_spanGetLengthMethod); BltUnFar(doneLabel); break; case RegexNodeKind.EndZ: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length - 1) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); } else { // if (pos < inputSpan.Length - 1) goto doneLabel Ldloc(pos); Ldloca(inputSpan); } Call(s_spanGetLengthMethod); Ldc(1); Sub(); BltFar(doneLabel); goto case RegexNodeKind.Eol; case RegexNodeKind.Eol: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length && slice[sliceStaticPos] != '\n') goto doneLabel; Label success = DefineLabel(); Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(success); Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } else { // if ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\n') goto doneLabel; Label success = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUn(success); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); EmitMultiCharString(node.Str!, IsCaseInsensitive(node), emitLengthCheck, (node.Options & RegexOptions.RightToLeft) != 0); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck, bool rightToLeft) { Debug.Assert(str.Length >= 2); if (rightToLeft) { Debug.Assert(emitLengthCheck); TransferSliceStaticPosToPos(); // if ((uint)(pos - str.Length) >= inputSpan.Length) goto doneLabel; Ldloc(pos); Ldc(str.Length); Sub(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); for (int i = str.Length - 1; i >= 0; i--) { // if (inputSpan[--pos] != str[str.Length - 1 - i]) goto doneLabel Ldloc(pos); Ldc(1); Sub(); Stloc(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); if (caseInsensitive) { CallToLower(); } Ldc(str[i]); BneFar(doneLabel); } return; } if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } foreach (char c in str) { // if (c != slice[sliceStaticPos++]) goto doneLabel; EmitTextSpanOffset(); sliceStaticPos++; LdindU2(); CallToLower(); Ldc(c); BneFar(doneLabel); } } else { // if (!slice.Slice(sliceStaticPos).StartsWith("...") goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); Ldstr(str); Call(s_stringAsSpanMethod); Call(s_spanStartsWith); BrfalseFar(doneLabel); sliceStaticPos += str.Length; } } // Emits the code to handle a backtracking, single-character loop. void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); Label backtrackingLabel = DefineLabel(); Label endLoop = DefineLabel(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder endingPos = DeclareInt32(); LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) // int startingPos = pos; Ldloc(pos); Stloc(startingPos); EmitSingleCharAtomicLoop(node); // int endingPos = pos; TransferSliceStaticPosToPos(); Ldloc(pos); Stloc(endingPos); // int capturepos = base.Crawlpos(); if (capturepos is not null) { Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } // startingPos += node.M; // or -= for rtl if (node.M > 0) { Ldloc(startingPos); Ldc(!rtl ? node.M : -node.M); Add(); Stloc(startingPos); } // goto endLoop; BrFar(endLoop); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel); if (capturepos is not null) { // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(capturepos); EmitUncaptureUntil(capturepos); } // endingPos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(endingPos); EmitStackPop(); Stloc(startingPos); // if (startingPos >= endingPos) goto doneLabel; // or <= for rtl Ldloc(startingPos); Ldloc(endingPos); if (!rtl) { BgeFar(doneLabel); } else { BleFar(doneLabel); } if (!rtl && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { // endingPos = inputSpan.Slice(startingPos, Math.Min(inputSpan.Length, endingPos + literal.Length - 1) - startingPos).LastIndexOf(literal); // if (endingPos < 0) // { // goto doneLabel; // } Ldloca(inputSpan); Ldloc(startingPos); if (literal.Item2 is not null) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(endingPos); Ldc(literal.Item2.Length - 1); Add(); Call(s_mathMinIntInt); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); Ldstr(literal.Item2); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfSpan); } else { Ldloc(endingPos); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanLastIndexOfAnyCharChar); break; case 3: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Ldc(literal.Item3[2]); Call(s_spanLastIndexOfAnyCharCharChar); break; default: Ldstr(literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfAnySpan); break; } } else { Ldc(literal.Item1); Call(s_spanLastIndexOfChar); } } Stloc(endingPos); Ldloc(endingPos); Ldc(0); BltFar(doneLabel); // endingPos += startingPos; Ldloc(endingPos); Ldloc(startingPos); Add(); Stloc(endingPos); } else { // endingPos--; // or ++ for rtl Ldloc(endingPos); Ldc(!rtl ? 1 : -1); Sub(); Stloc(endingPos); } // pos = endingPos; Ldloc(endingPos); Stloc(pos); if (!rtl) { // slice = inputSpan.Slice(pos); SliceInputSpan(); } MarkLabel(endLoop); EmitStackResizeIfNeeded(expressionHasCaptures ? 3 : 2); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(endingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos!)); } doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } Debug.Assert(node.M < node.N); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. LocalBuilder? iterationCount = null; int? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = node.N - node.M; // int iterationCount = 0; iterationCount = DeclareInt32(); Ldc(0); Stloc(iterationCount); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. // int startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. // goto endLoopLabel; Label endLoopLabel = DefineLabel(); BrFar(endLoopLabel); // Backtracking section. Subsequent failures will jump to here. Label backtrackingLabel = DefineLabel(); MarkLabel(backtrackingLabel); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturepos is not null) { // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitUncaptureUntil(capturepos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { // if (iterationCount >= maxIterations) goto doneLabel; Ldloc(iterationCount!); Ldc(maxIterations.Value); BgeFar(doneLabel); // iterationCount++; Ldloc(iterationCount!); Ldc(1); Add(); Stloc(iterationCount!); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. // pos = startingPos; // Match single char; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if (!rtl && iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). // startingPos = slice.IndexOfAny(node.Ch, literal); Ldloc(slice); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(node.Ch); Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(node.Ch + literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(node.Ch); Ldc(literal.Item2?[0] ?? literal.Item1); Call(s_spanIndexOfAnyCharChar); } Stloc(startingPos); // if ((uint)startingPos >= (uint)slice.Length) goto doneLabel; Ldloc(startingPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); // if (slice[startingPos] == node.Ch) goto doneLabel; Ldloca(slice); Ldloc(startingPos); Call(s_spanGetItemMethod); LdindU2(); Ldc(node.Ch); BeqFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } else if (!rtl && iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. // startingPos = slice.IndexOf(literal); Ldloc(slice); if (literal2.Item2 is not null) { Ldstr(literal2.Item2); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (literal2.Item3 is not null) { switch (literal2.Item3.Length) { case 2: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Ldc(literal2.Item3[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(literal2.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(literal2.Item1); Call(s_spanIndexOfChar); } Stloc(startingPos); // if (startingPos < 0) goto doneLabel; Ldloc(startingPos); Ldc(0); BltFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } // Store the position we've left off at in case we need to iterate again. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. Label originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes MarkLabel(endLoopLabel); if (capturepos is not null) { // capturepos = base.CrawlPos(); Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } if (node.IsInLoop()) { // Store the loop's state // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = capturepos; // base.runstack[stackpos++] = iterationCount; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos)); } if (iterationCount is not null) { EmitStackPush(() => Ldloc(iterationCount)); } // Skip past the backtracking section Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; if (iterationCount is not null) { EmitStackPop(); Stloc(iterationCount); } if (capturepos is not null) { EmitStackPop(); Stloc(capturepos); } EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; Label originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); LocalBuilder sawEmpty = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = pos; // sawEmpty = 0; // false Ldc(0); Stloc(iterationCount); Ldloc(pos); Stloc(startingPos); Ldc(0); Stloc(sawEmpty); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { // goto endLoop; BrFar(endLoop); } // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. // base.runstack[stackpos++] = base.Crawlpos(); // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = pos; // base.runstack[stackpos++] = sawEmpty; EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); EmitStackPush(() => Ldloc(sawEmpty)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { // if (iterationCount < minIterations) goto body; Ldloc(iterationCount); Ldc(minIterations); BltFar(body); } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. // if (pos == startingPos) sawEmpty = 1; // true Label skipSawEmptySet = DefineLabel(); Ldloc(pos); Ldloc(startingPos); Bne(skipSawEmptySet); Ldc(1); Stloc(sawEmpty); MarkLabel(skipSawEmptySet); // We matched the next iteration. Jump to the subsequent code. // goto endLoop; BrFar(endLoop); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // sawEmpty = base.runstack[--stackpos]; // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (doneLabel == originalDoneLabel) { // goto originalDoneLabel; BrFar(originalDoneLabel); } else { // if (iterationCount == 0) goto originalDoneLabel; // goto doneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); BrFar(doneLabel); } MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); EmitStackPush(() => Ldloc(sawEmpty)); Label skipBacktrack = DefineLabel(); BrFar(skipBacktrack); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // sawEmpty = base.runstack[--stackpos]; // iterationCount = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); if (maxIterations == int.MaxValue) { // if (sawEmpty != 0) goto doneLabel; Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } else { // if (iterationCount >= maxIterations || sawEmpty != 0) goto doneLabel; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(doneLabel); Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } // goto body; BrFar(body); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthChecksIfRequired); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthChecksIfRequired, rtl); return; } if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position with rtl Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // for (int i = 0; ...) using RentedLocalBuilder iterationLocal = RentInt32Local(); Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // TimeoutCheck(); // HandleSingleChar(); MarkLabel(bodyLabel); EmitTimeoutCheck(); EmitSingleChar(node); // for (...; ...; i++) Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // for (...; i < iterations; ...) MarkLabel(conditionLabel); Ldloc(iterationLocal); Ldc(iterations); BltFar(bodyLabel); return; } // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthChecksIfRequired) { EmitSpanLengthCheck(iterations); } // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; if (iterations <= MaxUnrollSize) { // if (slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // goto doneLabel; for (int i = 0; i < iterations; i++) { EmitSingleChar(node, emitLengthCheck: false); } } else { // ReadOnlySpan<char> tmp = slice.Slice(sliceStaticPos, iterations); // for (int i = 0; i < tmp.Length; i++) // { // TimeoutCheck(); // if (tmp[i] != ch) goto Done; // } // sliceStaticPos += iterations; Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); using RentedLocalBuilder spanLocal = RentReadOnlySpanCharLocal(); Ldloca(slice); Ldc(sliceStaticPos); Ldc(iterations); Call(s_spanSliceIntIntMethod); Stloc(spanLocal); using RentedLocalBuilder iterationLocal = RentInt32Local(); Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); MarkLabel(bodyLabel); EmitTimeoutCheck(); LocalBuilder tmpTextSpanLocal = slice; // we want EmitSingleChar to refer to this temporary int tmpTextSpanPos = sliceStaticPos; slice = spanLocal; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: iterationLocal); slice = tmpTextSpanLocal; sliceStaticPos = tmpTextSpanPos; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); MarkLabel(conditionLabel); Ldloc(iterationLocal); Ldloca(spanLocal); Call(s_spanGetLengthMethod); BltFar(bodyLabel); sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; using RentedLocalBuilder iterationLocal = RentInt32Local(); Label atomicLoopDoneLabel = DefineLabel(); Span<char> setChars = stackalloc char[5]; // max optimized by IndexOfAny today int numSetChars = 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position for rtl Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // int i = 0; Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // Body: // TimeoutCheck(); MarkLabel(bodyLabel); EmitTimeoutCheck(); // if (pos <= iterationLocal) goto atomicLoopDoneLabel; Ldloc(pos); Ldloc(iterationLocal); BleFar(atomicLoopDoneLabel); // if (inputSpan[pos - i - 1] != ch) goto atomicLoopDoneLabel; Ldloca(inputSpan); Ldloc(pos); Ldloc(iterationLocal); Sub(); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(atomicLoopDoneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(atomicLoopDoneLabel); } else // IsNotoneFamily { BeqFar(atomicLoopDoneLabel); } } // i++; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // if (i >= maxIterations) goto atomicLoopDoneLabel; MarkLabel(conditionLabel); if (maxIterations != int.MaxValue) { Ldloc(iterationLocal); Ldc(maxIterations); BltFar(bodyLabel); } else { BrFar(bodyLabel); } } else if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. // int i = slice.Slice(sliceStaticPos).IndexOf(char); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } Ldc(node.Ch); Call(s_spanIndexOfChar); Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it would // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); // int i = slice.Slice(sliceStaticPos).IndexOfAny(ch1, ch2, ...); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } switch (numSetChars) { case 2: Ldc(setChars[0]); Ldc(setChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(setChars[0]); Ldc(setChars[1]); Ldc(setChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(setChars.Slice(0, numSetChars).ToString()); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); break; } Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. // int i = inputSpan.Length - pos; TransferSliceStaticPosToPos(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(pos); Sub(); Stloc(iterationLocal); } else { // For everything else, do a normal loop. // Transfer sliceStaticPos to pos to help with bounds check elimination on the loop. TransferSliceStaticPosToPos(); Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // int i = 0; Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // Body: // TimeoutCheck(); MarkLabel(bodyLabel); EmitTimeoutCheck(); // if ((uint)i >= (uint)slice.Length) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(atomicLoopDoneLabel); // if (slice[i] != ch) goto atomicLoopDoneLabel; Ldloca(slice); Ldloc(iterationLocal); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(atomicLoopDoneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(atomicLoopDoneLabel); } else // IsNotoneFamily { BeqFar(atomicLoopDoneLabel); } } // i++; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // if (i >= maxIterations) goto atomicLoopDoneLabel; MarkLabel(conditionLabel); if (maxIterations != int.MaxValue) { Ldloc(iterationLocal); Ldc(maxIterations); BltFar(bodyLabel); } else { BrFar(bodyLabel); } } // Done: MarkLabel(atomicLoopDoneLabel); // Check to ensure we've found at least min iterations. if (minIterations > 0) { Ldloc(iterationLocal); Ldc(minIterations); BltFar(doneLabel); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. if (!rtl) { // slice = slice.Slice(i); Ldloca(slice); Ldloc(iterationLocal); Call(s_spanSliceIntMethod); Stloc(slice); // pos += i; Ldloc(pos); Ldloc(iterationLocal); Add(); Stloc(pos); } else { // pos -= i; Ldloc(pos); Ldloc(iterationLocal); Sub(); Stloc(pos); } } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static pos for rtl } Label skipUpdatesLabel = DefineLabel(); if (!rtl) { // if ((uint)sliceStaticPos >= (uint)slice.Length) goto skipUpdatesLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(skipUpdatesLabel); } else { // if (pos == 0) goto skipUpdatesLabel; Ldloc(pos); Ldc(0); BeqFar(skipUpdatesLabel); } if (!rtl) { // if (slice[sliceStaticPos] != ch) goto skipUpdatesLabel; Ldloca(slice); Ldc(sliceStaticPos); } else { // if (inputSpan[pos - 1] != ch) goto skipUpdatesLabel; Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); } Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(skipUpdatesLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(skipUpdatesLabel); } else // IsNotoneFamily { BeqFar(skipUpdatesLabel); } } if (!rtl) { // slice = slice.Slice(1); Ldloca(slice); Ldc(1); Call(s_spanSliceIntMethod); Stloc(slice); // pos++; Ldloc(pos); Ldc(1); Add(); Stloc(pos); } else { // pos--; Ldloc(pos); Ldc(1); Sub(); Stloc(pos); } MarkLabel(skipUpdatesLabel); } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) using RentedLocalBuilder i = RentInt32Local(); Ldc(0); Stloc(i); BrFar(condition); MarkLabel(body); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < node.M; ...) MarkLabel(condition); Ldloc(i); Ldc(node.M); BltFar(body); } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); Label originalDoneLabel = doneLabel; LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = 0; Ldc(0); Stloc(iterationCount); Ldc(0); Stloc(startingPos); // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { // base.runstack[stackpos++] = base.Crawlpos(); EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. Otherwise, // we've matched as many iterations as we can with this configuration. Jump to what comes after the loop. switch ((minIterations > 0, maxIterations == int.MaxValue)) { case (true, true): // if (pos != startingPos || iterationCount < minIterations) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (true, false): // if ((pos != startingPos || iterationCount < minIterations) && iterationCount < maxIterations) goto body; // goto endLoop; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (false, true): // if (pos != startingPos) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); BrFar(endLoop); break; case (false, false): // if (pos == startingPos || iterationCount >= maxIterations) goto endLoop; // goto body; Ldloc(pos); Ldloc(startingPos); BeqFar(endLoop); Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); BrFar(body); break; } // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { // int poppedCrawlPos = base.runstack[--stackpos]; // while (base.Crawlpos() > poppedCrawlPos) base.Uncapture(); using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (minIterations > 0) { // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // if (iterationCount < minIterations) goto doneLabel/originalDoneLabel; Ldloc(iterationCount); Ldc(minIterations); BltFar(childBacktracks ? doneLabel : originalDoneLabel); } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { // goto endLoop; BrFar(endLoop); // Backtrack: Label backtrack = DefineLabel(); MarkLabel(backtrack); // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { // Store the loop's state EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--runstack]; // startingPos = base.runstack[--runstack]; EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } } void EmitStackResizeIfNeeded(int count) { Debug.Assert(count >= 1); // if (stackpos >= base.runstack!.Length - (count - 1)) // { // Array.Resize(ref base.runstack, base.runstack.Length * 2); // } Label skipResize = DefineLabel(); Ldloc(stackpos); Ldthisfld(s_runstackField); Ldlen(); if (count > 1) { Ldc(count - 1); Sub(); } Blt(skipResize); Ldthis(); _ilg!.Emit(OpCodes.Ldflda, s_runstackField); Ldthisfld(s_runstackField); Ldlen(); Ldc(2); Mul(); Call(s_arrayResize); MarkLabel(skipResize); } void EmitStackPush(Action load) { // base.runstack[stackpos] = load(); Ldthisfld(s_runstackField); Ldloc(stackpos); load(); StelemI4(); // stackpos++; Ldloc(stackpos); Ldc(1); Add(); Stloc(stackpos); } void EmitStackPop() { // ... = base.runstack[--stackpos]; Ldthisfld(s_runstackField); Ldloc(stackpos); Ldc(1); Sub(); Stloc(stackpos); Ldloc(stackpos); LdelemI4(); } } protected void EmitScan(RegexOptions options, DynamicMethod tryFindNextStartingPositionMethod, DynamicMethod tryMatchAtCurrentPositionMethod) { bool rtl = (options & RegexOptions.RightToLeft) != 0; Label returnLabel = DefineLabel(); // while (TryFindNextPossibleStartingPosition(text)) Label whileLoopBody = DefineLabel(); MarkLabel(whileLoopBody); Ldthis(); Ldarg_1(); Call(tryFindNextStartingPositionMethod); BrfalseFar(returnLabel); if (_hasTimeout) { // CheckTimeout(); Ldthis(); Call(s_checkTimeoutMethod); } // if (TryMatchAtCurrentPosition(text) || runtextpos == text.length) // or == 0 for rtl // return; Ldthis(); Ldarg_1(); Call(tryMatchAtCurrentPositionMethod); BrtrueFar(returnLabel); Ldthisfld(s_runtextposField); if (!rtl) { Ldarga_s(1); Call(s_spanGetLengthMethod); } else { Ldc(0); } Ceq(); BrtrueFar(returnLabel); // runtextpos += 1 // or -1 for rtl Ldthis(); Ldthisfld(s_runtextposField); Ldc(!rtl ? 1 : -1); Add(); Stfld(s_runtextposField); // End loop body. BrFar(whileLoopBody); // return; MarkLabel(returnLabel); Ret(); } private void InitializeCultureForTryMatchAtCurrentPositionIfNecessary(AnalysisResults analysis) { _textInfo = null; if (analysis.HasIgnoreCase && (_options & RegexOptions.CultureInvariant) == 0) { // cache CultureInfo in local variable which saves excessive thread local storage accesses _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } /// <summary>Emits a a check for whether the character is in the specified character class.</summary> /// <remarks>The character to be checked has already been loaded onto the stack.</remarks> private void EmitMatchCharacterClass(string charClass, bool caseInsensitive) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // true Pop(); Ldc(1); return; case RegexCharClass.DigitClass: // char.IsDigit(ch) Call(s_charIsDigitMethod); return; case RegexCharClass.NotDigitClass: // !char.IsDigit(ch) Call(s_charIsDigitMethod); Ldc(0); Ceq(); return; case RegexCharClass.SpaceClass: // char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); return; case RegexCharClass.NotSpaceClass: // !char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); Ldc(0); Ceq(); return; case RegexCharClass.WordClass: // RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); return; case RegexCharClass.NotWordClass: // !RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); Ldc(0); Ceq(); return; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant; if (!invariant) { CallToLower(); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { if (lowInclusive == highInclusive) { // ch == charClass[3] Ldc(lowInclusive); Ceq(); } else { // (uint)ch - lowInclusive < highInclusive - lowInclusive + 1 Ldc(lowInclusive); Sub(); Ldc(highInclusive - lowInclusive + 1); CltUn(); } // Negate the answer if the negation flag was set if (RegexCharClass.IsNegated(charClass)) { Ldc(0); Ceq(); } return; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { // char.GetUnicodeCategory(ch) == category Call(s_charGetUnicodeInfo); Ldc((int)category); Ceq(); if (negated) { Ldc(0); Ceq(); } return; } // All checks after this point require reading the input character multiple times, // so we store it into a temporary local. using RentedLocalBuilder tempLocal = RentInt32Local(); Stloc(tempLocal); // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it's cheaper and smaller to compare against each than it is to use a lookup table. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int numChars = RegexCharClass.GetSetChars(charClass, setChars); if (numChars is 2 or 3) { if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out int mask)) // special-case common case of an upper and lowercase ASCII letter combination { // ((ch | mask) == setChars[1]) Ldloc(tempLocal); Ldc(mask); Or(); Ldc(setChars[1] | mask); Ceq(); } else { // (ch == setChars[0]) | (ch == setChars[1]) Ldloc(tempLocal); Ldc(setChars[0]); Ceq(); Ldloc(tempLocal); Ldc(setChars[1]); Ceq(); Or(); } // | (ch == setChars[2]) if (numChars == 3) { Ldloc(tempLocal); Ldc(setChars[2]); Ceq(); Or(); } return; } } using RentedLocalBuilder resultLocal = RentInt32Local(); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); // Helper method that emits a call to RegexRunner.CharInClass(ch{.ToLowerInvariant()}, charClass) void EmitCharInClass() { Ldloc(tempLocal); if (invariant) { CallToLower(); } Ldstr(charClass); Call(s_charInClassMethod); Stloc(resultLocal); } Label doneLabel = DefineLabel(); Label comparisonLabel = DefineLabel(); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) // ch >= 128 && RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(0); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. // ch < 128 || RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(1); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = string.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. // ch < 128 ? (bitVectorString[ch >> 4] & (1 << (ch & 0xF))) != 0 : Ldloc(tempLocal); Ldc(128); Bge(comparisonLabel); Ldstr(bitVectorString); Ldloc(tempLocal); Ldc(4); Shr(); Call(s_stringGetCharsMethod); Ldc(1); Ldloc(tempLocal); Ldc(15); And(); Ldc(31); And(); Shl(); And(); Ldc(0); CgtUn(); Stloc(resultLocal); Br(doneLabel); MarkLabel(comparisonLabel); if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. Ldc(0); Stloc(resultLocal); } else if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. Ldc(1); Stloc(resultLocal); } else { // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. EmitCharInClass(); } MarkLabel(doneLabel); Ldloc(resultLocal); } /// <summary>Emits a timeout check.</summary> private void EmitTimeoutCheck() { if (!_hasTimeout) { return; } Debug.Assert(_loopTimeoutCounter != null); // Increment counter for each loop iteration. Ldloc(_loopTimeoutCounter); Ldc(1); Add(); Stloc(_loopTimeoutCounter); // Emit code to check the timeout every 2048th iteration. Label label = DefineLabel(); Ldloc(_loopTimeoutCounter); Ldc(LoopTimeoutCheckCount); RemUn(); Brtrue(label); Ldthis(); Call(s_checkTimeoutMethod); MarkLabel(label); } } }
// 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.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions { /// <summary> /// RegexCompiler translates a block of RegexCode to MSIL, and creates a subclass of the RegexRunner type. /// </summary> internal abstract class RegexCompiler { private static readonly FieldInfo s_runtextstartField = RegexRunnerField("runtextstart"); private static readonly FieldInfo s_runtextposField = RegexRunnerField("runtextpos"); private static readonly FieldInfo s_runstackField = RegexRunnerField("runstack"); private static readonly MethodInfo s_captureMethod = RegexRunnerMethod("Capture"); private static readonly MethodInfo s_transferCaptureMethod = RegexRunnerMethod("TransferCapture"); private static readonly MethodInfo s_uncaptureMethod = RegexRunnerMethod("Uncapture"); private static readonly MethodInfo s_isMatchedMethod = RegexRunnerMethod("IsMatched"); private static readonly MethodInfo s_matchLengthMethod = RegexRunnerMethod("MatchLength"); private static readonly MethodInfo s_matchIndexMethod = RegexRunnerMethod("MatchIndex"); private static readonly MethodInfo s_isBoundaryMethod = typeof(RegexRunner).GetMethod("IsBoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_isWordCharMethod = RegexRunnerMethod("IsWordChar"); private static readonly MethodInfo s_isECMABoundaryMethod = typeof(RegexRunner).GetMethod("IsECMABoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan<char>), typeof(int) })!; private static readonly MethodInfo s_crawlposMethod = RegexRunnerMethod("Crawlpos"); private static readonly MethodInfo s_charInClassMethod = RegexRunnerMethod("CharInClass"); private static readonly MethodInfo s_checkTimeoutMethod = RegexRunnerMethod("CheckTimeout"); private static readonly MethodInfo s_charIsDigitMethod = typeof(char).GetMethod("IsDigit", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charIsWhiteSpaceMethod = typeof(char).GetMethod("IsWhiteSpace", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charGetUnicodeInfo = typeof(char).GetMethod("GetUnicodeCategory", new Type[] { typeof(char) })!; private static readonly MethodInfo s_charToLowerInvariantMethod = typeof(char).GetMethod("ToLowerInvariant", new Type[] { typeof(char) })!; private static readonly MethodInfo s_cultureInfoGetCurrentCultureMethod = typeof(CultureInfo).GetMethod("get_CurrentCulture")!; private static readonly MethodInfo s_cultureInfoGetTextInfoMethod = typeof(CultureInfo).GetMethod("get_TextInfo")!; private static readonly MethodInfo s_spanGetItemMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Item", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanGetLengthMethod = typeof(ReadOnlySpan<char>).GetMethod("get_Length")!; private static readonly MethodInfo s_memoryMarshalGetReference = typeof(MemoryMarshal).GetMethod("GetReference", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfChar = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfSpan = typeof(MemoryExtensions).GetMethod("IndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfChar = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("LastIndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfSpan = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanSliceIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanSliceIntIntMethod = typeof(ReadOnlySpan<char>).GetMethod("Slice", new Type[] { typeof(int), typeof(int) })!; private static readonly MethodInfo s_spanStartsWith = typeof(MemoryExtensions).GetMethod("StartsWith", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_stringAsSpanMethod = typeof(MemoryExtensions).GetMethod("AsSpan", new Type[] { typeof(string) })!; private static readonly MethodInfo s_stringGetCharsMethod = typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) })!; private static readonly MethodInfo s_textInfoToLowerMethod = typeof(TextInfo).GetMethod("ToLower", new Type[] { typeof(char) })!; private static readonly MethodInfo s_arrayResize = typeof(Array).GetMethod("Resize")!.MakeGenericMethod(typeof(int)); private static readonly MethodInfo s_mathMinIntInt = typeof(Math).GetMethod("Min", new Type[] { typeof(int), typeof(int) })!; /// <summary>The ILGenerator currently in use.</summary> protected ILGenerator? _ilg; /// <summary>The options for the expression.</summary> protected RegexOptions _options; /// <summary>The <see cref="RegexTree"/> written for the expression.</summary> protected RegexTree? _regexTree; /// <summary>Whether this expression has a non-infinite timeout.</summary> protected bool _hasTimeout; /// <summary>Pool of Int32 LocalBuilders.</summary> private Stack<LocalBuilder>? _int32LocalsPool; /// <summary>Pool of ReadOnlySpan of char locals.</summary> private Stack<LocalBuilder>? _readOnlySpanCharLocalsPool; /// <summary>Local representing a cached TextInfo for the culture to use for all case-insensitive operations.</summary> private LocalBuilder? _textInfo; /// <summary>Local representing a timeout counter for loops (set loops and node loops).</summary> private LocalBuilder? _loopTimeoutCounter; /// <summary>A frequency with which the timeout should be validated.</summary> private const int LoopTimeoutCheckCount = 2048; private static FieldInfo RegexRunnerField(string fieldname) => typeof(RegexRunner).GetField(fieldname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; private static MethodInfo RegexRunnerMethod(string methname) => typeof(RegexRunner).GetMethod(methname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)!; /// <summary> /// Entry point to dynamically compile a regular expression. The expression is compiled to /// an in-memory assembly. /// </summary> internal static RegexRunnerFactory? Compile(string pattern, RegexTree regexTree, RegexOptions options, bool hasTimeout) => new RegexLWCGCompiler().FactoryInstanceFromCode(pattern, regexTree, options, hasTimeout); /// <summary>A macro for _ilg.DefineLabel</summary> private Label DefineLabel() => _ilg!.DefineLabel(); /// <summary>A macro for _ilg.MarkLabel</summary> private void MarkLabel(Label l) => _ilg!.MarkLabel(l); /// <summary>A macro for _ilg.Emit(Opcodes.Ldstr, str)</summary> protected void Ldstr(string str) => _ilg!.Emit(OpCodes.Ldstr, str); /// <summary>A macro for the various forms of Ldc.</summary> protected void Ldc(int i) => _ilg!.Emit(OpCodes.Ldc_I4, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ldc_I8).</summary> protected void LdcI8(long i) => _ilg!.Emit(OpCodes.Ldc_I8, i); /// <summary>A macro for _ilg.Emit(OpCodes.Ret).</summary> protected void Ret() => _ilg!.Emit(OpCodes.Ret); /// <summary>A macro for _ilg.Emit(OpCodes.Dup).</summary> protected void Dup() => _ilg!.Emit(OpCodes.Dup); /// <summary>A macro for _ilg.Emit(OpCodes.Rem_Un).</summary> private void RemUn() => _ilg!.Emit(OpCodes.Rem_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Ceq).</summary> private void Ceq() => _ilg!.Emit(OpCodes.Ceq); /// <summary>A macro for _ilg.Emit(OpCodes.Cgt_Un).</summary> private void CgtUn() => _ilg!.Emit(OpCodes.Cgt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Clt_Un).</summary> private void CltUn() => _ilg!.Emit(OpCodes.Clt_Un); /// <summary>A macro for _ilg.Emit(OpCodes.Pop).</summary> private void Pop() => _ilg!.Emit(OpCodes.Pop); /// <summary>A macro for _ilg.Emit(OpCodes.Add).</summary> private void Add() => _ilg!.Emit(OpCodes.Add); /// <summary>A macro for _ilg.Emit(OpCodes.Sub).</summary> private void Sub() => _ilg!.Emit(OpCodes.Sub); /// <summary>A macro for _ilg.Emit(OpCodes.Mul).</summary> private void Mul() => _ilg!.Emit(OpCodes.Mul); /// <summary>A macro for _ilg.Emit(OpCodes.And).</summary> private void And() => _ilg!.Emit(OpCodes.And); /// <summary>A macro for _ilg.Emit(OpCodes.Or).</summary> private void Or() => _ilg!.Emit(OpCodes.Or); /// <summary>A macro for _ilg.Emit(OpCodes.Shl).</summary> private void Shl() => _ilg!.Emit(OpCodes.Shl); /// <summary>A macro for _ilg.Emit(OpCodes.Shr).</summary> private void Shr() => _ilg!.Emit(OpCodes.Shr); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldloca).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Ldloca(LocalBuilder lt) => _ilg!.Emit(OpCodes.Ldloca, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_U2).</summary> private void LdindU2() => _ilg!.Emit(OpCodes.Ldind_U2); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I4).</summary> private void LdindI4() => _ilg!.Emit(OpCodes.Ldind_I4); /// <summary>A macro for _ilg.Emit(OpCodes.Ldind_I8).</summary> private void LdindI8() => _ilg!.Emit(OpCodes.Ldind_I8); /// <summary>A macro for _ilg.Emit(OpCodes.Unaligned).</summary> private void Unaligned(byte alignment) => _ilg!.Emit(OpCodes.Unaligned, alignment); /// <summary>A macro for _ilg.Emit(OpCodes.Stloc).</summary> /// <remarks>ILGenerator will switch to the optimal form based on the local's index.</remarks> private void Stloc(LocalBuilder lt) => _ilg!.Emit(OpCodes.Stloc, lt); /// <summary>A macro for _ilg.Emit(OpCodes.Ldarg_0).</summary> protected void Ldthis() => _ilg!.Emit(OpCodes.Ldarg_0); /// <summary>A macro for _ilgEmit(OpCodes.Ldarg_1) </summary> private void Ldarg_1() => _ilg!.Emit(OpCodes.Ldarg_1); /// <summary>A macro for Ldthis(); Ldfld();</summary> protected void Ldthisfld(FieldInfo ft) { Ldthis(); _ilg!.Emit(OpCodes.Ldfld, ft); } /// <summary>Fetches the address of argument in passed in <paramref name="position"/></summary> /// <param name="position">The position of the argument which address needs to be fetched.</param> private void Ldarga_s(int position) => _ilg!.Emit(OpCodes.Ldarga_S, position); /// <summary>A macro for Ldthis(); Ldfld(); Stloc();</summary> private void Mvfldloc(FieldInfo ft, LocalBuilder lt) { Ldthisfld(ft); Stloc(lt); } /// <summary>A macro for _ilg.Emit(OpCodes.Stfld).</summary> protected void Stfld(FieldInfo ft) => _ilg!.Emit(OpCodes.Stfld, ft); /// <summary>A macro for _ilg.Emit(OpCodes.Callvirt, mt).</summary> protected void Callvirt(MethodInfo mt) => _ilg!.Emit(OpCodes.Callvirt, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Call, mt).</summary> protected void Call(MethodInfo mt) => _ilg!.Emit(OpCodes.Call, mt); /// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (short jump).</summary> private void Brfalse(Label l) => _ilg!.Emit(OpCodes.Brfalse_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brfalse) (long form).</summary> private void BrfalseFar(Label l) => _ilg!.Emit(OpCodes.Brfalse, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue) (long form).</summary> private void BrtrueFar(Label l) => _ilg!.Emit(OpCodes.Brtrue, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br) (long form).</summary> private void BrFar(Label l) => _ilg!.Emit(OpCodes.Br, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble) (long form).</summary> private void BleFar(Label l) => _ilg!.Emit(OpCodes.Ble, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt) (long form).</summary> private void BltFar(Label l) => _ilg!.Emit(OpCodes.Blt, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_Un) (long form).</summary> private void BltUnFar(Label l) => _ilg!.Emit(OpCodes.Blt_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge) (long form).</summary> private void BgeFar(Label l) => _ilg!.Emit(OpCodes.Bge, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un) (long form).</summary> private void BgeUnFar(Label l) => _ilg!.Emit(OpCodes.Bge_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne) (long form).</summary> private void BneFar(Label l) => _ilg!.Emit(OpCodes.Bne_Un, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq) (long form).</summary> private void BeqFar(Label l) => _ilg!.Emit(OpCodes.Beq, l); /// <summary>A macro for _ilg.Emit(OpCodes.Brtrue_S) (short jump).</summary> private void Brtrue(Label l) => _ilg!.Emit(OpCodes.Brtrue_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Br_S) (short jump).</summary> private void Br(Label l) => _ilg!.Emit(OpCodes.Br_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Ble_S) (short jump).</summary> private void Ble(Label l) => _ilg!.Emit(OpCodes.Ble_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Blt_S) (short jump).</summary> private void Blt(Label l) => _ilg!.Emit(OpCodes.Blt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_S) (short jump).</summary> private void Bge(Label l) => _ilg!.Emit(OpCodes.Bge_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bge_Un_S) (short jump).</summary> private void BgeUn(Label l) => _ilg!.Emit(OpCodes.Bge_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bgt_S) (short jump).</summary> private void Bgt(Label l) => _ilg!.Emit(OpCodes.Bgt_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Bne_S) (short jump).</summary> private void Bne(Label l) => _ilg!.Emit(OpCodes.Bne_Un_S, l); /// <summary>A macro for _ilg.Emit(OpCodes.Beq_S) (short jump).</summary> private void Beq(Label l) => _ilg!.Emit(OpCodes.Beq_S, l); /// <summary>A macro for the Ldlen instruction.</summary> private void Ldlen() => _ilg!.Emit(OpCodes.Ldlen); /// <summary>A macro for the Ldelem_I4 instruction.</summary> private void LdelemI4() => _ilg!.Emit(OpCodes.Ldelem_I4); /// <summary>A macro for the Stelem_I4 instruction.</summary> private void StelemI4() => _ilg!.Emit(OpCodes.Stelem_I4); private void Switch(Label[] table) => _ilg!.Emit(OpCodes.Switch, table); /// <summary>Declares a local bool.</summary> private LocalBuilder DeclareBool() => _ilg!.DeclareLocal(typeof(bool)); /// <summary>Declares a local int.</summary> private LocalBuilder DeclareInt32() => _ilg!.DeclareLocal(typeof(int)); /// <summary>Declares a local CultureInfo.</summary> private LocalBuilder? DeclareTextInfo() => _ilg!.DeclareLocal(typeof(TextInfo)); /// <summary>Declares a local string.</summary> private LocalBuilder DeclareString() => _ilg!.DeclareLocal(typeof(string)); private LocalBuilder DeclareReadOnlySpanChar() => _ilg!.DeclareLocal(typeof(ReadOnlySpan<char>)); /// <summary>Rents an Int32 local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentInt32Local() => new RentedLocalBuilder( _int32LocalsPool ??= new Stack<LocalBuilder>(), _int32LocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareInt32()); /// <summary>Rents a ReadOnlySpan(char) local variable slot from the pool of locals.</summary> /// <remarks> /// Care must be taken to Dispose of the returned <see cref="RentedLocalBuilder"/> when it's no longer needed, /// and also not to jump into the middle of a block involving a rented local from outside of that block. /// </remarks> private RentedLocalBuilder RentReadOnlySpanCharLocal() => new RentedLocalBuilder( _readOnlySpanCharLocalsPool ??= new Stack<LocalBuilder>(1), // capacity == 1 as we currently don't expect overlapping instances _readOnlySpanCharLocalsPool.TryPop(out LocalBuilder? iterationLocal) ? iterationLocal : DeclareReadOnlySpanChar()); /// <summary>Returned a rented local to the pool.</summary> private struct RentedLocalBuilder : IDisposable { private readonly Stack<LocalBuilder> _pool; private readonly LocalBuilder _local; internal RentedLocalBuilder(Stack<LocalBuilder> pool, LocalBuilder local) { _local = local; _pool = pool; } public static implicit operator LocalBuilder(RentedLocalBuilder local) => local._local; public void Dispose() { Debug.Assert(_pool != null); Debug.Assert(_local != null); Debug.Assert(!_pool.Contains(_local)); _pool.Push(_local); this = default; } } /// <summary>Sets the culture local to CultureInfo.CurrentCulture.</summary> private void InitLocalCultureInfo() { Debug.Assert(_textInfo != null); Call(s_cultureInfoGetCurrentCultureMethod); Callvirt(s_cultureInfoGetTextInfoMethod); Stloc(_textInfo); } /// <summary>Whether ToLower operations should be performed with the invariant culture as opposed to the one in <see cref="_textInfo"/>.</summary> private bool UseToLowerInvariant => _textInfo == null || (_options & RegexOptions.CultureInvariant) != 0; /// <summary>Invokes either char.ToLowerInvariant(c) or _textInfo.ToLower(c).</summary> private void CallToLower() { if (UseToLowerInvariant) { Call(s_charToLowerInvariantMethod); } else { using RentedLocalBuilder currentCharLocal = RentInt32Local(); Stloc(currentCharLocal); Ldloc(_textInfo!); Ldloc(currentCharLocal); Callvirt(s_textInfoToLowerMethod); } } /// <summary>Generates the implementation for TryFindNextPossibleStartingPosition.</summary> protected void EmitTryFindNextPossibleStartingPosition() { Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder pos = DeclareInt32(); bool rtl = (_options & RegexOptions.RightToLeft) != 0; _textInfo = null; if ((_options & RegexOptions.CultureInvariant) == 0) { bool needsCulture = _regexTree.FindOptimizations.FindMode switch { FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive => true, _ when _regexTree.FindOptimizations.FixedDistanceSets is List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets => sets.Exists(set => set.CaseInsensitive), _ => false, }; if (needsCulture) { _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } // Load necessary locals // int pos = base.runtextpos; // ReadOnlySpan<char> inputSpan = dynamicMethodArg; // TODO: We can reference the arg directly rather than using another local. Mvfldloc(s_runtextposField, pos); Ldarg_1(); Stloc(inputSpan); // Generate length check. If the input isn't long enough to possibly match, fail quickly. // It's rare for min required length to be 0, so we don't bother special-casing the check, // especially since we want the "return false" code regardless. int minRequiredLength = _regexTree.FindOptimizations.MinRequiredLength; Debug.Assert(minRequiredLength >= 0); Label returnFalse = DefineLabel(); Label finishedLengthCheck = DefineLabel(); // if (pos > inputSpan.Length - minRequiredLength) // or pos < minRequiredLength for rtl // { // base.runtextpos = inputSpan.Length; // or 0 for rtl // return false; // } Ldloc(pos); if (!rtl) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength > 0) { Ldc(minRequiredLength); Sub(); } Ble(finishedLengthCheck); } else { Ldc(minRequiredLength); Bge(finishedLengthCheck); } MarkLabel(returnFalse); Ldthis(); if (!rtl) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); } else { Ldc(0); } Stfld(s_runtextposField); Ldc(0); Ret(); MarkLabel(finishedLengthCheck); // Emit any anchors. if (EmitAnchors()) { return; } // Either anchors weren't specified, or they don't completely root all matches to a specific location. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_LeftToRight(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: Debug.Assert(!string.IsNullOrEmpty(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix)); EmitIndexOf_RightToLeft(_regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: Debug.Assert(_regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_LeftToRight(); break; case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: Debug.Assert(_regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet_RightToLeft(); break; case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); EmitLiteralAfterAtomicLoop(); break; default: Debug.Fail($"Unexpected mode: {_regexTree.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; case FindNextStartingPositionMode.NoSearch: // return true; Ldc(1); Ret(); break; } // Emits any anchors. Returns true if the anchor roots any match to a specific location and thus no further // searching is required; otherwise, false. bool EmitAnchors() { Label label; // Anchors that fully implement TryFindNextPossibleStartingPosition, with a check that leads to immediate success or failure determination. switch (_regexTree.FindOptimizations.FindMode) { case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: // if (pos != 0) goto returnFalse; // return true; Ldloc(pos); Ldc(0); Bne(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: // if (pos != base.runtextstart) goto returnFalse; // return true; Ldloc(pos); Ldthisfld(s_runtextstartField); Bne(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: // if (pos < inputSpan.Length - 1) base.runtextpos = inputSpan.Length - 1; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: // if (pos < inputSpan.Length) base.runtextpos = inputSpan.Length; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: // if (pos != 0) base.runtextpos = 0; // return true; label = DefineLabel(); Ldloc(pos); Ldc(0); Beq(label); Ldthis(); Ldc(0); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: // if (pos < inputSpan.Length - 1 || ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\n') goto returnFalse; // return true; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(1); Sub(); Blt(returnFalse); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUn(label); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); Bne(returnFalse); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: // if (pos < inputSpan.Length) goto returnFalse; // return true; Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Blt(returnFalse); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: // Jump to the end, minus the min required length, which in this case is actually the fixed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Bge(label); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump); Sub(); Stfld(s_runtextposField); MarkLabel(label); Ldc(1); Ret(); return true; } } // Now handle anchors that boost the position but don't determine immediate success or failure. if (!rtl) // we haven't done the work to validate these optimizations for RightToLeft { switch (_regexTree.FindOptimizations.LeadingAnchor) { case RegexNodeKind.Bol: { // Optimize the handling of a Beginning-Of-Line (BOL) anchor. BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any prefix or char class searches. label = DefineLabel(); // if (pos > 0... Ldloc(pos!); Ldc(0); Ble(label); // ... && inputSpan[pos - 1] != '\n') { ... } Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); Beq(label); // int tmp = inputSpan.Slice(pos).IndexOf('\n'); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldc('\n'); Call(s_spanIndexOfChar); using (RentedLocalBuilder newlinePos = RentInt32Local()) { Stloc(newlinePos); // if (newlinePos < 0 || newlinePos + pos + 1 > inputSpan.Length) // { // base.runtextpos = inputSpan.Length; // return false; // } Ldloc(newlinePos); Ldc(0); Blt(returnFalse); Ldloc(newlinePos); Ldloc(pos); Add(); Ldc(1); Add(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Bgt(returnFalse); // pos += newlinePos + 1; Ldloc(pos); Ldloc(newlinePos); Add(); Ldc(1); Add(); Stloc(pos); // We've updated the position. Make sure there's still enough room in the input for a possible match. // if (pos > inputSpan.Length - minRequiredLength) returnFalse; Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength != 0) { Ldc(minRequiredLength); Sub(); } Ldloc(pos); BltFar(returnFalse); } MarkLabel(label); } break; } switch (_regexTree.FindOptimizations.TrailingAnchor) { case RegexNodeKind.End or RegexNodeKind.EndZ when _regexTree.FindOptimizations.MaxPossibleLength is int maxLength: // Jump to the end, minus the max allowed length. { int extraNewlineBump = _regexTree.FindOptimizations.FindMode == FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ ? 1 : 0; label = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Bge(label); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldc(maxLength + extraNewlineBump); Sub(); Stloc(pos); MarkLabel(label); break; } } } return false; } // Emits a case-sensitive prefix search for a string at the beginning of the pattern. void EmitIndexOf_LeftToRight(string prefix) { using RentedLocalBuilder i = RentInt32Local(); // int i = inputSpan.Slice(pos).IndexOf(prefix); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Ldstr(prefix); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); Stloc(i); // if (i < 0) goto ReturnFalse; Ldloc(i); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(i); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } // Emits a case-sensitive right-to-left prefix search for a string at the beginning of the pattern. void EmitIndexOf_RightToLeft(string prefix) { // pos = inputSpan.Slice(0, pos).LastIndexOf(prefix); Ldloca(inputSpan); Ldc(0); Ldloc(pos); Call(s_spanSliceIntIntMethod); Ldstr(prefix); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfSpan); Stloc(pos); // if (pos < 0) goto ReturnFalse; Ldloc(pos); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + prefix.Length; // return true; Ldthis(); Ldloc(pos); Ldc(prefix.Length); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } // Emits a search for a set at a fixed position from the start of the pattern, // and potentially other sets at other fixed positions in the pattern. void EmitFixedSet_LeftToRight() { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? sets = _regexTree.FindOptimizations.FixedDistanceSets; (char[]? Chars, string Set, int Distance, bool CaseInsensitive) primarySet = sets![0]; const int MaxSets = 4; int setsToUse = Math.Min(sets.Count, MaxSets); using RentedLocalBuilder iLocal = RentInt32Local(); using RentedLocalBuilder textSpanLocal = RentReadOnlySpanCharLocal(); // ReadOnlySpan<char> span = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(textSpanLocal); // If we can use IndexOf{Any}, try to accelerate the skip loop via vectorization to match the first prefix. // We can use it if this is a case-sensitive class with a small number of characters in the class. int setIndex = 0; bool canUseIndexOf = !primarySet.CaseInsensitive && primarySet.Chars is not null; bool needLoop = !canUseIndexOf || setsToUse > 1; Label checkSpanLengthLabel = default; Label charNotInClassLabel = default; Label loopBody = default; if (needLoop) { checkSpanLengthLabel = DefineLabel(); charNotInClassLabel = DefineLabel(); loopBody = DefineLabel(); // for (int i = 0; Ldc(0); Stloc(iLocal); BrFar(checkSpanLengthLabel); MarkLabel(loopBody); } if (canUseIndexOf) { setIndex = 1; if (needLoop) { // slice.Slice(iLocal + primarySet.Distance); Ldloca(textSpanLocal); Ldloc(iLocal); if (primarySet.Distance != 0) { Ldc(primarySet.Distance); Add(); } Call(s_spanSliceIntMethod); } else if (primarySet.Distance != 0) { // slice.Slice(primarySet.Distance) Ldloca(textSpanLocal); Ldc(primarySet.Distance); Call(s_spanSliceIntMethod); } else { // slice Ldloc(textSpanLocal); } switch (primarySet.Chars!.Length) { case 1: // tmp = ...IndexOf(setChars[0]); Ldc(primarySet.Chars[0]); Call(s_spanIndexOfChar); break; case 2: // tmp = ...IndexOfAny(setChars[0], setChars[1]); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: // tmp = ...IndexOfAny(setChars[0], setChars[1], setChars[2]}); Ldc(primarySet.Chars[0]); Ldc(primarySet.Chars[1]); Ldc(primarySet.Chars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(primarySet.Chars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } if (needLoop) { // i += tmp; // if (tmp < 0) goto returnFalse; using (RentedLocalBuilder tmp = RentInt32Local()) { Stloc(tmp); Ldloc(iLocal); Ldloc(tmp); Add(); Stloc(iLocal); Ldloc(tmp); Ldc(0); BltFar(returnFalse); } } else { // i = tmp; // if (i < 0) goto returnFalse; Stloc(iLocal); Ldloc(iLocal); Ldc(0); BltFar(returnFalse); } // if (i >= slice.Length - (minRequiredLength - 1)) goto returnFalse; if (sets.Count > 1) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); Ldc(minRequiredLength - 1); Sub(); Ldloc(iLocal); BleFar(returnFalse); } } // if (!CharInClass(slice[i], prefix[0], "...")) continue; // if (!CharInClass(slice[i + 1], prefix[1], "...")) continue; // if (!CharInClass(slice[i + 2], prefix[2], "...")) continue; // ... Debug.Assert(setIndex is 0 or 1); for ( ; setIndex < sets.Count; setIndex++) { Debug.Assert(needLoop); Ldloca(textSpanLocal); Ldloc(iLocal); if (sets[setIndex].Distance != 0) { Ldc(sets[setIndex].Distance); Add(); } Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(sets[setIndex].Set, sets[setIndex].CaseInsensitive); BrfalseFar(charNotInClassLabel); } // base.runtextpos = pos + i; // return true; Ldthis(); Ldloc(pos); Ldloc(iLocal); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); if (needLoop) { MarkLabel(charNotInClassLabel); // for (...; ...; i++) Ldloc(iLocal); Ldc(1); Add(); Stloc(iLocal); // for (...; i < span.Length - (minRequiredLength - 1); ...); MarkLabel(checkSpanLengthLabel); Ldloc(iLocal); Ldloca(textSpanLocal); Call(s_spanGetLengthMethod); if (setsToUse > 1 || primarySet.Distance != 0) { Ldc(minRequiredLength - 1); Sub(); } BltFar(loopBody); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } // Emits a right-to-left search for a set at a fixed position from the start of the pattern. // (Currently that position will always be a distance of 0, meaning the start of the pattern itself.) void EmitFixedSet_RightToLeft() { (char[]? Chars, string Set, int Distance, bool CaseInsensitive) set = _regexTree.FindOptimizations.FixedDistanceSets![0]; Debug.Assert(set.Distance == 0); if (set.Chars is { Length: 1 } && !set.CaseInsensitive) { // pos = inputSpan.Slice(0, pos).LastIndexOf(set.Chars[0]); Ldloca(inputSpan); Ldc(0); Ldloc(pos); Call(s_spanSliceIntIntMethod); Ldc(set.Chars[0]); Call(s_spanLastIndexOfChar); Stloc(pos); // if (pos < 0) goto returnFalse; Ldloc(pos); Ldc(0); BltFar(returnFalse); // base.runtextpos = pos + 1; // return true; Ldthis(); Ldloc(pos); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } else { Label condition = DefineLabel(); // while ((uint)--pos < (uint)inputSpan.Length) MarkLabel(condition); Ldloc(pos); Ldc(1); Sub(); Stloc(pos); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(returnFalse); // if (!MatchCharacterClass(inputSpan[i], set.Set, set.CaseInsensitive)) goto condition; Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(set.Set, set.CaseInsensitive); Brfalse(condition); // base.runtextpos = pos + 1; // return true; Ldthis(); Ldloc(pos); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); } } // Emits a search for a literal following a leading atomic single-character loop. void EmitLiteralAfterAtomicLoop() { Debug.Assert(_regexTree.FindOptimizations.LiteralAfterLoop is not null); (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = _regexTree.FindOptimizations.LiteralAfterLoop.Value; Debug.Assert(target.LoopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(target.LoopNode.N == int.MaxValue); // while (true) Label loopBody = DefineLabel(); Label loopEnd = DefineLabel(); MarkLabel(loopBody); // ReadOnlySpan<char> slice = inputSpan.Slice(pos); using RentedLocalBuilder slice = RentReadOnlySpanCharLocal(); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); // Find the literal. If we can't find it, we're done searching. // int i = slice.IndexOf(literal); // if (i < 0) break; using RentedLocalBuilder i = RentInt32Local(); Ldloc(slice); if (target.Literal.String is string literalString) { Ldstr(literalString); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (target.Literal.Chars is not char[] literalChars) { Ldc(target.Literal.Char); Call(s_spanIndexOfChar); } else { switch (literalChars.Length) { case 2: Ldc(literalChars[0]); Ldc(literalChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literalChars[0]); Ldc(literalChars[1]); Ldc(literalChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(new string(literalChars)); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } Stloc(i); Ldloc(i); Ldc(0); BltFar(loopEnd); // We found the literal. Walk backwards from it finding as many matches as we can against the loop. // int prev = i; using RentedLocalBuilder prev = RentInt32Local(); Ldloc(i); Stloc(prev); // while ((uint)--prev < (uint)slice.Length) && MatchCharClass(slice[prev])); Label innerLoopBody = DefineLabel(); Label innerLoopEnd = DefineLabel(); MarkLabel(innerLoopBody); Ldloc(prev); Ldc(1); Sub(); Stloc(prev); Ldloc(prev); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(innerLoopEnd); Ldloca(slice); Ldloc(prev); Call(s_spanGetItemMethod); LdindU2(); EmitMatchCharacterClass(target.LoopNode.Str!, caseInsensitive: false); BrtrueFar(innerLoopBody); MarkLabel(innerLoopEnd); if (target.LoopNode.M > 0) { // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. // if ((i - prev - 1) < target.LoopNode.M) // { // pos += i + 1; // continue; // } Label metMinimum = DefineLabel(); Ldloc(i); Ldloc(prev); Sub(); Ldc(1); Sub(); Ldc(target.LoopNode.M); Bge(metMinimum); Ldloc(pos); Ldloc(i); Add(); Ldc(1); Add(); Stloc(pos); BrFar(loopBody); MarkLabel(metMinimum); } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. // base.runtextpos = pos + prev + 1; // return true; Ldthis(); Ldloc(pos); Ldloc(prev); Add(); Ldc(1); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); // } MarkLabel(loopEnd); // base.runtextpos = inputSpan.Length; // return false; BrFar(returnFalse); } } /// <summary>Generates the implementation for TryMatchAtCurrentPosition.</summary> protected void EmitTryMatchAtCurrentPosition() { // In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiled was effectively an unrolled // version of what RegexInterpreter would process. The RegexNode tree would be turned into a series of opcodes via // RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterated through the // opcodes generating code for each equivalent to what the interpreter would do albeit with some decisions made at compile-time // rather than at run-time. This approach, however, lead to complicated code that wasn't pay-for-play (e.g. a big backtracking // jump table that all compilations went through even if there was no backtracking), that didn't factor in the shape of the // tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that didn't read well // when decompiled from IL to C# or when directly emitted as C# as part of a source generator. // // This implementation is instead based on directly walking the RegexNode tree and outputting code for each node in the graph. // A dedicated for each kind of RegexNode emits the code necessary to handle that node's processing, including recursively // calling the relevant function for any of its children nodes. Backtracking is handled not via a giant jump table, but instead // by emitting direct jumps to each backtracking construct. This is achieved by having all match failures jump to a "done" // label that can be changed by a previous emitter, e.g. before EmitLoop returns, it ensures that "doneLabel" is set to the // label that code should jump back to when backtracking. That way, a subsequent EmitXx function doesn't need to know exactly // where to jump: it simply always jumps to "doneLabel" on match failure, and "doneLabel" is always configured to point to // the right location. In an expression without backtracking, or before any backtracking constructs have been encountered, // "doneLabel" is simply the final return location from the TryMatchAtCurrentPosition method that will undo any captures and exit, signaling to // the calling scan loop that nothing was matched. Debug.Assert(_regexTree != null); _int32LocalsPool?.Clear(); _readOnlySpanCharLocalsPool?.Clear(); // Get the root Capture node of the tree. RegexNode node = _regexTree.Root; Debug.Assert(node.Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); Debug.Assert(node.ChildCount() == 1, "Capture nodes should have one child"); // Skip the Capture node. We handle the implicit root capture specially. node = node.Child(0); // In some limited cases, TryFindNextPossibleStartingPosition will only return true if it successfully matched the whole expression. // We can special case these to do essentially nothing in TryMatchAtCurrentPosition other than emit the capture. switch (node.Kind) { case RegexNodeKind.Multi or RegexNodeKind.Notone or RegexNodeKind.One or RegexNodeKind.Set when !IsCaseInsensitive(node): // This is the case for single and multiple characters, though the whole thing is only guaranteed // to have been validated in TryFindNextPossibleStartingPosition when doing case-sensitive comparison. // base.Capture(0, base.runtextpos, base.runtextpos + node.Str.Length); // base.runtextpos = base.runtextpos + node.Str.Length; // return true; int length = node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1; if ((node.Options & RegexOptions.RightToLeft) != 0) { length = -length; } Ldthis(); Dup(); Ldc(0); Ldthisfld(s_runtextposField); Dup(); Ldc(length); Add(); Call(s_captureMethod); Ldthisfld(s_runtextposField); Ldc(length); Add(); Stfld(s_runtextposField); Ldc(1); Ret(); return; // The source generator special-cases RegexNode.Empty, for purposes of code learning rather than // performance. Since that's not applicable to RegexCompiler, that code isn't mirrored here. } AnalysisResults analysis = RegexTreeAnalyzer.Analyze(_regexTree); // Initialize the main locals used throughout the implementation. LocalBuilder inputSpan = DeclareReadOnlySpanChar(); LocalBuilder originalPos = DeclareInt32(); LocalBuilder pos = DeclareInt32(); LocalBuilder slice = DeclareReadOnlySpanChar(); Label doneLabel = DefineLabel(); Label originalDoneLabel = doneLabel; if (_hasTimeout) { _loopTimeoutCounter = DeclareInt32(); } // CultureInfo culture = CultureInfo.CurrentCulture; // only if the whole expression or any subportion is ignoring case, and we're not using invariant InitializeCultureForTryMatchAtCurrentPositionIfNecessary(analysis); // ReadOnlySpan<char> inputSpan = input; Ldarg_1(); Stloc(inputSpan); // int pos = base.runtextpos; // int originalpos = pos; Ldthisfld(s_runtextposField); Stloc(pos); Ldloc(pos); Stloc(originalPos); // int stackpos = 0; LocalBuilder stackpos = DeclareInt32(); Ldc(0); Stloc(stackpos); // The implementation tries to use const indexes into the span wherever possible, which we can do // for all fixed-length constructs. In such cases (e.g. single chars, repeaters, strings, etc.) // we know at any point in the regex exactly how far into it we are, and we can use that to index // into the span created at the beginning of the routine to begin at exactly where we're starting // in the input. When we encounter a variable-length construct, we transfer the static value to // pos, slicing the inputSpan appropriately, and then zero out the static position. int sliceStaticPos = 0; SliceInputSpan(); // Check whether there are captures anywhere in the expression. If there isn't, we can skip all // the boilerplate logic around uncapturing, as there won't be anything to uncapture. bool expressionHasCaptures = analysis.MayContainCapture(node); // Emit the code for all nodes in the tree. EmitNode(node); // pos += sliceStaticPos; // base.runtextpos = pos; // Capture(0, originalpos, pos); // return true; Ldthis(); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); Stloc(pos); Ldloc(pos); } Stfld(s_runtextposField); Ldthis(); Ldc(0); Ldloc(originalPos); Ldloc(pos); Call(s_captureMethod); Ldc(1); Ret(); // NOTE: The following is a difference from the source generator. The source generator emits: // UncaptureUntil(0); // return false; // at every location where the all-up match is known to fail. In contrast, the compiler currently // emits this uncapture/return code in one place and jumps to it upon match failure. The difference // stems primarily from the return-at-each-location pattern resulting in cleaner / easier to read // source code, which is not an issue for RegexCompiler emitting IL instead of C#. // If the graph contained captures, undo any remaining to handle failed matches. if (expressionHasCaptures) { // while (base.Crawlpos() != 0) base.Uncapture(); Label finalReturnLabel = DefineLabel(); Br(finalReturnLabel); MarkLabel(originalDoneLabel); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Brtrue(body); // Done: MarkLabel(finalReturnLabel); } else { // Done: MarkLabel(originalDoneLabel); } // return false; Ldc(0); Ret(); // Generated code successfully. return; static bool IsCaseInsensitive(RegexNode node) => (node.Options & RegexOptions.IgnoreCase) != 0; // Slices the inputSpan starting at pos until end and stores it into slice. void SliceInputSpan() { // slice = inputSpan.Slice(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanSliceIntMethod); Stloc(slice); } // Emits the sum of a constant and a value from a local. void EmitSum(int constant, LocalBuilder? local) { if (local == null) { Ldc(constant); } else if (constant == 0) { Ldloc(local); } else { Ldloc(local); Ldc(constant); Add(); } } // Emits a check that the span is large enough at the currently known static position to handle the required additional length. void EmitSpanLengthCheck(int requiredLength, LocalBuilder? dynamicRequiredLength = null) { // if ((uint)(sliceStaticPos + requiredLength + dynamicRequiredLength - 1) >= (uint)slice.Length) goto Done; Debug.Assert(requiredLength > 0); EmitSum(sliceStaticPos + requiredLength - 1, dynamicRequiredLength); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); } // Emits code to get ref slice[sliceStaticPos] void EmitTextSpanOffset() { Ldloc(slice); Call(s_memoryMarshalGetReference); if (sliceStaticPos > 0) { Ldc(sliceStaticPos * sizeof(char)); Add(); } } // Adds the value of sliceStaticPos into the pos local, zeros out sliceStaticPos, // and resets slice to be inputSpan.Slice(pos). void TransferSliceStaticPosToPos(bool forceSliceReload = false) { if (sliceStaticPos > 0) { // pos += sliceStaticPos; // sliceStaticPos = 0; Ldloc(pos); Ldc(sliceStaticPos); Add(); Stloc(pos); sliceStaticPos = 0; // slice = inputSpan.Slice(pos); SliceInputSpan(); } else if (forceSliceReload) { // slice = inputSpan.Slice(pos); SliceInputSpan(); } } // Emits the code for an alternation. void EmitAlternation(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Alternate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); int childCount = node.ChildCount(); Debug.Assert(childCount >= 2); Label originalDoneLabel = doneLabel; // Both atomic and non-atomic are supported. While a parent RegexNode.Atomic node will itself // successfully prevent backtracking into this child node, we can emit better / cheaper code // for an Alternate when it is atomic, so we still take it into account here. Debug.Assert(node.Parent is not null); bool isAtomic = analysis.IsAtomicByAncestor(node); // Label to jump to when any branch completes successfully. Label matchLabel = DefineLabel(); // Save off pos. We'll need to reset this each time a branch fails. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // We need to be able to undo captures in two situations: // - If a branch of the alternation itself contains captures, then if that branch // fails to match, any captures from that branch until that failure point need to // be uncaptured prior to jumping to the next branch. // - If the expression after the alternation contains captures, then failures // to match in those expressions could trigger backtracking back into the // alternation, and thus we need uncapture any of them. // As such, if the alternation contains captures or if it's not atomic, we need // to grab the current crawl position so we can unwind back to it when necessary. // We can do all of the uncapturing as part of falling through to the next branch. // If we fail in a branch, then such uncapturing will unwind back to the position // at the start of the alternation. If we fail after the alternation, and the // matched branch didn't contain any backtracking, then the failure will end up // jumping to the next branch, which will unwind the captures. And if we fail after // the alternation and the matched branch did contain backtracking, that backtracking // construct is responsible for unwinding back to its starting crawl position. If // it eventually ends up failing, that failure will result in jumping to the next branch // of the alternation, which will again dutifully unwind the remaining captures until // what they were at the start of the alternation. Of course, if there are no captures // anywhere in the regex, we don't have to do any of that. LocalBuilder? startingCapturePos = null; if (expressionHasCaptures && (analysis.MayContainCapture(node) || !isAtomic)) { // startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // After executing the alternation, subsequent matching may fail, at which point execution // will need to backtrack to the alternation. We emit a branching table at the end of the // alternation, with a label that will be left as the "doneLabel" upon exiting emitting the // alternation. The branch table is populated with an entry for each branch of the alternation, // containing either the label for the last backtracking construct in the branch if such a construct // existed (in which case the doneLabel upon emitting that node will be different from before it) // or the label for the next branch. var labelMap = new Label[childCount]; Label backtrackLabel = DefineLabel(); for (int i = 0; i < childCount; i++) { bool isLastBranch = i == childCount - 1; Label nextBranch = default; if (!isLastBranch) { // Failure to match any branch other than the last one should result // in jumping to process the next branch. nextBranch = DefineLabel(); doneLabel = nextBranch; } else { // Failure to match the last branch is equivalent to failing to match // the whole alternation, which means those failures should jump to // what "doneLabel" was defined as when starting the alternation. doneLabel = originalDoneLabel; } // Emit the code for each branch. EmitNode(node.Child(i)); // Add this branch to the backtracking table. At this point, either the child // had backtracking constructs, in which case doneLabel points to the last one // and that's where we'll want to jump to, or it doesn't, in which case doneLabel // still points to the nextBranch, which similarly is where we'll want to jump to. if (!isAtomic) { // if (stackpos + 3 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = i; // base.runstack[stackpos++] = startingCapturePos; // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldc(i)); if (startingCapturePos is not null) { EmitStackPush(() => Ldloc(startingCapturePos)); } EmitStackPush(() => Ldloc(startingPos)); } labelMap[i] = doneLabel; // If we get here in the generated code, the branch completed successfully. // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. // pos += sliceStaticPos; // sliceStaticPos = 0; // goto matchLabel; TransferSliceStaticPosToPos(); BrFar(matchLabel); // Reset state for next branch and loop around to generate it. This includes // setting pos back to what it was at the beginning of the alternation, // updating slice to be the full length it was, and if there's a capture that // needs to be reset, uncapturing it. if (!isLastBranch) { // NextBranch: // pos = startingPos; // slice = inputSpan.Slice(pos); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); MarkLabel(nextBranch); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } } } // We should never fall through to this location in the generated code. Either // a branch succeeded in matching and jumped to the end, or a branch failed in // matching and jumped to the next branch location. We only get to this code // if backtracking occurs and the code explicitly jumps here based on our setting // "doneLabel" to the label for this section. Thus, we only need to emit it if // something can backtrack to us, which can't happen if we're inside of an atomic // node. Thus, emit the backtracking section only if we're non-atomic. if (isAtomic) { doneLabel = originalDoneLabel; } else { doneLabel = backtrackLabel; MarkLabel(backtrackLabel); // startingPos = base.runstack[--stackpos]; // startingCapturePos = base.runstack[--stackpos]; // switch (base.runstack[--stackpos]) { ... } // branch number EmitStackPop(); Stloc(startingPos); if (startingCapturePos is not null) { EmitStackPop(); Stloc(startingCapturePos); } EmitStackPop(); Switch(labelMap); } // Successfully completed the alternate. MarkLabel(matchLabel); Debug.Assert(sliceStaticPos == 0); } // Emits the code to handle a backreference. void EmitBackreference(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; TransferSliceStaticPosToPos(); Label backreferenceEnd = DefineLabel(); // if (!base.IsMatched(capnum)) goto (ecmascript ? end : doneLabel); Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar((node.Options & RegexOptions.ECMAScript) == 0 ? doneLabel : backreferenceEnd); using RentedLocalBuilder matchLength = RentInt32Local(); using RentedLocalBuilder matchIndex = RentInt32Local(); using RentedLocalBuilder i = RentInt32Local(); // int matchLength = base.MatchLength(capnum); Ldthis(); Ldc(capnum); Call(s_matchLengthMethod); Stloc(matchLength); if (!rtl) { // if (slice.Length < matchLength) goto doneLabel; Ldloca(slice); Call(s_spanGetLengthMethod); } else { // if (pos < matchLength) goto doneLabel; Ldloc(pos); } Ldloc(matchLength); BltFar(doneLabel); // int matchIndex = base.MatchIndex(capnum); Ldthis(); Ldc(capnum); Call(s_matchIndexMethod); Stloc(matchIndex); Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) Ldc(0); Stloc(i); Br(condition); MarkLabel(body); // if (inputSpan[matchIndex + i] != slice[i]) goto doneLabel; // for rtl, instead of slice[i] using inputSpan[pos - matchLength + i] Ldloca(inputSpan); Ldloc(matchIndex); Ldloc(i); Add(); Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } if (!rtl) { Ldloca(slice); Ldloc(i); } else { Ldloca(inputSpan); Ldloc(pos); Ldloc(matchLength); Sub(); Ldloc(i); Add(); } Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } BneFar(doneLabel); // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < matchLength; ...) MarkLabel(condition); Ldloc(i); Ldloc(matchLength); Blt(body); // pos += matchLength; // or -= for rtl Ldloc(pos); Ldloc(matchLength); if (!rtl) { Add(); } else { Sub(); } Stloc(pos); if (!rtl) { SliceInputSpan(); } MarkLabel(backreferenceEnd); } // Emits the code for an if(backreference)-then-else conditional. void EmitBackreferenceConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.BackreferenceConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 2, $"Expected 2 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // Get the capture number to test. int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(0); RegexNode? noBranch = node.Child(1) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label refNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the conditional needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder resumeAt = DeclareInt32(); // if (!base.IsMatched(capnum)) goto refNotMatched; Ldthis(); Ldc(capnum); Call(s_isMatchedMethod); BrfalseFar(refNotMatched); // The specified capture was captured. Run the "yes" branch. // If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt); } bool needsEndConditional = postYesDoneLabel != originalDoneLabel || noBranch is not null; if (needsEndConditional) { // goto endConditional; BrFar(endConditional); } MarkLabel(refNotMatched); Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt); } } if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // We're atomic by our parent, so even if either child branch has backtracking constructs, // we don't need to emit any backtracking logic in support, as nothing will backtrack in. // Instead, we just ensure we revert back to the original done label so that any backtracking // skips over this node. doneLabel = originalDoneLabel; if (needsEndConditional) { MarkLabel(endConditional); } } else { // Subsequent expressions might try to backtrack to here, so output a backtracking map based on resumeAt. // Skip the backtracking section // goto endConditional; Debug.Assert(needsEndConditional); Br(endConditional); // Backtrack section Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // Pop from the stack the branch that was used and jump back to its backtracking location. // resumeAt = base.runstack[--stackpos]; EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postIfDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto originalDoneLabel; BrFar(originalDoneLabel); if (needsEndConditional) { MarkLabel(endConditional); } // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt)); } } // Emits the code for an if(expression)-then-else conditional. void EmitExpressionConditional(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.ExpressionConditional, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 3, $"Expected 3 children, found {node.ChildCount()}"); bool isAtomic = analysis.IsAtomicByAncestor(node); // We're branching in a complicated fashion. Make sure sliceStaticPos is 0. TransferSliceStaticPosToPos(); // The first child node is the condition expression. If this matches, then we branch to the "yes" branch. // If it doesn't match, then we branch to the optional "no" branch if it exists, or simply skip the "yes" // branch, otherwise. The condition is treated as a positive lookaround. RegexNode condition = node.Child(0); // Get the "yes" branch and the "no" branch. The "no" branch is optional in syntax and is thus // somewhat likely to be Empty. RegexNode yesBranch = node.Child(1); RegexNode? noBranch = node.Child(2) is { Kind: not RegexNodeKind.Empty } childNo ? childNo : null; Label originalDoneLabel = doneLabel; Label expressionNotMatched = DefineLabel(); Label endConditional = DefineLabel(); // As with alternations, we have potentially multiple branches, each of which may contain // backtracking constructs, but the expression after the condition needs a single target // to backtrack to. So, we expose a single Backtrack label and track which branch was // followed in this resumeAt local. LocalBuilder? resumeAt = null; if (!isAtomic) { resumeAt = DeclareInt32(); } // If the condition expression has captures, we'll need to uncapture them in the case of no match. LocalBuilder? startingCapturePos = null; if (analysis.MayContainCapture(condition)) { // int startingCapturePos = base.Crawlpos(); startingCapturePos = DeclareInt32(); Ldthis(); Call(s_crawlposMethod); Stloc(startingCapturePos); } // Emit the condition expression. Route any failures to after the yes branch. This code is almost // the same as for a positive lookaround; however, a positive lookaround only needs to reset the position // on a successful match, as a failed match fails the whole expression; here, we need to reset the // position on completion, regardless of whether the match is successful or not. doneLabel = expressionNotMatched; // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingSliceStaticPos = sliceStaticPos; // Emit the child. The condition expression is a zero-width assertion, which is atomic, // so prevent backtracking into it. EmitNode(condition); doneLabel = originalDoneLabel; // After the condition completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; // The expression matched. Run the "yes" branch. If it successfully matches, jump to the end. EmitNode(yesBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch Label postYesDoneLabel = doneLabel; if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 0; Ldc(0); Stloc(resumeAt!); } // goto endConditional; BrFar(endConditional); // After the condition completes unsuccessfully, reset the text positions // _and_ reset captures, which should not persist when the whole expression failed. // pos = startingPos; MarkLabel(expressionNotMatched); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingSliceStaticPos; if (startingCapturePos is not null) { EmitUncaptureUntil(startingCapturePos); } Label postNoDoneLabel = originalDoneLabel; if (noBranch is not null) { // Output the no branch. doneLabel = originalDoneLabel; EmitNode(noBranch); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch postNoDoneLabel = doneLabel; if (!isAtomic && postNoDoneLabel != originalDoneLabel) { // resumeAt = 1; Ldc(1); Stloc(resumeAt!); } } else { // There's only a yes branch. If it's going to cause us to output a backtracking // label but code may not end up taking the yes branch path, we need to emit a resumeAt // that will cause the backtracking to immediately pass through this node. if (!isAtomic && postYesDoneLabel != originalDoneLabel) { // resumeAt = 2; Ldc(2); Stloc(resumeAt!); } } // If either the yes branch or the no branch contained backtracking, subsequent expressions // might try to backtrack to here, so output a backtracking map based on resumeAt. if (isAtomic || (postYesDoneLabel == originalDoneLabel && postNoDoneLabel == originalDoneLabel)) { // EndConditional: doneLabel = originalDoneLabel; MarkLabel(endConditional); } else { Debug.Assert(resumeAt is not null); // Skip the backtracking section. BrFar(endConditional); Label backtrack = DefineLabel(); doneLabel = backtrack; MarkLabel(backtrack); // resumeAt = StackPop(); EmitStackPop(); Stloc(resumeAt); if (postYesDoneLabel != originalDoneLabel) { // if (resumeAt == 0) goto postYesDoneLabel; Ldloc(resumeAt); Ldc(0); BeqFar(postYesDoneLabel); } if (postNoDoneLabel != originalDoneLabel) { // if (resumeAt == 1) goto postNoDoneLabel; Ldloc(resumeAt); Ldc(1); BeqFar(postNoDoneLabel); } // goto postConditionalDoneLabel; BrFar(originalDoneLabel); // EndConditional: MarkLabel(endConditional); // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = resumeAt; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(resumeAt!)); } } // Emits the code for a Capture node. void EmitCapture(RegexNode node, RegexNode? subsequent = null) { Debug.Assert(node.Kind is RegexNodeKind.Capture, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping); int uncapnum = RegexParser.MapCaptureNumber(node.N, _regexTree.CaptureNumberSparseMapping); bool isAtomic = analysis.IsAtomicByAncestor(node); // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); // startingPos = pos; TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); RegexNode child = node.Child(0); if (uncapnum != -1) { // if (!IsMatched(uncapnum)) goto doneLabel; Ldthis(); Ldc(uncapnum); Call(s_isMatchedMethod); BrfalseFar(doneLabel); } // Emit child node. Label originalDoneLabel = doneLabel; EmitNode(child, subsequent); bool childBacktracks = doneLabel != originalDoneLabel; // pos += sliceStaticPos; // slice = slice.Slice(sliceStaticPos); TransferSliceStaticPosToPos(); if (uncapnum == -1) { // Capture(capnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldloc(startingPos); Ldloc(pos); Call(s_captureMethod); } else { // TransferCapture(capnum, uncapnum, startingPos, pos); Ldthis(); Ldc(capnum); Ldc(uncapnum); Ldloc(startingPos); Ldloc(pos); Call(s_transferCaptureMethod); } if (isAtomic || !childBacktracks) { // If the capture is atomic and nothing can backtrack into it, we're done. // Similarly, even if the capture isn't atomic, if the captured expression // doesn't do any backtracking, we're done. doneLabel = originalDoneLabel; } else { // We're not atomic and the child node backtracks. When it does, we need // to ensure that the starting position for the capture is appropriately // reset to what it was initially (it could have changed as part of being // in a loop or similar). So, we emit a backtracking section that // pushes/pops the starting position before falling through. // if (stackpos + 1 >= base.runstack.Length) Array.Resize(ref base.runstack, base.runstack.Length * 2); // base.runstack[stackpos++] = startingPos; EmitStackResizeIfNeeded(1); EmitStackPush(() => Ldloc(startingPos)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); Br(backtrackingEnd); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } // Emits code to unwind the capture stack until the crawl position specified in the provided local. void EmitUncaptureUntil(LocalBuilder startingCapturePos) { Debug.Assert(startingCapturePos != null); // while (base.Crawlpos() > startingCapturePos) base.Uncapture(); Label condition = DefineLabel(); Label body = DefineLabel(); Br(condition); MarkLabel(body); Ldthis(); Call(s_uncaptureMethod); MarkLabel(condition); Ldthis(); Call(s_crawlposMethod); Ldloc(startingCapturePos); Bgt(body); } // Emits the code to handle a positive lookaround assertion. This is a positive lookahead // for left-to-right and a positive lookbehind for right-to-left. void EmitPositiveLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // After the child completes successfully, reset the text positions. // Do not reset captures, which persist beyond the lookaround. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; } // Emits the code to handle a negative lookaround assertion. This is a negative lookahead // for left-to-right and a negative lookbehind for right-to-left. void EmitNegativeLookaroundAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); if (analysis.HasRightToLeft) { // Lookarounds are the only places in the node tree where we might change direction, // i.e. where we might go from RegexOptions.None to RegexOptions.RightToLeft, or vice // versa. This is because lookbehinds are implemented by making the whole subgraph be // RegexOptions.RightToLeft and reversed. Since we use static position to optimize left-to-right // and don't use it in support of right-to-left, we need to resync the static position // to the current position when entering a lookaround, just in case we're changing direction. TransferSliceStaticPosToPos(forceSliceReload: true); } Label originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookaround. // startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); int startingTextSpanPos = sliceStaticPos; Label negativeLookaheadDoneLabel = DefineLabel(); doneLabel = negativeLookaheadDoneLabel; // Emit the child. RegexNode child = node.Child(0); if (analysis.MayBacktrack(child)) { // Lookarounds are implicitly atomic, so we need to emit the node as atomic if it might backtrack. EmitAtomic(node, null); } else { EmitNode(child); } // If the generated code ends up here, it matched the lookaround, which actually // means failure for a _negative_ lookaround, so we need to jump to the original done. // goto originalDoneLabel; BrFar(originalDoneLabel); // Failures (success for a negative lookaround) jump here. MarkLabel(negativeLookaheadDoneLabel); if (doneLabel == negativeLookaheadDoneLabel) { doneLabel = originalDoneLabel; } // After the child completes in failure (success for negative lookaround), reset the text positions. // pos = startingPos; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; doneLabel = originalDoneLabel; } // Emits the code for the node. void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { StackHelper.CallOnEmptyStack(EmitNode, node, subsequent, emitLengthChecksIfRequired); return; } // RightToLeft doesn't take advantage of static positions. While RightToLeft won't update static // positions, a previous operation may have left us with a non-zero one. Make sure it's zero'd out // such that pos and slice are up-to-date. Note that RightToLeft also shouldn't use the slice span, // as it's not kept up-to-date; any RightToLeft implementation that wants to use it must first update // it from pos. if ((node.Options & RegexOptions.RightToLeft) != 0) { TransferSliceStaticPosToPos(); } switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: case RegexNodeKind.Bol: case RegexNodeKind.Eol: case RegexNodeKind.End: case RegexNodeKind.EndZ: EmitAnchors(node); break; case RegexNodeKind.Boundary: case RegexNodeKind.NonBoundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.NonECMABoundary: EmitBoundary(node); break; case RegexNodeKind.Multi: EmitMultiChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: EmitSingleChar(node, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: EmitSingleCharLoop(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: EmitSingleCharAtomicLoop(node); break; case RegexNodeKind.Loop: EmitLoop(node); break; case RegexNodeKind.Lazyloop: EmitLazy(node); break; case RegexNodeKind.Alternate: EmitAlternation(node); break; case RegexNodeKind.Concatenate: EmitConcatenation(node, subsequent, emitLengthChecksIfRequired); break; case RegexNodeKind.Atomic: EmitAtomic(node, subsequent); break; case RegexNodeKind.Backreference: EmitBackreference(node); break; case RegexNodeKind.BackreferenceConditional: EmitBackreferenceConditional(node); break; case RegexNodeKind.ExpressionConditional: EmitExpressionConditional(node); break; case RegexNodeKind.Capture: EmitCapture(node, subsequent); break; case RegexNodeKind.PositiveLookaround: EmitPositiveLookaroundAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaroundAssertion(node); break; case RegexNodeKind.Nothing: BrFar(doneLabel); break; case RegexNodeKind.Empty: // Emit nothing. break; case RegexNodeKind.UpdateBumpalong: EmitUpdateBumpalong(node); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } } // Emits the node for an atomic. void EmitAtomic(RegexNode node, RegexNode? subsequent) { Debug.Assert(node.Kind is RegexNodeKind.Atomic or RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); RegexNode child = node.Child(0); if (!analysis.MayBacktrack(child)) { // If the child has no backtracking, the atomic is a nop and we can just skip it. // Note that the source generator equivalent for this is in the top-level EmitNode, in order to avoid // outputting some extra comments and scopes. As such formatting isn't a concern for the compiler, // the logic is instead here in EmitAtomic. EmitNode(child, subsequent); return; } // Grab the current done label and the current backtracking position. The purpose of the atomic node // is to ensure that nodes after it that might backtrack skip over the atomic, which means after // rendering the atomic's child, we need to reset the label so that subsequent backtracking doesn't // see any label left set by the atomic's child. We also need to reset the backtracking stack position // so that the state on the stack remains consistent. Label originalDoneLabel = doneLabel; // int startingStackpos = stackpos; using RentedLocalBuilder startingStackpos = RentInt32Local(); Ldloc(stackpos); Stloc(startingStackpos); // Emit the child. EmitNode(child, subsequent); // Reset the stack position and done label. // stackpos = startingStackpos; Ldloc(startingStackpos); Stloc(stackpos); doneLabel = originalDoneLabel; } // Emits the code to handle updating base.runtextpos to pos in response to // an UpdateBumpalong node. This is used when we want to inform the scan loop that // it should bump from this location rather than from the original location. void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.UpdateBumpalong, $"Unexpected type: {node.Kind}"); // if (base.runtextpos < pos) // { // base.runtextpos = pos; // } TransferSliceStaticPosToPos(); Ldthisfld(s_runtextposField); Ldloc(pos); Label skipUpdate = DefineLabel(); Bge(skipUpdate); Ldthis(); Ldloc(pos); Stfld(s_runtextposField); MarkLabel(skipUpdate); } // Emits code for a concatenation void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChecksIfRequired) { Debug.Assert(node.Kind is RegexNodeKind.Concatenate, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() >= 2, $"Expected at least 2 children, found {node.ChildCount()}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // Emit the code for each child one after the other. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { // If we can find a subsequence of fixed-length children, we can emit a length check once for that sequence // and then skip the individual length checks for each. if (!rtl && emitLengthChecksIfRequired && node.TryGetJoinableLengthCheckChildRange(i, out int requiredLength, out int exclusiveEnd)) { EmitSpanLengthCheck(requiredLength); for (; i < exclusiveEnd; i++) { EmitNode(node.Child(i), GetSubsequent(i, node, subsequent), emitLengthChecksIfRequired: false); } i--; continue; } EmitNode(node.Child(i), GetSubsequent(i, node, subsequent)); } // Gets the node to treat as the subsequent one to node.Child(index) static RegexNode? GetSubsequent(int index, RegexNode node, RegexNode? subsequent) { int childCount = node.ChildCount(); for (int i = index + 1; i < childCount; i++) { RegexNode next = node.Child(i); if (next.Kind is not RegexNodeKind.UpdateBumpalong) // skip node types that don't have a semantic impact { return next; } } return subsequent; } } // Emits the code to handle a single-character match. void EmitSingleChar(RegexNode node, bool emitLengthCheck = true, LocalBuilder? offset = null) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; Debug.Assert(!rtl || offset is null); if (emitLengthCheck) { if (!rtl) { // if ((uint)(sliceStaticPos + offset) >= slice.Length) goto Done; EmitSpanLengthCheck(1, offset); } else { // if ((uint)(pos - 1) >= inputSpan.Length) goto Done; Ldloc(pos); Ldc(1); Sub(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); } } if (!rtl) { // slice[staticPos + offset] Ldloca(slice); EmitSum(sliceStaticPos, offset); } else { // inputSpan[pos - 1] Ldloca(inputSpan); EmitSum(-1, pos); } Call(s_spanGetItemMethod); LdindU2(); // if (loadedChar != ch) goto doneLabel; if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(doneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(doneLabel); } else // IsNotoneFamily { BeqFar(doneLabel); } } if (!rtl) { sliceStaticPos++; } else { // pos--; Ldloc(pos); Ldc(1); Sub(); Stloc(pos); } } // Emits the code to handle a boundary check on a character. void EmitBoundary(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Boundary or RegexNodeKind.NonBoundary or RegexNodeKind.ECMABoundary or RegexNodeKind.NonECMABoundary, $"Unexpected type: {node.Kind}"); if ((node.Options & RegexOptions.RightToLeft) != 0) { // RightToLeft doesn't use static position. This ensures it's 0. TransferSliceStaticPosToPos(); } // if (!IsBoundary(inputSpan, pos + sliceStaticPos)) goto doneLabel; Ldthis(); Ldloc(inputSpan); Ldloc(pos); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Add(); } switch (node.Kind) { case RegexNodeKind.Boundary: Call(s_isBoundaryMethod); BrfalseFar(doneLabel); break; case RegexNodeKind.NonBoundary: Call(s_isBoundaryMethod); BrtrueFar(doneLabel); break; case RegexNodeKind.ECMABoundary: Call(s_isECMABoundaryMethod); BrfalseFar(doneLabel); break; default: Debug.Assert(node.Kind == RegexNodeKind.NonECMABoundary); Call(s_isECMABoundaryMethod); BrtrueFar(doneLabel); break; } } // Emits the code to handle various anchors. void EmitAnchors(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.Bol or RegexNodeKind.End or RegexNodeKind.EndZ or RegexNodeKind.Eol, $"Unexpected type: {node.Kind}"); Debug.Assert((node.Options & RegexOptions.RightToLeft) == 0 || sliceStaticPos == 0); Debug.Assert(sliceStaticPos >= 0); Debug.Assert(sliceStaticPos >= 0); switch (node.Kind) { case RegexNodeKind.Beginning: case RegexNodeKind.Start: if (sliceStaticPos > 0) { // If we statically know we've already matched part of the regex, there's no way we're at the // beginning or start, as we've already progressed past it. BrFar(doneLabel); } else { // if (pos > 0/start) goto doneLabel; Ldloc(pos); if (node.Kind == RegexNodeKind.Beginning) { Ldc(0); } else { Ldthisfld(s_runtextstartField); } BneFar(doneLabel); } break; case RegexNodeKind.Bol: if (sliceStaticPos > 0) { // if (slice[sliceStaticPos - 1] != '\n') goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos - 1); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); } else { // We can't use our slice in this case, because we'd need to access slice[-1], so we access the inputSpan directly: // if (pos > 0 && inputSpan[pos - 1] != '\n') goto doneLabel; Label success = DefineLabel(); Ldloc(pos); Ldc(0); Ble(success); Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; case RegexNodeKind.End: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); } else { // if (pos < inputSpan.Length) goto doneLabel; Ldloc(pos); Ldloca(inputSpan); } Call(s_spanGetLengthMethod); BltUnFar(doneLabel); break; case RegexNodeKind.EndZ: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length - 1) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); } else { // if (pos < inputSpan.Length - 1) goto doneLabel Ldloc(pos); Ldloca(inputSpan); } Call(s_spanGetLengthMethod); Ldc(1); Sub(); BltFar(doneLabel); goto case RegexNodeKind.Eol; case RegexNodeKind.Eol: if (sliceStaticPos > 0) { // if (sliceStaticPos < slice.Length && slice[sliceStaticPos] != '\n') goto doneLabel; Label success = DefineLabel(); Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUn(success); Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } else { // if ((uint)pos < (uint)inputSpan.Length && inputSpan[pos] != '\n') goto doneLabel; Label success = DefineLabel(); Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUn(success); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); Ldc('\n'); BneFar(doneLabel); MarkLabel(success); } break; } } // Emits the code to handle a multiple-character match. void EmitMultiChar(RegexNode node, bool emitLengthCheck) { Debug.Assert(node.Kind is RegexNodeKind.Multi, $"Unexpected type: {node.Kind}"); EmitMultiCharString(node.Str!, IsCaseInsensitive(node), emitLengthCheck, (node.Options & RegexOptions.RightToLeft) != 0); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck, bool rightToLeft) { Debug.Assert(str.Length >= 2); if (rightToLeft) { Debug.Assert(emitLengthCheck); TransferSliceStaticPosToPos(); // if ((uint)(pos - str.Length) >= inputSpan.Length) goto doneLabel; Ldloc(pos); Ldc(str.Length); Sub(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); for (int i = str.Length - 1; i >= 0; i--) { // if (inputSpan[--pos] != str[str.Length - 1 - i]) goto doneLabel Ldloc(pos); Ldc(1); Sub(); Stloc(pos); Ldloca(inputSpan); Ldloc(pos); Call(s_spanGetItemMethod); LdindU2(); if (caseInsensitive) { CallToLower(); } Ldc(str[i]); BneFar(doneLabel); } return; } if (caseInsensitive) // StartsWith(..., XxIgnoreCase) won't necessarily be the same as char-by-char comparison { // This case should be relatively rare. It will only occur with IgnoreCase and a series of non-ASCII characters. if (emitLengthCheck) { EmitSpanLengthCheck(str.Length); } foreach (char c in str) { // if (c != slice[sliceStaticPos++]) goto doneLabel; EmitTextSpanOffset(); sliceStaticPos++; LdindU2(); CallToLower(); Ldc(c); BneFar(doneLabel); } } else { // if (!slice.Slice(sliceStaticPos).StartsWith("...") goto doneLabel; Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); Ldstr(str); Call(s_stringAsSpanMethod); Call(s_spanStartsWith); BrfalseFar(doneLabel); sliceStaticPos += str.Length; } } // Emits the code to handle a backtracking, single-character loop. void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop, $"Unexpected type: {node.Kind}"); // If this is actually atomic based on its parent, emit it as atomic instead; no backtracking necessary. if (analysis.IsAtomicByAncestor(node)) { EmitSingleCharAtomicLoop(node); return; } // If this is actually a repeater, emit that instead; no backtracking necessary. if (node.M == node.N) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); return; } // Emit backtracking around an atomic single char loop. We can then implement the backtracking // as an afterthought, since we know exactly how many characters are accepted by each iteration // of the wrapped loop (1) and that there's nothing captured by the loop. Debug.Assert(node.M < node.N); Label backtrackingLabel = DefineLabel(); Label endLoop = DefineLabel(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder endingPos = DeclareInt32(); LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // Grab the current position, then emit the loop as atomic, and then // grab the current position again. Even though we emit the loop without // knowledge of backtracking, we can layer it on top by just walking back // through the individual characters (a benefit of the loop matching exactly // one character per iteration, no possible captures within the loop, etc.) // int startingPos = pos; Ldloc(pos); Stloc(startingPos); EmitSingleCharAtomicLoop(node); // int endingPos = pos; TransferSliceStaticPosToPos(); Ldloc(pos); Stloc(endingPos); // int capturepos = base.Crawlpos(); if (capturepos is not null) { Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } // startingPos += node.M; // or -= for rtl if (node.M > 0) { Ldloc(startingPos); Ldc(!rtl ? node.M : -node.M); Add(); Stloc(startingPos); } // goto endLoop; BrFar(endLoop); // Backtracking section. Subsequent failures will jump to here, at which // point we decrement the matched count as long as it's above the minimum // required, and try again by flowing to everything that comes after this. MarkLabel(backtrackingLabel); if (capturepos is not null) { // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(capturepos); EmitUncaptureUntil(capturepos); } // endingPos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(endingPos); EmitStackPop(); Stloc(startingPos); // if (startingPos >= endingPos) goto doneLabel; // or <= for rtl Ldloc(startingPos); Ldloc(endingPos); if (!rtl) { BgeFar(doneLabel); } else { BleFar(doneLabel); } if (!rtl && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal) { // endingPos = inputSpan.Slice(startingPos, Math.Min(inputSpan.Length, endingPos + literal.Length - 1) - startingPos).LastIndexOf(literal); // if (endingPos < 0) // { // goto doneLabel; // } Ldloca(inputSpan); Ldloc(startingPos); if (literal.Item2 is not null) { Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(endingPos); Ldc(literal.Item2.Length - 1); Add(); Call(s_mathMinIntInt); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); Ldstr(literal.Item2); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfSpan); } else { Ldloc(endingPos); Ldloc(startingPos); Sub(); Call(s_spanSliceIntIntMethod); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanLastIndexOfAnyCharChar); break; case 3: Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Ldc(literal.Item3[2]); Call(s_spanLastIndexOfAnyCharCharChar); break; default: Ldstr(literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanLastIndexOfAnySpan); break; } } else { Ldc(literal.Item1); Call(s_spanLastIndexOfChar); } } Stloc(endingPos); Ldloc(endingPos); Ldc(0); BltFar(doneLabel); // endingPos += startingPos; Ldloc(endingPos); Ldloc(startingPos); Add(); Stloc(endingPos); } else { // endingPos--; // or ++ for rtl Ldloc(endingPos); Ldc(!rtl ? 1 : -1); Sub(); Stloc(endingPos); } // pos = endingPos; Ldloc(endingPos); Stloc(pos); if (!rtl) { // slice = inputSpan.Slice(pos); SliceInputSpan(); } MarkLabel(endLoop); EmitStackResizeIfNeeded(expressionHasCaptures ? 3 : 2); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(endingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos!)); } doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy, $"Unexpected type: {node.Kind}"); // Emit the min iterations as a repeater. Any failures here don't necessitate backtracking, // as the lazy itself failed to match, and there's no backtracking possible by the individual // characters/iterations themselves. if (node.M > 0) { EmitSingleCharRepeater(node, emitLengthChecksIfRequired); } // If the whole thing was actually that repeater, we're done. Similarly, if this is actually an atomic // lazy loop, nothing will ever backtrack into this node, so we never need to iterate more than the minimum. if (node.M == node.N || analysis.IsAtomicByAncestor(node)) { return; } Debug.Assert(node.M < node.N); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; // We now need to match one character at a time, each time allowing the remainder of the expression // to try to match, and only matching another character if the subsequent expression fails to match. // We're about to enter a loop, so ensure our text position is 0. TransferSliceStaticPosToPos(); // If the loop isn't unbounded, track the number of iterations and the max number to allow. LocalBuilder? iterationCount = null; int? maxIterations = null; if (node.N != int.MaxValue) { maxIterations = node.N - node.M; // int iterationCount = 0; iterationCount = DeclareInt32(); Ldc(0); Stloc(iterationCount); } // Track the current crawl position. Upon backtracking, we'll unwind any captures beyond this point. LocalBuilder? capturepos = expressionHasCaptures ? DeclareInt32() : null; // Track the current pos. Each time we backtrack, we'll reset to the stored position, which // is also incremented each time we match another character in the loop. // int startingPos = pos; LocalBuilder startingPos = DeclareInt32(); Ldloc(pos); Stloc(startingPos); // Skip the backtracking section for the initial subsequent matching. We've already matched the // minimum number of iterations, which means we can successfully match with zero additional iterations. // goto endLoopLabel; Label endLoopLabel = DefineLabel(); BrFar(endLoopLabel); // Backtracking section. Subsequent failures will jump to here. Label backtrackingLabel = DefineLabel(); MarkLabel(backtrackingLabel); // Uncapture any captures if the expression has any. It's possible the captures it has // are before this node, in which case this is wasted effort, but still functionally correct. if (capturepos is not null) { // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitUncaptureUntil(capturepos); } // If there's a max number of iterations, see if we've exceeded the maximum number of characters // to match. If we haven't, increment the iteration count. if (maxIterations is not null) { // if (iterationCount >= maxIterations) goto doneLabel; Ldloc(iterationCount!); Ldc(maxIterations.Value); BgeFar(doneLabel); // iterationCount++; Ldloc(iterationCount!); Ldc(1); Add(); Stloc(iterationCount!); } // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. // pos = startingPos; // Match single char; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); EmitSingleChar(node); TransferSliceStaticPosToPos(); // Now that we've appropriately advanced by one character and are set for what comes after the loop, // see if we can skip ahead more iterations by doing a search for a following literal. if (!rtl && iterationCount is null && node.Kind is RegexNodeKind.Notonelazy && !IsCaseInsensitive(node) && subsequent?.FindStartingLiteral(4) is ValueTuple<char, string?, string?> literal && // 5 == max optimized by IndexOfAny, and we need to reserve 1 for node.Ch (literal.Item3 is not null ? !literal.Item3.Contains(node.Ch) : (literal.Item2?[0] ?? literal.Item1) != node.Ch)) // no overlap between node.Ch and the start of the literal { // e.g. "<[^>]*?>" // This lazy loop will consume all characters other than node.Ch until the subsequent literal. // We can implement it to search for either that char or the literal, whichever comes first. // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). // startingPos = slice.IndexOfAny(node.Ch, literal); Ldloc(slice); if (literal.Item3 is not null) { switch (literal.Item3.Length) { case 2: Ldc(node.Ch); Ldc(literal.Item3[0]); Ldc(literal.Item3[1]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(node.Ch + literal.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(node.Ch); Ldc(literal.Item2?[0] ?? literal.Item1); Call(s_spanIndexOfAnyCharChar); } Stloc(startingPos); // if ((uint)startingPos >= (uint)slice.Length) goto doneLabel; Ldloc(startingPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(doneLabel); // if (slice[startingPos] == node.Ch) goto doneLabel; Ldloca(slice); Ldloc(startingPos); Call(s_spanGetItemMethod); LdindU2(); Ldc(node.Ch); BeqFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } else if (!rtl && iterationCount is null && node.Kind is RegexNodeKind.Setlazy && node.Str == RegexCharClass.AnyClass && subsequent?.FindStartingLiteral() is ValueTuple<char, string?, string?> literal2) { // e.g. ".*?string" with RegexOptions.Singleline // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal // isn't found, the loop fails. We can implement it to just search for that literal. // startingPos = slice.IndexOf(literal); Ldloc(slice); if (literal2.Item2 is not null) { Ldstr(literal2.Item2); Call(s_stringAsSpanMethod); Call(s_spanIndexOfSpan); } else if (literal2.Item3 is not null) { switch (literal2.Item3.Length) { case 2: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(literal2.Item3[0]); Ldc(literal2.Item3[1]); Ldc(literal2.Item3[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(literal2.Item3); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } } else { Ldc(literal2.Item1); Call(s_spanIndexOfChar); } Stloc(startingPos); // if (startingPos < 0) goto doneLabel; Ldloc(startingPos); Ldc(0); BltFar(doneLabel); // pos += startingPos; // slice = inputSpace.Slice(pos); Ldloc(pos); Ldloc(startingPos); Add(); Stloc(pos); SliceInputSpan(); } // Store the position we've left off at in case we need to iterate again. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Update the done label for everything that comes after this node. This is done after we emit the single char // matching, as that failing indicates the loop itself has failed to match. Label originalDoneLabel = doneLabel; doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes MarkLabel(endLoopLabel); if (capturepos is not null) { // capturepos = base.CrawlPos(); Ldthis(); Call(s_crawlposMethod); Stloc(capturepos); } if (node.IsInLoop()) { // Store the loop's state // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = capturepos; // base.runstack[stackpos++] = iterationCount; EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); if (capturepos is not null) { EmitStackPush(() => Ldloc(capturepos)); } if (iterationCount is not null) { EmitStackPush(() => Ldloc(iterationCount)); } // Skip past the backtracking section Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; if (iterationCount is not null) { EmitStackPop(); Stloc(iterationCount); } if (capturepos is not null) { EmitStackPop(); Stloc(capturepos); } EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } void EmitLazy(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; Label originalDoneLabel = doneLabel; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually an atomic lazy loop, we need to output just the minimum number of iterations, // as nothing will backtrack into the lazy loop to get it progress further. if (isAtomic) { switch (minIterations) { case 0: // Atomic lazy with a min count of 0: nop. return; case 1: // Atomic lazy with a min count of 1: just output the child, no looping required. EmitNode(node.Child(0)); return; } } // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); LocalBuilder sawEmpty = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = pos; // sawEmpty = 0; // false Ldc(0); Stloc(iterationCount); Ldloc(pos); Stloc(startingPos); Ldc(0); Stloc(sawEmpty); // If the min count is 0, start out by jumping right to what's after the loop. Backtracking // will then bring us back in to do further iterations. if (minIterations == 0) { // goto endLoop; BrFar(endLoop); } // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. // base.runstack[stackpos++] = base.Crawlpos(); // base.runstack[stackpos++] = startingPos; // base.runstack[stackpos++] = pos; // base.runstack[stackpos++] = sawEmpty; EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); EmitStackPush(() => Ldloc(sawEmpty)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 if (doneLabel == iterationFailedLabel) { doneLabel = originalDoneLabel; } // Loop condition. Continue iterating if we've not yet reached the minimum. if (minIterations > 0) { // if (iterationCount < minIterations) goto body; Ldloc(iterationCount); Ldc(minIterations); BltFar(body); } // If the last iteration was empty, we need to prevent further iteration from this point // unless we backtrack out of this iteration. We can do that easily just by pretending // we reached the max iteration count. // if (pos == startingPos) sawEmpty = 1; // true Label skipSawEmptySet = DefineLabel(); Ldloc(pos); Ldloc(startingPos); Bne(skipSawEmptySet); Ldc(1); Stloc(sawEmpty); MarkLabel(skipSawEmptySet); // We matched the next iteration. Jump to the subsequent code. // goto endLoop; BrFar(endLoop); // Now handle what happens when an iteration fails. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // sawEmpty = base.runstack[--stackpos]; // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; // capturepos = base.runstack[--stackpos]; // while (base.Crawlpos() > capturepos) base.Uncapture(); EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (doneLabel == originalDoneLabel) { // goto originalDoneLabel; BrFar(originalDoneLabel); } else { // if (iterationCount == 0) goto originalDoneLabel; // goto doneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); BrFar(doneLabel); } MarkLabel(endLoop); if (!isAtomic) { // Store the capture's state and skip the backtracking section EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); EmitStackPush(() => Ldloc(sawEmpty)); Label skipBacktrack = DefineLabel(); BrFar(skipBacktrack); // Emit a backtracking section that restores the capture's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // sawEmpty = base.runstack[--stackpos]; // iterationCount = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(sawEmpty); EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); if (maxIterations == int.MaxValue) { // if (sawEmpty != 0) goto doneLabel; Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } else { // if (iterationCount >= maxIterations || sawEmpty != 0) goto doneLabel; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(doneLabel); Ldloc(sawEmpty); Ldc(0); BneFar(doneLabel); } // goto body; BrFar(body); doneLabel = backtrack; MarkLabel(skipBacktrack); } } // Emits the code to handle a loop (repeater) with a fixed number of iterations. // RegexNode.M is used for the number of iterations (RegexNode.N is ignored), as this // might be used to implement the required iterations of other kinds of loops. void EmitSingleCharRepeater(RegexNode node, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.IsOneFamily || node.IsNotoneFamily || node.IsSetFamily, $"Unexpected type: {node.Kind}"); int iterations = node.M; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; switch (iterations) { case 0: // No iterations, nothing to do. return; case 1: // Just match the individual item EmitSingleChar(node, emitLengthChecksIfRequired); return; case <= RegexNode.MultiVsRepeaterLimit when node.IsOneFamily && !IsCaseInsensitive(node): // This is a repeated case-sensitive character; emit it as a multi in order to get all the optimizations // afforded to a multi, e.g. unrolling the loop with multi-char reads/comparisons at a time. EmitMultiCharString(new string(node.Ch, iterations), caseInsensitive: false, emitLengthChecksIfRequired, rtl); return; } if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position with rtl Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // for (int i = 0; ...) using RentedLocalBuilder iterationLocal = RentInt32Local(); Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // TimeoutCheck(); // HandleSingleChar(); MarkLabel(bodyLabel); EmitTimeoutCheck(); EmitSingleChar(node); // for (...; ...; i++) Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // for (...; i < iterations; ...) MarkLabel(conditionLabel); Ldloc(iterationLocal); Ldc(iterations); BltFar(bodyLabel); return; } // if ((uint)(sliceStaticPos + iterations - 1) >= (uint)slice.Length) goto doneLabel; if (emitLengthChecksIfRequired) { EmitSpanLengthCheck(iterations); } // Arbitrary limit for unrolling vs creating a loop. We want to balance size in the generated // code with other costs, like the (small) overhead of slicing to create the temp span to iterate. const int MaxUnrollSize = 16; if (iterations <= MaxUnrollSize) { // if (slice[sliceStaticPos] != c1 || // slice[sliceStaticPos + 1] != c2 || // ...) // goto doneLabel; for (int i = 0; i < iterations; i++) { EmitSingleChar(node, emitLengthCheck: false); } } else { // ReadOnlySpan<char> tmp = slice.Slice(sliceStaticPos, iterations); // for (int i = 0; i < tmp.Length; i++) // { // TimeoutCheck(); // if (tmp[i] != ch) goto Done; // } // sliceStaticPos += iterations; Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); using RentedLocalBuilder spanLocal = RentReadOnlySpanCharLocal(); Ldloca(slice); Ldc(sliceStaticPos); Ldc(iterations); Call(s_spanSliceIntIntMethod); Stloc(spanLocal); using RentedLocalBuilder iterationLocal = RentInt32Local(); Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); MarkLabel(bodyLabel); EmitTimeoutCheck(); LocalBuilder tmpTextSpanLocal = slice; // we want EmitSingleChar to refer to this temporary int tmpTextSpanPos = sliceStaticPos; slice = spanLocal; sliceStaticPos = 0; EmitSingleChar(node, emitLengthCheck: false, offset: iterationLocal); slice = tmpTextSpanLocal; sliceStaticPos = tmpTextSpanPos; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); MarkLabel(conditionLabel); Ldloc(iterationLocal); Ldloca(spanLocal); Call(s_spanGetLengthMethod); BltFar(bodyLabel); sliceStaticPos += iterations; } } // Emits the code to handle a non-backtracking, variable-length loop around a single character comparison. void EmitSingleCharAtomicLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); // If this is actually a repeater, emit that instead. if (node.M == node.N) { EmitSingleCharRepeater(node); return; } // If this is actually an optional single char, emit that instead. if (node.M == 0 && node.N == 1) { EmitAtomicSingleCharZeroOrOne(node); return; } Debug.Assert(node.N > node.M); int minIterations = node.M; int maxIterations = node.N; bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; using RentedLocalBuilder iterationLocal = RentInt32Local(); Label atomicLoopDoneLabel = DefineLabel(); Span<char> setChars = stackalloc char[5]; // max optimized by IndexOfAny today int numSetChars = 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static position for rtl Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // int i = 0; Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // Body: // TimeoutCheck(); MarkLabel(bodyLabel); EmitTimeoutCheck(); // if (pos <= iterationLocal) goto atomicLoopDoneLabel; Ldloc(pos); Ldloc(iterationLocal); BleFar(atomicLoopDoneLabel); // if (inputSpan[pos - i - 1] != ch) goto atomicLoopDoneLabel; Ldloca(inputSpan); Ldloc(pos); Ldloc(iterationLocal); Sub(); Ldc(1); Sub(); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(atomicLoopDoneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(atomicLoopDoneLabel); } else // IsNotoneFamily { BeqFar(atomicLoopDoneLabel); } } // i++; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // if (i >= maxIterations) goto atomicLoopDoneLabel; MarkLabel(conditionLabel); if (maxIterations != int.MaxValue) { Ldloc(iterationLocal); Ldc(maxIterations); BltFar(bodyLabel); } else { BrFar(bodyLabel); } } else if (node.IsNotoneFamily && maxIterations == int.MaxValue && (!IsCaseInsensitive(node))) { // For Notone, we're looking for a specific character, as everything until we find // it is consumed by the loop. If we're unbounded, such as with ".*" and if we're case-sensitive, // we can use the vectorized IndexOf to do the search, rather than open-coding it. The unbounded // restriction is purely for simplicity; it could be removed in the future with additional code to // handle the unbounded case. // int i = slice.Slice(sliceStaticPos).IndexOf(char); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } Ldc(node.Ch); Call(s_spanIndexOfChar); Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && !IsCaseInsensitive(node) && (numSetChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0 && RegexCharClass.IsNegated(node.Str!)) { // If the set is negated and contains only a few characters (if it contained 1 and was negated, it would // have been reduced to a Notone), we can use an IndexOfAny to find any of the target characters. // As with the notoneloopatomic above, the unbounded constraint is purely for simplicity. Debug.Assert(numSetChars > 1); // int i = slice.Slice(sliceStaticPos).IndexOfAny(ch1, ch2, ...); if (sliceStaticPos > 0) { Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); } else { Ldloc(slice); } switch (numSetChars) { case 2: Ldc(setChars[0]); Ldc(setChars[1]); Call(s_spanIndexOfAnyCharChar); break; case 3: Ldc(setChars[0]); Ldc(setChars[1]); Ldc(setChars[2]); Call(s_spanIndexOfAnyCharCharChar); break; default: Ldstr(setChars.Slice(0, numSetChars).ToString()); Call(s_stringAsSpanMethod); Call(s_spanIndexOfAnySpan); break; } Stloc(iterationLocal); // if (i >= 0) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldc(0); BgeFar(atomicLoopDoneLabel); // i = slice.Length - sliceStaticPos; Ldloca(slice); Call(s_spanGetLengthMethod); if (sliceStaticPos > 0) { Ldc(sliceStaticPos); Sub(); } Stloc(iterationLocal); } else if (node.IsSetFamily && maxIterations == int.MaxValue && node.Str == RegexCharClass.AnyClass) { // .* was used with RegexOptions.Singleline, which means it'll consume everything. Just jump to the end. // The unbounded constraint is the same as in the Notone case above, done purely for simplicity. // int i = inputSpan.Length - pos; TransferSliceStaticPosToPos(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Ldloc(pos); Sub(); Stloc(iterationLocal); } else { // For everything else, do a normal loop. // Transfer sliceStaticPos to pos to help with bounds check elimination on the loop. TransferSliceStaticPosToPos(); Label conditionLabel = DefineLabel(); Label bodyLabel = DefineLabel(); // int i = 0; Ldc(0); Stloc(iterationLocal); BrFar(conditionLabel); // Body: // TimeoutCheck(); MarkLabel(bodyLabel); EmitTimeoutCheck(); // if ((uint)i >= (uint)slice.Length) goto atomicLoopDoneLabel; Ldloc(iterationLocal); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(atomicLoopDoneLabel); // if (slice[i] != ch) goto atomicLoopDoneLabel; Ldloca(slice); Ldloc(iterationLocal); Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(atomicLoopDoneLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(atomicLoopDoneLabel); } else // IsNotoneFamily { BeqFar(atomicLoopDoneLabel); } } // i++; Ldloc(iterationLocal); Ldc(1); Add(); Stloc(iterationLocal); // if (i >= maxIterations) goto atomicLoopDoneLabel; MarkLabel(conditionLabel); if (maxIterations != int.MaxValue) { Ldloc(iterationLocal); Ldc(maxIterations); BltFar(bodyLabel); } else { BrFar(bodyLabel); } } // Done: MarkLabel(atomicLoopDoneLabel); // Check to ensure we've found at least min iterations. if (minIterations > 0) { Ldloc(iterationLocal); Ldc(minIterations); BltFar(doneLabel); } // Now that we've completed our optional iterations, advance the text span // and pos by the number of iterations completed. if (!rtl) { // slice = slice.Slice(i); Ldloca(slice); Ldloc(iterationLocal); Call(s_spanSliceIntMethod); Stloc(slice); // pos += i; Ldloc(pos); Ldloc(iterationLocal); Add(); Stloc(pos); } else { // pos -= i; Ldloc(pos); Ldloc(iterationLocal); Sub(); Stloc(pos); } } // Emits the code to handle a non-backtracking optional zero-or-one loop. void EmitAtomicSingleCharZeroOrOne(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M == 0 && node.N == 1); bool rtl = (node.Options & RegexOptions.RightToLeft) != 0; if (rtl) { TransferSliceStaticPosToPos(); // we don't use static pos for rtl } Label skipUpdatesLabel = DefineLabel(); if (!rtl) { // if ((uint)sliceStaticPos >= (uint)slice.Length) goto skipUpdatesLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(skipUpdatesLabel); } else { // if (pos == 0) goto skipUpdatesLabel; Ldloc(pos); Ldc(0); BeqFar(skipUpdatesLabel); } if (!rtl) { // if (slice[sliceStaticPos] != ch) goto skipUpdatesLabel; Ldloca(slice); Ldc(sliceStaticPos); } else { // if (inputSpan[pos - 1] != ch) goto skipUpdatesLabel; Ldloca(inputSpan); Ldloc(pos); Ldc(1); Sub(); } Call(s_spanGetItemMethod); LdindU2(); if (node.IsSetFamily) { EmitMatchCharacterClass(node.Str!, IsCaseInsensitive(node)); BrfalseFar(skipUpdatesLabel); } else { if (IsCaseInsensitive(node)) { CallToLower(); } Ldc(node.Ch); if (node.IsOneFamily) { BneFar(skipUpdatesLabel); } else // IsNotoneFamily { BeqFar(skipUpdatesLabel); } } if (!rtl) { // slice = slice.Slice(1); Ldloca(slice); Ldc(1); Call(s_spanSliceIntMethod); Stloc(slice); // pos++; Ldloc(pos); Ldc(1); Add(); Stloc(pos); } else { // pos--; Ldloc(pos); Ldc(1); Sub(); Stloc(pos); } MarkLabel(skipUpdatesLabel); } void EmitNonBacktrackingRepeater(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.M == node.N, $"Unexpected M={node.M} == N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Debug.Assert(!analysis.MayBacktrack(node.Child(0)), $"Expected non-backtracking node {node.Kind}"); // Ensure every iteration of the loop sees a consistent value. TransferSliceStaticPosToPos(); // Loop M==N times to match the child exactly that numbers of times. Label condition = DefineLabel(); Label body = DefineLabel(); // for (int i = 0; ...) using RentedLocalBuilder i = RentInt32Local(); Ldc(0); Stloc(i); BrFar(condition); MarkLabel(body); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // make sure static the static position remains at 0 for subsequent constructs // for (...; ...; i++) Ldloc(i); Ldc(1); Add(); Stloc(i); // for (...; i < node.M; ...) MarkLabel(condition); Ldloc(i); Ldc(node.M); BltFar(body); } void EmitLoop(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop, $"Unexpected type: {node.Kind}"); Debug.Assert(node.M < int.MaxValue, $"Unexpected M={node.M}"); Debug.Assert(node.N >= node.M, $"Unexpected M={node.M}, N={node.N}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); int minIterations = node.M; int maxIterations = node.N; bool isAtomic = analysis.IsAtomicByAncestor(node); // If this is actually a repeater and the child doesn't have any backtracking in it that might // cause us to need to unwind already taken iterations, just output it as a repeater loop. if (minIterations == maxIterations && !analysis.MayBacktrack(node.Child(0))) { EmitNonBacktrackingRepeater(node); return; } // We might loop any number of times. In order to ensure this loop and subsequent code sees sliceStaticPos // the same regardless, we always need it to contain the same value, and the easiest such value is 0. // So, we transfer sliceStaticPos to pos, and ensure that any path out of here has sliceStaticPos as 0. TransferSliceStaticPosToPos(); Label originalDoneLabel = doneLabel; LocalBuilder startingPos = DeclareInt32(); LocalBuilder iterationCount = DeclareInt32(); Label body = DefineLabel(); Label endLoop = DefineLabel(); // iterationCount = 0; // startingPos = 0; Ldc(0); Stloc(iterationCount); Ldc(0); Stloc(startingPos); // Iteration body MarkLabel(body); EmitTimeoutCheck(); // We need to store the starting pos and crawl position so that it may // be backtracked through later. This needs to be the starting position from // the iteration we're leaving, so it's pushed before updating it to pos. EmitStackResizeIfNeeded(3); if (expressionHasCaptures) { // base.runstack[stackpos++] = base.Crawlpos(); EmitStackPush(() => { Ldthis(); Call(s_crawlposMethod); }); } EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(pos)); // Save off some state. We need to store the current pos so we can compare it against // pos after the iteration, in order to determine whether the iteration was empty. Empty // iterations are allowed as part of min matches, but once we've met the min quote, empty matches // are considered match failures. // startingPos = pos; Ldloc(pos); Stloc(startingPos); // Proactively increase the number of iterations. We do this prior to the match rather than once // we know it's successful, because we need to decrement it as part of a failed match when // backtracking; it's thus simpler to just always decrement it as part of a failed match, even // when initially greedily matching the loop, which then requires we increment it before trying. // iterationCount++; Ldloc(iterationCount); Ldc(1); Add(); Stloc(iterationCount); // Last but not least, we need to set the doneLabel that a failed match of the body will jump to. // Such an iteration match failure may or may not fail the whole operation, depending on whether // we've already matched the minimum required iterations, so we need to jump to a location that // will make that determination. Label iterationFailedLabel = DefineLabel(); doneLabel = iterationFailedLabel; // Finally, emit the child. Debug.Assert(sliceStaticPos == 0); EmitNode(node.Child(0)); TransferSliceStaticPosToPos(); // ensure sliceStaticPos remains 0 bool childBacktracks = doneLabel != iterationFailedLabel; // Loop condition. Continue iterating greedily if we've not yet reached the maximum. We also need to stop // iterating if the iteration matched empty and we already hit the minimum number of iterations. Otherwise, // we've matched as many iterations as we can with this configuration. Jump to what comes after the loop. switch ((minIterations > 0, maxIterations == int.MaxValue)) { case (true, true): // if (pos != startingPos || iterationCount < minIterations) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (true, false): // if ((pos != startingPos || iterationCount < minIterations) && iterationCount < maxIterations) goto body; // goto endLoop; Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); Ldloc(pos); Ldloc(startingPos); BneFar(body); Ldloc(iterationCount); Ldc(minIterations); BltFar(body); BrFar(endLoop); break; case (false, true): // if (pos != startingPos) goto body; // goto endLoop; Ldloc(pos); Ldloc(startingPos); BneFar(body); BrFar(endLoop); break; case (false, false): // if (pos == startingPos || iterationCount >= maxIterations) goto endLoop; // goto body; Ldloc(pos); Ldloc(startingPos); BeqFar(endLoop); Ldloc(iterationCount); Ldc(maxIterations); BgeFar(endLoop); BrFar(body); break; } // Now handle what happens when an iteration fails, which could be an initial failure or it // could be while backtracking. We need to reset state to what it was before just that iteration // started. That includes resetting pos and clearing out any captures from that iteration. MarkLabel(iterationFailedLabel); // iterationCount--; Ldloc(iterationCount); Ldc(1); Sub(); Stloc(iterationCount); // if (iterationCount < 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BltFar(originalDoneLabel); // pos = base.runstack[--stackpos]; // startingPos = base.runstack[--stackpos]; EmitStackPop(); Stloc(pos); EmitStackPop(); Stloc(startingPos); if (expressionHasCaptures) { // int poppedCrawlPos = base.runstack[--stackpos]; // while (base.Crawlpos() > poppedCrawlPos) base.Uncapture(); using RentedLocalBuilder poppedCrawlPos = RentInt32Local(); EmitStackPop(); Stloc(poppedCrawlPos); EmitUncaptureUntil(poppedCrawlPos); } SliceInputSpan(); if (minIterations > 0) { // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // if (iterationCount < minIterations) goto doneLabel/originalDoneLabel; Ldloc(iterationCount); Ldc(minIterations); BltFar(childBacktracks ? doneLabel : originalDoneLabel); } if (isAtomic) { doneLabel = originalDoneLabel; MarkLabel(endLoop); } else { if (childBacktracks) { // goto endLoop; BrFar(endLoop); // Backtrack: Label backtrack = DefineLabel(); MarkLabel(backtrack); // if (iterationCount == 0) goto originalDoneLabel; Ldloc(iterationCount); Ldc(0); BeqFar(originalDoneLabel); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; } MarkLabel(endLoop); if (node.IsInLoop()) { // Store the loop's state EmitStackResizeIfNeeded(3); EmitStackPush(() => Ldloc(startingPos)); EmitStackPush(() => Ldloc(iterationCount)); // Skip past the backtracking section // goto backtrackingEnd; Label backtrackingEnd = DefineLabel(); BrFar(backtrackingEnd); // Emit a backtracking section that restores the loop's state and then jumps to the previous done label Label backtrack = DefineLabel(); MarkLabel(backtrack); // iterationCount = base.runstack[--runstack]; // startingPos = base.runstack[--runstack]; EmitStackPop(); Stloc(iterationCount); EmitStackPop(); Stloc(startingPos); // goto doneLabel; BrFar(doneLabel); doneLabel = backtrack; MarkLabel(backtrackingEnd); } } } void EmitStackResizeIfNeeded(int count) { Debug.Assert(count >= 1); // if (stackpos >= base.runstack!.Length - (count - 1)) // { // Array.Resize(ref base.runstack, base.runstack.Length * 2); // } Label skipResize = DefineLabel(); Ldloc(stackpos); Ldthisfld(s_runstackField); Ldlen(); if (count > 1) { Ldc(count - 1); Sub(); } Blt(skipResize); Ldthis(); _ilg!.Emit(OpCodes.Ldflda, s_runstackField); Ldthisfld(s_runstackField); Ldlen(); Ldc(2); Mul(); Call(s_arrayResize); MarkLabel(skipResize); } void EmitStackPush(Action load) { // base.runstack[stackpos] = load(); Ldthisfld(s_runstackField); Ldloc(stackpos); load(); StelemI4(); // stackpos++; Ldloc(stackpos); Ldc(1); Add(); Stloc(stackpos); } void EmitStackPop() { // ... = base.runstack[--stackpos]; Ldthisfld(s_runstackField); Ldloc(stackpos); Ldc(1); Sub(); Stloc(stackpos); Ldloc(stackpos); LdelemI4(); } } protected void EmitScan(RegexOptions options, DynamicMethod tryFindNextStartingPositionMethod, DynamicMethod tryMatchAtCurrentPositionMethod) { bool rtl = (options & RegexOptions.RightToLeft) != 0; Label returnLabel = DefineLabel(); // while (TryFindNextPossibleStartingPosition(text)) Label whileLoopBody = DefineLabel(); MarkLabel(whileLoopBody); Ldthis(); Ldarg_1(); Call(tryFindNextStartingPositionMethod); BrfalseFar(returnLabel); if (_hasTimeout) { // CheckTimeout(); Ldthis(); Call(s_checkTimeoutMethod); } // if (TryMatchAtCurrentPosition(text) || runtextpos == text.length) // or == 0 for rtl // return; Ldthis(); Ldarg_1(); Call(tryMatchAtCurrentPositionMethod); BrtrueFar(returnLabel); Ldthisfld(s_runtextposField); if (!rtl) { Ldarga_s(1); Call(s_spanGetLengthMethod); } else { Ldc(0); } Ceq(); BrtrueFar(returnLabel); // runtextpos += 1 // or -1 for rtl Ldthis(); Ldthisfld(s_runtextposField); Ldc(!rtl ? 1 : -1); Add(); Stfld(s_runtextposField); // End loop body. BrFar(whileLoopBody); // return; MarkLabel(returnLabel); Ret(); } private void InitializeCultureForTryMatchAtCurrentPositionIfNecessary(AnalysisResults analysis) { _textInfo = null; if (analysis.HasIgnoreCase && (_options & RegexOptions.CultureInvariant) == 0) { // cache CultureInfo in local variable which saves excessive thread local storage accesses _textInfo = DeclareTextInfo(); InitLocalCultureInfo(); } } /// <summary>Emits a a check for whether the character is in the specified character class.</summary> /// <remarks>The character to be checked has already been loaded onto the stack.</remarks> private void EmitMatchCharacterClass(string charClass, bool caseInsensitive) { // We need to perform the equivalent of calling RegexRunner.CharInClass(ch, charClass), // but that call is relatively expensive. Before we fall back to it, we try to optimize // some common cases for which we can do much better, such as known character classes // for which we can call a dedicated method, or a fast-path for ASCII using a lookup table. // First, see if the char class is a built-in one for which there's a better function // we can just call directly. Everything in this section must work correctly for both // case-sensitive and case-insensitive modes, regardless of culture. switch (charClass) { case RegexCharClass.AnyClass: // true Pop(); Ldc(1); return; case RegexCharClass.DigitClass: // char.IsDigit(ch) Call(s_charIsDigitMethod); return; case RegexCharClass.NotDigitClass: // !char.IsDigit(ch) Call(s_charIsDigitMethod); Ldc(0); Ceq(); return; case RegexCharClass.SpaceClass: // char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); return; case RegexCharClass.NotSpaceClass: // !char.IsWhiteSpace(ch) Call(s_charIsWhiteSpaceMethod); Ldc(0); Ceq(); return; case RegexCharClass.WordClass: // RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); return; case RegexCharClass.NotWordClass: // !RegexRunner.IsWordChar(ch) Call(s_isWordCharMethod); Ldc(0); Ceq(); return; } // If we're meant to be doing a case-insensitive lookup, and if we're not using the invariant culture, // lowercase the input. If we're using the invariant culture, we may still end up calling ToLower later // on, but we may also be able to avoid it, in particular in the case of our lookup table, where we can // generate the lookup table already factoring in the invariant case sensitivity. There are multiple // special-code paths between here and the lookup table, but we only take those if invariant is false; // if it were true, they'd need to use CallToLower(). bool invariant = false; if (caseInsensitive) { invariant = UseToLowerInvariant; if (!invariant) { CallToLower(); } } // Next, handle simple sets of one range, e.g. [A-Z], [0-9], etc. This includes some built-in classes, like ECMADigitClass. if (!invariant && RegexCharClass.TryGetSingleRange(charClass, out char lowInclusive, out char highInclusive)) { if (lowInclusive == highInclusive) { // ch == charClass[3] Ldc(lowInclusive); Ceq(); } else { // (uint)ch - lowInclusive < highInclusive - lowInclusive + 1 Ldc(lowInclusive); Sub(); Ldc(highInclusive - lowInclusive + 1); CltUn(); } // Negate the answer if the negation flag was set if (RegexCharClass.IsNegated(charClass)) { Ldc(0); Ceq(); } return; } // Next if the character class contains nothing but a single Unicode category, we can calle char.GetUnicodeCategory and // compare against it. It has a fast-lookup path for ASCII, so is as good or better than any lookup we'd generate (plus // we get smaller code), and it's what we'd do for the fallback (which we get to avoid generating) as part of CharInClass. if (!invariant && RegexCharClass.TryGetSingleUnicodeCategory(charClass, out UnicodeCategory category, out bool negated)) { // char.GetUnicodeCategory(ch) == category Call(s_charGetUnicodeInfo); Ldc((int)category); Ceq(); if (negated) { Ldc(0); Ceq(); } return; } // All checks after this point require reading the input character multiple times, // so we store it into a temporary local. using RentedLocalBuilder tempLocal = RentInt32Local(); Stloc(tempLocal); // Next, if there's only 2 or 3 chars in the set (fairly common due to the sets we create for prefixes), // it's cheaper and smaller to compare against each than it is to use a lookup table. if (!invariant && !RegexCharClass.IsNegated(charClass)) { Span<char> setChars = stackalloc char[3]; int numChars = RegexCharClass.GetSetChars(charClass, setChars); if (numChars is 2 or 3) { if (RegexCharClass.DifferByOneBit(setChars[0], setChars[1], out int mask)) // special-case common case of an upper and lowercase ASCII letter combination { // ((ch | mask) == setChars[1]) Ldloc(tempLocal); Ldc(mask); Or(); Ldc(setChars[1] | mask); Ceq(); } else { // (ch == setChars[0]) | (ch == setChars[1]) Ldloc(tempLocal); Ldc(setChars[0]); Ceq(); Ldloc(tempLocal); Ldc(setChars[1]); Ceq(); Or(); } // | (ch == setChars[2]) if (numChars == 3) { Ldloc(tempLocal); Ldc(setChars[2]); Ceq(); Or(); } return; } } using RentedLocalBuilder resultLocal = RentInt32Local(); // Analyze the character set more to determine what code to generate. RegexCharClass.CharClassAnalysisResults analysis = RegexCharClass.Analyze(charClass); // Helper method that emits a call to RegexRunner.CharInClass(ch{.ToLowerInvariant()}, charClass) void EmitCharInClass() { Ldloc(tempLocal); if (invariant) { CallToLower(); } Ldstr(charClass); Call(s_charInClassMethod); Stloc(resultLocal); } Label doneLabel = DefineLabel(); Label comparisonLabel = DefineLabel(); if (!invariant) // if we're being asked to do a case insensitive, invariant comparison, use the lookup table { if (analysis.ContainsNoAscii) { // We determined that the character class contains only non-ASCII, // for example if the class were [\p{IsGreek}\p{IsGreekExtended}], which is // the same as [\u0370-\u03FF\u1F00-1FFF]. (In the future, we could possibly // extend the analysis to produce a known lower-bound and compare against // that rather than always using 128 as the pivot point.) // ch >= 128 && RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(0); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } if (analysis.AllAsciiContained) { // We determined that every ASCII character is in the class, for example // if the class were the negated example from case 1 above: // [^\p{IsGreek}\p{IsGreekExtended}]. // ch < 128 || RegexRunner.CharInClass(ch, "...") Ldloc(tempLocal); Ldc(128); Blt(comparisonLabel); EmitCharInClass(); Br(doneLabel); MarkLabel(comparisonLabel); Ldc(1); Stloc(resultLocal); MarkLabel(doneLabel); Ldloc(resultLocal); return; } } // Now, our big hammer is to generate a lookup table that lets us quickly index by character into a yes/no // answer as to whether the character is in the target character class. However, we don't want to store // a lookup table for every possible character for every character class in the regular expression; at one // bit for each of 65K characters, that would be an 8K bitmap per character class. Instead, we handle the // common case of ASCII input via such a lookup table, which at one bit for each of 128 characters is only // 16 bytes per character class. We of course still need to be able to handle inputs that aren't ASCII, so // we check the input against 128, and have a fallback if the input is >= to it. Determining the right // fallback could itself be expensive. For example, if it's possible that a value >= 128 could match the // character class, we output a call to RegexRunner.CharInClass, but we don't want to have to enumerate the // entire character class evaluating every character against it, just to determine whether it's a match. // Instead, we employ some quick heuristics that will always ensure we provide a correct answer even if // we could have sometimes generated better code to give that answer. // Generate the lookup table to store 128 answers as bits. We use a const string instead of a byte[] / static // data property because it lets IL emit handle all the details for us. string bitVectorString = string.Create(8, (charClass, invariant), static (dest, state) => // String length is 8 chars == 16 bytes == 128 bits. { for (int i = 0; i < 128; i++) { char c = (char)i; bool isSet = state.invariant ? RegexCharClass.CharInClass(char.ToLowerInvariant(c), state.charClass) : RegexCharClass.CharInClass(c, state.charClass); if (isSet) { dest[i >> 4] |= (char)(1 << (i & 0xF)); } } }); // We determined that the character class may contain ASCII, so we // output the lookup against the lookup table. // ch < 128 ? (bitVectorString[ch >> 4] & (1 << (ch & 0xF))) != 0 : Ldloc(tempLocal); Ldc(128); Bge(comparisonLabel); Ldstr(bitVectorString); Ldloc(tempLocal); Ldc(4); Shr(); Call(s_stringGetCharsMethod); Ldc(1); Ldloc(tempLocal); Ldc(15); And(); Ldc(31); And(); Shl(); And(); Ldc(0); CgtUn(); Stloc(resultLocal); Br(doneLabel); MarkLabel(comparisonLabel); if (analysis.ContainsOnlyAscii) { // We know that all inputs that could match are ASCII, for example if the // character class were [A-Za-z0-9], so since the ch is now known to be >= 128, we // can just fail the comparison. Ldc(0); Stloc(resultLocal); } else if (analysis.AllNonAsciiContained) { // We know that all non-ASCII inputs match, for example if the character // class were [^\r\n], so since we just determined the ch to be >= 128, we can just // give back success. Ldc(1); Stloc(resultLocal); } else { // We know that the whole class wasn't ASCII, and we don't know anything about the non-ASCII // characters other than that some might be included, for example if the character class // were [\w\d], so since ch >= 128, we need to fall back to calling CharInClass. EmitCharInClass(); } MarkLabel(doneLabel); Ldloc(resultLocal); } /// <summary>Emits a timeout check.</summary> private void EmitTimeoutCheck() { if (!_hasTimeout) { return; } Debug.Assert(_loopTimeoutCounter != null); // Increment counter for each loop iteration. Ldloc(_loopTimeoutCounter); Ldc(1); Add(); Stloc(_loopTimeoutCounter); // Emit code to check the timeout every 2048th iteration. Label label = DefineLabel(); Ldloc(_loopTimeoutCounter); Ldc(LoopTimeoutCheckCount); RemUn(); Brtrue(label); Ldthis(); Call(s_checkTimeoutMethod); MarkLabel(label); } } }
1
dotnet/runtime
66,321
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug
Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
stephentoub
2022-03-08T01:37:40Z
2022-03-08T19:24:48Z
446a0d610d4479fa9ba58ec14a89132a18ed33c4
b6c5a12cfa92e06734286bd991e7cca87ded1e24
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug. Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexInterpreterCode.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.Text.RegularExpressions { /// <summary>Contains the code, written by <see cref="RegexWriter"/>, for <see cref="RegexInterpreter"/> to evaluate a regular expression.</summary> internal sealed class RegexInterpreterCode { /// <summary>Find logic to use to find the next possible location for a match.</summary> public readonly RegexFindOptimizations FindOptimizations; /// <summary>The options associated with the regex.</summary> public readonly RegexOptions Options; /// <summary>RegexOpcodes and arguments written by <see cref="RegexWriter"/>.</summary> public readonly int[] Codes; /// <summary>The string / set table. <see cref="Codes"/> includes offsets into this table, for string and set arguments.</summary> public readonly string[] Strings; /// <summary>ASCII lookup table optimization for sets in <see cref="Strings"/>.</summary> public readonly uint[]?[] StringsAsciiLookup; /// <summary>How many instructions in <see cref="Codes"/> use backtracking.</summary> public readonly int TrackCount; public RegexInterpreterCode(RegexFindOptimizations findOptimizations, RegexOptions options, int[] codes, string[] strings, int trackcount) { FindOptimizations = findOptimizations; Options = options; Codes = codes; Strings = strings; StringsAsciiLookup = new uint[strings.Length][]; TrackCount = trackcount; } /// <summary>Gets whether the specified opcode may incur backtracking.</summary> public static bool OpcodeBacktracks(RegexOpcode opcode) { opcode &= RegexOpcode.OperatorMask; switch (opcode) { case RegexOpcode.Oneloop: case RegexOpcode.Onelazy: case RegexOpcode.Notoneloop: case RegexOpcode.Notonelazy: case RegexOpcode.Setloop: case RegexOpcode.Setlazy: case RegexOpcode.Lazybranch: case RegexOpcode.Branchmark: case RegexOpcode.Lazybranchmark: case RegexOpcode.Nullcount: case RegexOpcode.Setcount: case RegexOpcode.Branchcount: case RegexOpcode.Lazybranchcount: case RegexOpcode.Setmark: case RegexOpcode.Capturemark: case RegexOpcode.Getmark: case RegexOpcode.Setjump: case RegexOpcode.Backjump: case RegexOpcode.Forejump: case RegexOpcode.Goto: return true; default: return false; } } /// <summary>Gets the number of integers required to store an operation represented by the specified opcode (including the opcode).</summary> /// <returns>Values range from 1 (just the opcode) to 3 (the opcode plus up to two operands).</returns> public static int OpcodeSize(RegexOpcode opcode) { opcode &= RegexOpcode.OperatorMask; switch (opcode) { case RegexOpcode.Nothing: case RegexOpcode.Bol: case RegexOpcode.Eol: case RegexOpcode.Boundary: case RegexOpcode.NonBoundary: case RegexOpcode.ECMABoundary: case RegexOpcode.NonECMABoundary: case RegexOpcode.Beginning: case RegexOpcode.Start: case RegexOpcode.EndZ: case RegexOpcode.End: case RegexOpcode.Nullmark: case RegexOpcode.Setmark: case RegexOpcode.Getmark: case RegexOpcode.Setjump: case RegexOpcode.Backjump: case RegexOpcode.Forejump: case RegexOpcode.Stop: case RegexOpcode.UpdateBumpalong: // The opcode has no operands. return 1; case RegexOpcode.One: case RegexOpcode.Notone: case RegexOpcode.Multi: case RegexOpcode.Backreference: case RegexOpcode.TestBackreference: case RegexOpcode.Goto: case RegexOpcode.Nullcount: case RegexOpcode.Setcount: case RegexOpcode.Lazybranch: case RegexOpcode.Branchmark: case RegexOpcode.Lazybranchmark: case RegexOpcode.Set: // The opcode has one operand. return 2; case RegexOpcode.Capturemark: case RegexOpcode.Branchcount: case RegexOpcode.Lazybranchcount: case RegexOpcode.Onerep: case RegexOpcode.Notonerep: case RegexOpcode.Oneloop: case RegexOpcode.Oneloopatomic: case RegexOpcode.Notoneloop: case RegexOpcode.Notoneloopatomic: case RegexOpcode.Onelazy: case RegexOpcode.Notonelazy: case RegexOpcode.Setlazy: case RegexOpcode.Setrep: case RegexOpcode.Setloop: case RegexOpcode.Setloopatomic: // The opcode has two operands. return 3; default: Debug.Fail($"Unknown opcode: {opcode}"); goto case RegexOpcode.Stop; } } #if DEBUG [ExcludeFromCodeCoverage] public override string ToString() { var sb = new StringBuilder(); sb.AppendLine($"Direction: {((Options & RegexOptions.RightToLeft) != 0 ? "right-to-left" : "left-to-right")}"); sb.AppendLine(); for (int i = 0; i < Codes.Length; i += OpcodeSize((RegexOpcode)Codes[i])) { sb.AppendLine(DescribeInstruction(i)); } return sb.ToString(); } [ExcludeFromCodeCoverage] internal string DescribeInstruction(int opcodeOffset) { RegexOpcode opcode = (RegexOpcode)Codes[opcodeOffset]; var sb = new StringBuilder(); sb.Append($"{opcodeOffset:D6} "); sb.Append(OpcodeBacktracks(opcode & RegexOpcode.OperatorMask) ? '~' : ' '); sb.Append(opcode & RegexOpcode.OperatorMask); if ((opcode & RegexOpcode.CaseInsensitive) != 0) sb.Append("-Ci"); if ((opcode & RegexOpcode.RightToLeft) != 0) sb.Append("-Rtl"); if ((opcode & RegexOpcode.Backtracking) != 0) sb.Append("-Back"); if ((opcode & RegexOpcode.BacktrackingSecond) != 0) sb.Append("-Back2"); opcode &= RegexOpcode.OperatorMask; switch (opcode) { case RegexOpcode.One: case RegexOpcode.Onerep: case RegexOpcode.Oneloop: case RegexOpcode.Oneloopatomic: case RegexOpcode.Onelazy: case RegexOpcode.Notone: case RegexOpcode.Notonerep: case RegexOpcode.Notoneloop: case RegexOpcode.Notoneloopatomic: case RegexOpcode.Notonelazy: sb.Append(Indent()).Append('\'').Append(RegexCharClass.DescribeChar((char)Codes[opcodeOffset + 1])).Append('\''); break; case RegexOpcode.Set: case RegexOpcode.Setrep: case RegexOpcode.Setloop: case RegexOpcode.Setloopatomic: case RegexOpcode.Setlazy: sb.Append(Indent()).Append(RegexCharClass.DescribeSet(Strings[Codes[opcodeOffset + 1]])); break; case RegexOpcode.Multi: sb.Append(Indent()).Append('"').Append(Strings[Codes[opcodeOffset + 1]]).Append('"'); break; case RegexOpcode.Backreference: case RegexOpcode.TestBackreference: sb.Append(Indent()).Append("index = ").Append(Codes[opcodeOffset + 1]); break; case RegexOpcode.Capturemark: sb.Append(Indent()).Append("index = ").Append(Codes[opcodeOffset + 1]); if (Codes[opcodeOffset + 2] != -1) { sb.Append(", unindex = ").Append(Codes[opcodeOffset + 2]); } break; case RegexOpcode.Nullcount: case RegexOpcode.Setcount: sb.Append(Indent()).Append("value = ").Append(Codes[opcodeOffset + 1]); break; case RegexOpcode.Goto: case RegexOpcode.Lazybranch: case RegexOpcode.Branchmark: case RegexOpcode.Lazybranchmark: case RegexOpcode.Branchcount: case RegexOpcode.Lazybranchcount: sb.Append(Indent()).Append("addr = ").Append(Codes[opcodeOffset + 1]); break; } switch (opcode) { case RegexOpcode.Onerep: case RegexOpcode.Oneloop: case RegexOpcode.Oneloopatomic: case RegexOpcode.Onelazy: case RegexOpcode.Notonerep: case RegexOpcode.Notoneloop: case RegexOpcode.Notoneloopatomic: case RegexOpcode.Notonelazy: case RegexOpcode.Setrep: case RegexOpcode.Setloop: case RegexOpcode.Setloopatomic: case RegexOpcode.Setlazy: sb.Append(", rep = ").Append(Codes[opcodeOffset + 2] == int.MaxValue ? "inf" : Codes[opcodeOffset + 2]); break; case RegexOpcode.Branchcount: case RegexOpcode.Lazybranchcount: sb.Append(", limit = ").Append(Codes[opcodeOffset + 2] == int.MaxValue ? "inf" : Codes[opcodeOffset + 2]); break; } return sb.ToString(); string Indent() => new string(' ', Math.Max(1, 25 - sb.Length)); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Text.RegularExpressions { /// <summary>Contains the code, written by <see cref="RegexWriter"/>, for <see cref="RegexInterpreter"/> to evaluate a regular expression.</summary> internal sealed class RegexInterpreterCode { /// <summary>Find logic to use to find the next possible location for a match.</summary> public readonly RegexFindOptimizations FindOptimizations; /// <summary>The options associated with the regex.</summary> public readonly RegexOptions Options; /// <summary>RegexOpcodes and arguments written by <see cref="RegexWriter"/>.</summary> public readonly int[] Codes; /// <summary>The string / set table. <see cref="Codes"/> includes offsets into this table, for string and set arguments.</summary> public readonly string[] Strings; /// <summary>ASCII lookup table optimization for sets in <see cref="Strings"/>.</summary> public readonly uint[]?[] StringsAsciiLookup; /// <summary>How many instructions in <see cref="Codes"/> use backtracking.</summary> public readonly int TrackCount; public RegexInterpreterCode(RegexFindOptimizations findOptimizations, RegexOptions options, int[] codes, string[] strings, int trackcount) { FindOptimizations = findOptimizations; Options = options; Codes = codes; Strings = strings; StringsAsciiLookup = new uint[strings.Length][]; TrackCount = trackcount; } /// <summary>Gets whether the specified opcode may incur backtracking.</summary> public static bool OpcodeBacktracks(RegexOpcode opcode) { opcode &= RegexOpcode.OperatorMask; switch (opcode) { case RegexOpcode.Oneloop: case RegexOpcode.Onelazy: case RegexOpcode.Notoneloop: case RegexOpcode.Notonelazy: case RegexOpcode.Setloop: case RegexOpcode.Setlazy: case RegexOpcode.Lazybranch: case RegexOpcode.Branchmark: case RegexOpcode.Lazybranchmark: case RegexOpcode.Nullcount: case RegexOpcode.Setcount: case RegexOpcode.Branchcount: case RegexOpcode.Lazybranchcount: case RegexOpcode.Setmark: case RegexOpcode.Capturemark: case RegexOpcode.Getmark: case RegexOpcode.Setjump: case RegexOpcode.Backjump: case RegexOpcode.Forejump: case RegexOpcode.Goto: return true; default: return false; } } #if DEBUG /// <summary>Gets the number of integers required to store an operation represented by the specified opcode (including the opcode).</summary> /// <returns>Values range from 1 (just the opcode) to 3 (the opcode plus up to two operands).</returns> [ExcludeFromCodeCoverage] public static int OpcodeSize(RegexOpcode opcode) { opcode &= RegexOpcode.OperatorMask; switch (opcode) { case RegexOpcode.Nothing: case RegexOpcode.Bol: case RegexOpcode.Eol: case RegexOpcode.Boundary: case RegexOpcode.NonBoundary: case RegexOpcode.ECMABoundary: case RegexOpcode.NonECMABoundary: case RegexOpcode.Beginning: case RegexOpcode.Start: case RegexOpcode.EndZ: case RegexOpcode.End: case RegexOpcode.Nullmark: case RegexOpcode.Setmark: case RegexOpcode.Getmark: case RegexOpcode.Setjump: case RegexOpcode.Backjump: case RegexOpcode.Forejump: case RegexOpcode.Stop: case RegexOpcode.UpdateBumpalong: // The opcode has no operands. return 1; case RegexOpcode.One: case RegexOpcode.Notone: case RegexOpcode.Multi: case RegexOpcode.Backreference: case RegexOpcode.TestBackreference: case RegexOpcode.Goto: case RegexOpcode.Nullcount: case RegexOpcode.Setcount: case RegexOpcode.Lazybranch: case RegexOpcode.Branchmark: case RegexOpcode.Lazybranchmark: case RegexOpcode.Set: // The opcode has one operand. return 2; case RegexOpcode.Capturemark: case RegexOpcode.Branchcount: case RegexOpcode.Lazybranchcount: case RegexOpcode.Onerep: case RegexOpcode.Notonerep: case RegexOpcode.Oneloop: case RegexOpcode.Oneloopatomic: case RegexOpcode.Notoneloop: case RegexOpcode.Notoneloopatomic: case RegexOpcode.Onelazy: case RegexOpcode.Notonelazy: case RegexOpcode.Setlazy: case RegexOpcode.Setrep: case RegexOpcode.Setloop: case RegexOpcode.Setloopatomic: // The opcode has two operands. return 3; default: Debug.Fail($"Unknown opcode: {opcode}"); goto case RegexOpcode.Stop; } } [ExcludeFromCodeCoverage] public override string ToString() { var sb = new StringBuilder(); sb.AppendLine($"Direction: {((Options & RegexOptions.RightToLeft) != 0 ? "right-to-left" : "left-to-right")}"); sb.AppendLine(); for (int i = 0; i < Codes.Length; i += OpcodeSize((RegexOpcode)Codes[i])) { sb.AppendLine(DescribeInstruction(i)); } return sb.ToString(); } [ExcludeFromCodeCoverage] internal string DescribeInstruction(int opcodeOffset) { RegexOpcode opcode = (RegexOpcode)Codes[opcodeOffset]; var sb = new StringBuilder(); sb.Append($"{opcodeOffset:D6} "); sb.Append(OpcodeBacktracks(opcode & RegexOpcode.OperatorMask) ? '~' : ' '); sb.Append(opcode & RegexOpcode.OperatorMask); if ((opcode & RegexOpcode.CaseInsensitive) != 0) sb.Append("-Ci"); if ((opcode & RegexOpcode.RightToLeft) != 0) sb.Append("-Rtl"); if ((opcode & RegexOpcode.Backtracking) != 0) sb.Append("-Back"); if ((opcode & RegexOpcode.BacktrackingSecond) != 0) sb.Append("-Back2"); opcode &= RegexOpcode.OperatorMask; switch (opcode) { case RegexOpcode.One: case RegexOpcode.Onerep: case RegexOpcode.Oneloop: case RegexOpcode.Oneloopatomic: case RegexOpcode.Onelazy: case RegexOpcode.Notone: case RegexOpcode.Notonerep: case RegexOpcode.Notoneloop: case RegexOpcode.Notoneloopatomic: case RegexOpcode.Notonelazy: sb.Append(Indent()).Append('\'').Append(RegexCharClass.DescribeChar((char)Codes[opcodeOffset + 1])).Append('\''); break; case RegexOpcode.Set: case RegexOpcode.Setrep: case RegexOpcode.Setloop: case RegexOpcode.Setloopatomic: case RegexOpcode.Setlazy: sb.Append(Indent()).Append(RegexCharClass.DescribeSet(Strings[Codes[opcodeOffset + 1]])); break; case RegexOpcode.Multi: sb.Append(Indent()).Append('"').Append(Strings[Codes[opcodeOffset + 1]]).Append('"'); break; case RegexOpcode.Backreference: case RegexOpcode.TestBackreference: sb.Append(Indent()).Append("index = ").Append(Codes[opcodeOffset + 1]); break; case RegexOpcode.Capturemark: sb.Append(Indent()).Append("index = ").Append(Codes[opcodeOffset + 1]); if (Codes[opcodeOffset + 2] != -1) { sb.Append(", unindex = ").Append(Codes[opcodeOffset + 2]); } break; case RegexOpcode.Nullcount: case RegexOpcode.Setcount: sb.Append(Indent()).Append("value = ").Append(Codes[opcodeOffset + 1]); break; case RegexOpcode.Goto: case RegexOpcode.Lazybranch: case RegexOpcode.Branchmark: case RegexOpcode.Lazybranchmark: case RegexOpcode.Branchcount: case RegexOpcode.Lazybranchcount: sb.Append(Indent()).Append("addr = ").Append(Codes[opcodeOffset + 1]); break; } switch (opcode) { case RegexOpcode.Onerep: case RegexOpcode.Oneloop: case RegexOpcode.Oneloopatomic: case RegexOpcode.Onelazy: case RegexOpcode.Notonerep: case RegexOpcode.Notoneloop: case RegexOpcode.Notoneloopatomic: case RegexOpcode.Notonelazy: case RegexOpcode.Setrep: case RegexOpcode.Setloop: case RegexOpcode.Setloopatomic: case RegexOpcode.Setlazy: sb.Append(", rep = ").Append(Codes[opcodeOffset + 2] == int.MaxValue ? "inf" : Codes[opcodeOffset + 2]); break; case RegexOpcode.Branchcount: case RegexOpcode.Lazybranchcount: sb.Append(", limit = ").Append(Codes[opcodeOffset + 2] == int.MaxValue ? "inf" : Codes[opcodeOffset + 2]); break; } return sb.ToString(); string Indent() => new string(' ', Math.Max(1, 25 - sb.Length)); } #endif } }
1
dotnet/runtime
66,321
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug
Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
stephentoub
2022-03-08T01:37:40Z
2022-03-08T19:24:48Z
446a0d610d4479fa9ba58ec14a89132a18ed33c4
b6c5a12cfa92e06734286bd991e7cca87ded1e24
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug. Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
./src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.Match.Tests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Tests; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Text.RegularExpressions.Tests { public class RegexMatchTests { public static IEnumerable<object[]> Match_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { (string Pattern, string Input, RegexOptions Options, int Beginning, int Length, bool ExpectedSuccess, string ExpectedValue)[] cases = Cases(engine).ToArray(); Regex[] regexes = RegexHelpers.GetRegexesAsync(engine, cases.Select(c => (c.Pattern, (RegexOptions?)c.Options, (TimeSpan?)null)).ToArray()).Result; for (int i = 0; i < regexes.Length; i++) { yield return new object[] { engine, cases[i].Pattern, cases[i].Input, cases[i].Options, regexes[i], cases[i].Beginning, cases[i].Length, cases[i].ExpectedSuccess, cases[i].ExpectedValue }; } } static IEnumerable<(string Pattern, string Input, RegexOptions Options, int Beginning, int Length, bool ExpectedSuccess, string ExpectedValue)> Cases(RegexEngine engine) { // pattern, input, options, beginning, length, expectedSuccess, expectedValue yield return (@"H#", "#H#", RegexOptions.IgnoreCase, 0, 3, true, "H#"); // https://github.com/dotnet/runtime/issues/39390 yield return (@"H#", "#H#", RegexOptions.None, 0, 3, true, "H#"); // Testing octal sequence matches: "\\060(\\061)?\\061" // Octal \061 is ASCII 49 ('1') yield return (@"\060(\061)?\061", "011", RegexOptions.None, 0, 3, true, "011"); // Testing hexadecimal sequence matches: "(\\x30\\x31\\x32)" // Hex \x31 is ASCII 49 ('1') yield return (@"(\x30\x31\x32)", "012", RegexOptions.None, 0, 3, true, "012"); // Testing control character escapes???: "2", "(\u0032)" yield return ("(\u0034)", "4", RegexOptions.None, 0, 1, true, "4"); // Using long loop prefix yield return (@"a{10}", new string('a', 10), RegexOptions.None, 0, 10, true, new string('a', 10)); yield return (@"a{100}", new string('a', 100), RegexOptions.None, 0, 100, true, new string('a', 100)); yield return (@"a{10}b", new string('a', 10) + "bc", RegexOptions.None, 0, 12, true, new string('a', 10) + "b"); yield return (@"a{100}b", new string('a', 100) + "bc", RegexOptions.None, 0, 102, true, new string('a', 100) + "b"); yield return (@"a{11}b", new string('a', 10) + "bc", RegexOptions.None, 0, 12, false, string.Empty); yield return (@"a{101}b", new string('a', 100) + "bc", RegexOptions.None, 0, 102, false, string.Empty); yield return (@"a{1,3}b", "bc", RegexOptions.None, 0, 2, false, string.Empty); yield return (@"a{1,3}b", "abc", RegexOptions.None, 0, 3, true, "ab"); yield return (@"a{1,3}b", "aaabc", RegexOptions.None, 0, 5, true, "aaab"); yield return (@"a{1,3}b", "aaaabc", RegexOptions.None, 0, 6, true, "aaab"); yield return (@"a{1,3}?b", "bc", RegexOptions.None, 0, 2, false, string.Empty); yield return (@"a{1,3}?b", "abc", RegexOptions.None, 0, 3, true, "ab"); yield return (@"a{1,3}?b", "aaabc", RegexOptions.None, 0, 5, true, "aaab"); yield return (@"a{1,3}?b", "aaaabc", RegexOptions.None, 0, 6, true, "aaab"); yield return (@"a{2,}b", "abc", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"a{2,}b", "aabc", RegexOptions.None, 0, 4, true, "aab"); yield return (@"a{2,}?b", "abc", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"a{2,}?b", "aabc", RegexOptions.None, 0, 4, true, "aab"); // {,n} is treated as a literal rather than {0,n} as it should be yield return (@"a{,3}b", "a{,3}bc", RegexOptions.None, 0, 6, true, "a{,3}b"); yield return (@"a{,3}b", "aaabc", RegexOptions.None, 0, 5, false, string.Empty); // Using [a-z], \s, \w: Actual - "([a-zA-Z]+)\\s(\\w+)" yield return (@"([a-zA-Z]+)\s(\w+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau"); yield return (@"([a-zA-Z]+?)\s(\w+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau"); // \\S, \\d, \\D, \\W: Actual - "(\\S+):\\W(\\d+)\\s(\\D+)" yield return (@"(\S+):\W(\d+)\s(\D+)", "Price: 5 dollars", RegexOptions.None, 0, 16, true, "Price: 5 dollars"); // \\S, \\d, \\D, \\W: Actual - "[^0-9]+(\\d+)" yield return (@"[^0-9]+(\d+)", "Price: 30 dollars", RegexOptions.None, 0, 17, true, "Price: 30"); if (!RegexHelpers.IsNonBacktracking(engine)) { // Zero-width negative lookahead assertion yield return (@"abc(?!XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, false, string.Empty); // Zero-width positive lookbehind assertion yield return (@"(\w){6}(?<=XXX)def", "abcXXXdef", RegexOptions.None, 0, 9, true, "abcXXXdef"); yield return (@"(?<=c)def", "123abcdef", RegexOptions.None, 0, 9, true, "def"); yield return (@"(?<=abc)def", "123abcdef", RegexOptions.None, 0, 9, true, "def"); yield return (@"(?<=a\wc)def", "123abcdef", RegexOptions.None, 0, 9, true, "def"); yield return (@"(?<=\ba\wc)def", "123 abcdef", RegexOptions.None, 0, 10, true, "def"); yield return (@"(?<=.\ba\wc\B)def", "123 abcdef", RegexOptions.None, 0, 10, true, "def"); yield return (@"(?<=^123 abc)def", "123 abcdef", RegexOptions.None, 0, 10, true, "def"); yield return (@"(?<=^123 abc)def", "123 abcdef", RegexOptions.Multiline, 0, 10, true, "def"); yield return (@"(?<=123$\nabc)def", "123\nabcdef", RegexOptions.Multiline, 0, 10, true, "def"); yield return (@"123(?<!$) abcdef", "123 abcdef", RegexOptions.None, 0, 10, true, "123 abcdef"); yield return (@"\w{3}(?<=^xyz|^abc)defg", "abcdefg", RegexOptions.None, 0, 7, true, "abcdefg"); yield return (@"(abc)\w(?<=(?(1)d|e))", "abcdabc", RegexOptions.None, 0, 7, true, "abcd"); yield return (@"(abc)\w(?<!(?(1)e|d))", "abcdabc", RegexOptions.None, 0, 7, true, "abcd"); yield return (@"(abc)\w(?<=(?(cd)d|e))", "abcdabc", RegexOptions.None, 0, 7, true, "abcd"); yield return (@"(abc)\w(?<!(?(cd)e|d))", "abcdabc", RegexOptions.None, 0, 7, true, "abcd"); yield return (@"\w{3}(?<=(\w){6,8})", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "def"); yield return (@"\w{3}(?<=(?:\d\w){4})", "a1b2c3d4e5", RegexOptions.None, 0, 10, true, "d4e"); yield return (@"\w{3}(?<=(\w){6,8}?)", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "def"); yield return (@"\w{3}(?<=(?:\d\w){3,4}?\d)", "a1b2c3d4e5", RegexOptions.None, 0, 10, true, "3d4"); yield return (@"(\w{3})\w*(?<=\1)", "---abcdefababc123", RegexOptions.None, 0, 17, true, "abcdefababc"); yield return (@"(?<=\w{3})\w{4}", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "defg"); yield return (@"(?<=\w{3,8})\w{4}", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "defg"); yield return (@"(?<=\w*)\w{4}", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "abcd"); yield return (@"(?<=\w?)\w{4}", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "abcd"); yield return (@"(?<=\d?)a{4}", "123aaaaaaaaa", RegexOptions.None, 0, 12, true, "aaaa"); yield return (@"(?<=a{3,5}[ab]*)1234", "aaaaaaa1234", RegexOptions.None, 0, 11, true, "1234"); // Zero-width negative lookbehind assertion: Actual - "(\\w){6}(?<!XXX)def" yield return (@"(\w){6}(?<!XXX)def", "XXXabcdef", RegexOptions.None, 0, 9, true, "XXXabcdef"); // Nonbacktracking subexpression: Actual - "[^0-9]+(?>[0-9]+)3" // The last 3 causes the match to fail, since the non backtracking subexpression does not give up the last digit it matched // for it to be a success. For a correct match, remove the last character, '3' from the pattern yield return ("[^0-9]+(?>[0-9]+)3", "abc123", RegexOptions.None, 0, 6, false, string.Empty); yield return ("[^0-9]+(?>[0-9]+)", "abc123", RegexOptions.None, 0, 6, true, "abc123"); yield return (@"(?!.*a)\w*g", "bcaefg", RegexOptions.None, 0, 6, true, "efg"); yield return (@"(?!.*a)\w*g", "aaaaag", RegexOptions.None, 0, 6, true, "g"); yield return (@"(?!.*a)\w*g", "aaaaaa", RegexOptions.None, 0, 6, false, string.Empty); } // More nonbacktracking expressions foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.IgnoreCase }) { string Case(string s) => (options & RegexOptions.IgnoreCase) != 0 ? s.ToUpper() : s; yield return (Case("(?:hi|hello|hey)hi"), "hellohi", options, 0, 7, true, "hellohi"); // allow backtracking and it succeeds yield return (Case(@"a[^wyz]*w"), "abczw", RegexOptions.IgnoreCase, 0, 0, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { // Atomic greedy yield return (Case("(?>[0-9]+)abc"), "abc12345abc", options, 3, 8, true, "12345abc"); yield return (Case("(?>(?>[0-9]+))abc"), "abc12345abc", options, 3, 8, true, "12345abc"); yield return (Case("(?>[0-9]*)abc"), "abc12345abc", options, 3, 8, true, "12345abc"); yield return (Case("(?>[^z]+)z"), "zzzzxyxyxyz123", options, 4, 9, true, "xyxyxyz"); yield return (Case("(?>(?>[^z]+))z"), "zzzzxyxyxyz123", options, 4, 9, true, "xyxyxyz"); yield return (Case("(?>[^z]*)z123"), "zzzzxyxyxyz123", options, 4, 10, true, "xyxyxyz123"); yield return (Case("(?>a+)123"), "aa1234", options, 0, 5, true, "aa123"); yield return (Case("(?>a*)123"), "aa1234", options, 0, 5, true, "aa123"); yield return (Case("(?>(?>a*))123"), "aa1234", options, 0, 5, true, "aa123"); yield return (Case("(?>a{2,})b"), "aaab", options, 0, 4, true, "aaab"); yield return (Case("[a-z]{0,4}(?>[x-z]*.)(?=xyz1)"), "abcdxyz1", options, 0, 8, true, "abcd"); yield return (Case("[a-z]{0,4}(?=[x-z]*.)(?=cd)"), "abcdxyz1", options, 0, 8, true, "ab"); yield return (Case("[a-z]{0,4}(?![x-z]*[wx])(?=cd)"), "abcdxyz1", options, 0, 8, true, "ab"); // Atomic lazy yield return (Case("(?>[0-9]+?)abc"), "abc12345abc", options, 3, 8, true, "5abc"); yield return (Case("(?>(?>[0-9]+?))abc"), "abc12345abc", options, 3, 8, true, "5abc"); yield return (Case("(?>[0-9]*?)abc"), "abc12345abc", options, 3, 8, true, "abc"); yield return (Case("(?>[^z]+?)z"), "zzzzxyxyxyz123", options, 4, 9, true, "yz"); yield return (Case("(?>(?>[^z]+?))z"), "zzzzxyxyxyz123", options, 4, 9, true, "yz"); yield return (Case("(?>[^z]*?)z123"), "zzzzxyxyxyz123", options, 4, 10, true, "z123"); yield return (Case("(?>a+?)123"), "aa1234", options, 0, 5, true, "a123"); yield return (Case("(?>a*?)123"), "aa1234", options, 0, 5, true, "123"); yield return (Case("(?>(?>a*?))123"), "aa1234", options, 0, 5, true, "123"); yield return (Case("(?>a{2,}?)b"), "aaab", options, 0, 4, true, "aab"); // Alternations yield return (Case("(?>hi|hello|hey)hi"), "hellohi", options, 0, 0, false, string.Empty); yield return (Case("(?>hi|hello|hey)hi"), "hihi", options, 0, 4, true, "hihi"); } } // Loops at beginning of expressions yield return (@"a+", "aaa", RegexOptions.None, 0, 3, true, "aaa"); yield return (@"a+\d+", "a1", RegexOptions.None, 0, 2, true, "a1"); yield return (@".+\d+", "a1", RegexOptions.None, 0, 2, true, "a1"); yield return (".+\nabc", "a\nabc", RegexOptions.None, 0, 5, true, "a\nabc"); yield return (@"\d+", "abcd123efg", RegexOptions.None, 0, 10, true, "123"); yield return (@"\d+\d+", "abcd123efg", RegexOptions.None, 0, 10, true, "123"); yield return (@"\w+123\w+", "abcd123efg", RegexOptions.None, 0, 10, true, "abcd123efg"); yield return (@"\d+\w+", "abcd123efg", RegexOptions.None, 0, 10, true, "123efg"); yield return (@"\w+@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{3,}@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{4,}@\w+.com", "[email protected]", RegexOptions.None, 0, 11, false, string.Empty); yield return (@"\w{2,5}@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{3}@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{0,3}@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{0,2}c@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w*@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"(\w+)@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"((\w+))@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"(\w+)c@\w+.com", "[email protected]", RegexOptions.None, 0, 17, true, "[email protected]"); yield return (@"\w+://\w+\.\w+", "test https://dot.net test", RegexOptions.None, 0, 25, true, "https://dot.net"); yield return (@"\w+[:|$*&]//\w+\.\w+", "test https://dot.net test", RegexOptions.None, 0, 25, true, "https://dot.net"); yield return (@".+a", "baa", RegexOptions.None, 0, 3, true, "baa"); yield return (@"[ab]+a", "cacbaac", RegexOptions.None, 0, 7, true, "baa"); yield return (@"^(\d{2,3}){2}$", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(\d{2,3}){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"((\d{2,3})){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(abc\d{2,3}){2}", "abc123abc4567", RegexOptions.None, 0, 12, true, "abc123abc456"); // Lazy versions of those loops yield return (@"a+?", "aaa", RegexOptions.None, 0, 3, true, "a"); yield return (@"a+?\d+?", "a1", RegexOptions.None, 0, 2, true, "a1"); yield return (@".+?\d+?", "a1", RegexOptions.None, 0, 2, true, "a1"); yield return (".+?\nabc", "a\nabc", RegexOptions.None, 0, 5, true, "a\nabc"); yield return (@"\d+?", "abcd123efg", RegexOptions.None, 0, 10, true, "1"); yield return (@"\d+?\d+?", "abcd123efg", RegexOptions.None, 0, 10, true, "12"); yield return (@"\w+?123\w+?", "abcd123efg", RegexOptions.None, 0, 10, true, "abcd123e"); yield return (@"\d+?\w+?", "abcd123efg", RegexOptions.None, 0, 10, true, "12"); yield return (@"\w+?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{3,}?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{4,}?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, false, string.Empty); yield return (@"\w{2,5}?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{3}?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{0,3}?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{0,2}?c@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w*?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"(\w+?)@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"((\w+?))@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"(\w+?)c@\w+?\.com", "[email protected]", RegexOptions.None, 0, 17, true, "[email protected]"); yield return (@".+?a", "baa", RegexOptions.None, 0, 3, true, "ba"); yield return (@"[ab]+?a", "cacbaac", RegexOptions.None, 0, 7, true, "ba"); yield return (@"^(\d{2,3}?){2}$", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(\d{2,3}?){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"((\d{2,3}?)){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(abc\d{2,3}?){2}", "abc123abc4567", RegexOptions.None, 0, 12, true, "abc123abc45"); // Testing selected FindOptimizations finds the right prefix yield return (@"(^|a+)bc", " aabc", RegexOptions.None, 0, 5, true, "aabc"); yield return (@"(^|($|a+))bc", " aabc", RegexOptions.None, 0, 5, true, "aabc"); yield return (@"yz(^|a+)bc", " yzaabc", RegexOptions.None, 0, 7, true, "yzaabc"); yield return (@"(^a|a$) bc", "a bc", RegexOptions.None, 0, 4, true, "a bc"); yield return (@"(abcdefg|abcdef|abc|a)h", " ah ", RegexOptions.None, 0, 8, true, "ah"); yield return (@"(^abcdefg|abcdef|^abc|a)h", " abcdefh ", RegexOptions.None, 0, 13, true, "abcdefh"); yield return (@"(a|^abcdefg|abcdef|^abc)h", " abcdefh ", RegexOptions.None, 0, 13, true, "abcdefh"); yield return (@"(abcdefg|abcdef)h", " abcdefghij ", RegexOptions.None, 0, 16, true, "abcdefgh"); if (!RegexHelpers.IsNonBacktracking(engine)) { // Back references not support with NonBacktracking yield return (@"(\w+)c@\w+.com\1", "[email protected]", RegexOptions.None, 0, 17, true, "[email protected]"); yield return (@"(\w+)@def.com\1", "[email protected]", RegexOptions.None, 0, 13, false, string.Empty); yield return (@"(\w+)@def.com\1", "[email protected]", RegexOptions.None, 0, 13, true, "[email protected]"); yield return (@"(\w*)@def.com\1", "[email protected]", RegexOptions.None, 0, 11, true, "@def.com"); yield return (@"\w+(?<!a)", "a", RegexOptions.None, 0, 1, false, string.Empty); yield return (@"\w+(?<!a)", "aa", RegexOptions.None, 0, 2, false, string.Empty); yield return (@"(?>\w+)(?<!a)", "a", RegexOptions.None, 0, 1, false, string.Empty); yield return (@"(?>\w+)(?<!a)", "aa", RegexOptions.None, 0, 2, false, string.Empty); yield return (@"(\w+?)c@\w+?.com\1", "[email protected]", RegexOptions.None, 0, 17, true, "[email protected]"); yield return (@"(\w+?)@def.com\1", "[email protected]", RegexOptions.None, 0, 13, false, string.Empty); yield return (@"(\w+?)@def.com\1", "[email protected]", RegexOptions.None, 0, 13, true, "[email protected]"); yield return (@"(\w*?)@def.com\1", "[email protected]", RegexOptions.None, 0, 11, true, "@def.com"); yield return (@"\w+?(?<!a)", "a", RegexOptions.None, 0, 1, false, string.Empty); yield return (@"\w+?(?<!a)", "aa", RegexOptions.None, 0, 2, false, string.Empty); yield return (@"(?>\w+?)(?<!a)", "a", RegexOptions.None, 0, 1, false, string.Empty); yield return (@"(?>\w+?)(?<!a)", "aa", RegexOptions.None, 0, 2, false, string.Empty); } yield return (@"(\d{2,3})+", "1234", RegexOptions.None, 0, 4, true, "123"); yield return (@"(\d{2,3})*", "123456", RegexOptions.None, 0, 4, true, "123"); yield return (@"(\d{2,3})+?", "1234", RegexOptions.None, 0, 4, true, "123"); yield return (@"(\d{2,3})*?", "123456", RegexOptions.None, 0, 4, true, ""); yield return (@"(\d{2,3}?)+", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(\d{2,3}?)*", "123456", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(\d{2,3}?)+?", "1234", RegexOptions.None, 0, 4, true, "12"); yield return (@"(\d{2,3}?)*?", "123456", RegexOptions.None, 0, 4, true, ""); foreach (RegexOptions lineOption in new[] { RegexOptions.None, RegexOptions.Singleline }) { yield return (@".*", "abc", lineOption, 1, 2, true, "bc"); yield return (@".*c", "abc", lineOption, 1, 2, true, "bc"); yield return (@"b.*", "abc", lineOption, 1, 2, true, "bc"); yield return (@".*", "abc", lineOption, 2, 1, true, "c"); yield return (@"a.*[bc]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*[bc]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*[bc]", "xyza12345d6789", lineOption, 0, 14, false, ""); yield return (@"a.*[bcd]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*[bcd]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*[bcd]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*[bcd]", "xyza12345e6789", lineOption, 0, 14, false, ""); yield return (@"a.*[bcde]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*[bcde]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*[bcde]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*[bcde]", "xyza12345e6789", lineOption, 0, 14, true, "a12345e"); yield return (@"a.*[bcde]", "xyza12345f6789", lineOption, 0, 14, false, ""); yield return (@"a.*[bcdef]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*[bcdef]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*[bcdef]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*[bcdef]", "xyza12345e6789", lineOption, 0, 14, true, "a12345e"); yield return (@"a.*[bcdef]", "xyza12345f6789", lineOption, 0, 14, true, "a12345f"); yield return (@"a.*[bcdef]", "xyza12345g6789", lineOption, 0, 14, false, ""); yield return (@".*?", "abc", lineOption, 1, 2, true, ""); yield return (@".*?c", "abc", lineOption, 1, 2, true, "bc"); yield return (@"b.*?", "abc", lineOption, 1, 2, true, "b"); yield return (@".*?", "abc", lineOption, 2, 1, true, ""); yield return (@"a.*?[bc]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*?[bc]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*?[bc]", "xyza12345d6789", lineOption, 0, 14, false, ""); yield return (@"a.*?[bcd]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*?[bcd]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*?[bcd]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*?[bcd]", "xyza12345e6789", lineOption, 0, 14, false, ""); yield return (@"a.*?[bcde]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*?[bcde]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*?[bcde]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*?[bcde]", "xyza12345e6789", lineOption, 0, 14, true, "a12345e"); yield return (@"a.*?[bcde]", "xyza12345f6789", lineOption, 0, 14, false, ""); yield return (@"a.*?[bcdef]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*?[bcdef]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*?[bcdef]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*?[bcdef]", "xyza12345e6789", lineOption, 0, 14, true, "a12345e"); yield return (@"a.*?[bcdef]", "xyza12345f6789", lineOption, 0, 14, true, "a12345f"); yield return (@"a.*?[bcdef]", "xyza12345g6789", lineOption, 0, 14, false, ""); } // Nested loops yield return ("a*(?:a[ab]*)*", "aaaababbbbbbabababababaaabbb", RegexOptions.None, 0, 28, true, "aaaa"); yield return ("a*(?:a[ab]*?)*?", "aaaababbbbbbabababababaaabbb", RegexOptions.None, 0, 28, true, "aaaa"); // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return (@"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzz", RegexOptions.IgnoreCase, 0, 17, true, "aaaasdfajsdlfjzzz"); yield return (@"\Aaaaaa\w+zzz\Z", "aaaa", RegexOptions.IgnoreCase, 0, 4, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"\Aaaaaa\w+zzz\Z", "aaaa", RegexOptions.RightToLeft, 0, 4, false, string.Empty); yield return (@"\Aaaaaa\w+zzzzz\Z", "aaaa", RegexOptions.RightToLeft, 0, 4, false, string.Empty); yield return (@"\Aaaaaa\w+zzz\Z", "aaaa", RegexOptions.RightToLeft | RegexOptions.IgnoreCase, 0, 4, false, string.Empty); } yield return (@"abc\Adef", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); yield return (@"abc\adef", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"abc\Gdef", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); } yield return (@"abc^def", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); yield return (@"abc\Zef", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); yield return (@"abc\zef", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return (@"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzza", RegexOptions.None, 0, 18, false, string.Empty); // Anchors foreach (RegexOptions anchorOptions in new[] { RegexOptions.None, RegexOptions.Multiline }) { yield return (@"^abc", "abc", anchorOptions, 0, 3, true, "abc"); yield return (@"^abc", " abc", anchorOptions, 0, 4, false, ""); yield return (@"^abc|^def", "def", anchorOptions, 0, 3, true, "def"); yield return (@"^abc|^def", " abc", anchorOptions, 0, 4, false, ""); yield return (@"^abc|^def", " def", anchorOptions, 0, 4, false, ""); yield return (@"abc|^def", " abc", anchorOptions, 0, 4, true, "abc"); yield return (@"abc|^def|^efg", " abc", anchorOptions, 0, 4, true, "abc"); yield return (@"^abc|def|^efg", " def", anchorOptions, 0, 4, true, "def"); yield return (@"^abc|def", " def", anchorOptions, 0, 4, true, "def"); yield return (@"abcd$", "1234567890abcd", anchorOptions, 0, 14, true, "abcd"); yield return (@"abc{1,4}d$", "1234567890abcd", anchorOptions, 0, 14, true, "abcd"); yield return (@"abc{1,4}d$", "1234567890abccccd", anchorOptions, 0, 17, true, "abccccd"); } if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"\Gabc", "abc", RegexOptions.None, 0, 3, true, "abc"); yield return (@"\Gabc", " abc", RegexOptions.None, 0, 4, false, ""); yield return (@"\Gabc", " abc", RegexOptions.None, 1, 3, true, "abc"); yield return (@"\Gabc|\Gdef", "def", RegexOptions.None, 0, 3, true, "def"); yield return (@"\Gabc|\Gdef", " abc", RegexOptions.None, 0, 4, false, ""); yield return (@"\Gabc|\Gdef", " def", RegexOptions.None, 0, 4, false, ""); yield return (@"\Gabc|\Gdef", " abc", RegexOptions.None, 1, 3, true, "abc"); yield return (@"\Gabc|\Gdef", " def", RegexOptions.None, 1, 3, true, "def"); yield return (@"abc|\Gdef", " abc", RegexOptions.None, 0, 4, true, "abc"); yield return (@"\Gabc|def", " def", RegexOptions.None, 0, 4, true, "def"); } // Anchors and multiline yield return (@"^A$", "A\n", RegexOptions.Multiline, 0, 2, true, "A"); yield return (@"^A$", "ABC\n", RegexOptions.Multiline, 0, 4, false, string.Empty); yield return (@"^A$", "123\nA", RegexOptions.Multiline, 0, 5, true, "A"); yield return (@"^A$", "123\nA\n456", RegexOptions.Multiline, 0, 9, true, "A"); yield return (@"^A$|^B$", "123\nB\n456", RegexOptions.Multiline, 0, 9, true, "B"); // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return (@"\A(line2\n)line3\Z", "line2\nline3\n", RegexOptions.Multiline, 0, 12, true, "line2\nline3"); // Using beginning/end of string chars ^: Actual - "^b" yield return ("^b", "ab", RegexOptions.None, 0, 2, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { // Actual - "(?<char>\\w)\\<char>" yield return (@"(?<char>\w)\<char>", "aa", RegexOptions.None, 0, 2, true, "aa"); // Actual - "(?<43>\\w)\\43" yield return (@"(?<43>\w)\43", "aa", RegexOptions.None, 0, 2, true, "aa"); // Actual - "abc(?(1)111|222)" yield return ("(abbc)(?(1)111|222)", "abbc222", RegexOptions.None, 0, 7, false, string.Empty); } // "x" option. Removes unescaped whitespace from the pattern: Actual - " ([^/]+) ","x" yield return (" ((.)+) #comment ", "abc", RegexOptions.IgnorePatternWhitespace, 0, 3, true, "abc"); // "x" option. Removes unescaped whitespace from the pattern. : Actual - "\x20([^/]+)\x20","x" yield return ("\x20([^/]+)\x20\x20\x20\x20\x20\x20\x20", " abc ", RegexOptions.IgnorePatternWhitespace, 0, 10, true, " abc "); // Turning on case insensitive option in mid-pattern : Actual - "aaa(?i:match this)bbb" if ("i".ToUpper() == "I") { yield return ("aaa(?i:match this)bbb", "aaaMaTcH ThIsbbb", RegexOptions.None, 0, 16, true, "aaaMaTcH ThIsbbb"); } yield return ("(?i:a)b(?i:c)d", "aaaaAbCdddd", RegexOptions.None, 0, 11, true, "AbCd"); yield return ("(?i:[\u0000-\u1000])[Bb]", "aaaaAbCdddd", RegexOptions.None, 0, 11, true, "Ab"); // Turning off case insensitive option in mid-pattern : Actual - "aaa(?-i:match this)bbb", "i" yield return ("aAa(?-i:match this)bbb", "AaAmatch thisBBb", RegexOptions.IgnoreCase, 0, 16, true, "AaAmatch thisBBb"); // Turning on/off all the options at once : Actual - "aaa(?imnsx-imnsx:match this)bbb", "i" yield return ("aaa(?imnsx-imnsx:match this)bbb", "AaAmatcH thisBBb", RegexOptions.IgnoreCase, 0, 16, false, string.Empty); // Actual - "aaa(?#ignore this completely)bbb" yield return ("aAa(?#ignore this completely)bbb", "aAabbb", RegexOptions.None, 0, 6, true, "aAabbb"); // Trying empty string: Actual "[a-z0-9]+", "" yield return ("[a-z0-9]+", "", RegexOptions.None, 0, 0, false, string.Empty); // Numbering pattern slots: "(?<1>\\d{3})(?<2>\\d{3})(?<3>\\d{4})" yield return (@"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "8885551111", RegexOptions.None, 0, 10, true, "8885551111"); yield return (@"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "Invalid string", RegexOptions.None, 0, 14, false, string.Empty); // Not naming pattern slots at all: "^(cat|chat)" yield return ("^(cat|chat)", "cats are bad", RegexOptions.None, 0, 12, true, "cat"); yield return ("abc", "abc", RegexOptions.None, 0, 3, true, "abc"); yield return ("abc", "aBc", RegexOptions.None, 0, 3, false, string.Empty); yield return ("abc", "aBc", RegexOptions.IgnoreCase, 0, 3, true, "aBc"); yield return (@"abc.*def", "abcghiDEF", RegexOptions.IgnoreCase, 0, 9, true, "abcghiDEF"); // Using *, +, ?, {}: Actual - "a+\\.?b*\\.?c{2}" yield return (@"a+\.?b*\.+c{2}", "ab.cc", RegexOptions.None, 0, 5, true, "ab.cc"); yield return (@"[^a]+\.[^z]+", "zzzzz", RegexOptions.None, 0, 5, false, string.Empty); // IgnoreCase yield return ("AAA", "aaabbb", RegexOptions.IgnoreCase, 0, 6, true, "aaa"); yield return (@"\p{Lu}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b"); yield return (@"\p{Ll}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b"); yield return (@"\p{Lt}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b"); yield return (@"\p{Lo}", "1bc", RegexOptions.IgnoreCase, 0, 3, false, string.Empty); yield return (".[abc]", "xYZAbC", RegexOptions.IgnoreCase, 0, 6, true, "ZA"); yield return (".[abc]", "xYzXyZx", RegexOptions.IgnoreCase, 0, 6, false, ""); // Sets containing characters that differ by a bit yield return ("123[Aa]", "123a", RegexOptions.None, 0, 4, true, "123a"); yield return ("123[0p]", "123p", RegexOptions.None, 0, 4, true, "123p"); yield return ("123[Aa@]", "123@", RegexOptions.None, 0, 4, true, "123@"); // "\D+" yield return (@"\D+", "12321", RegexOptions.None, 0, 5, false, string.Empty); // Groups yield return ("(?<first_name>\\S+)\\s(?<last_name>\\S+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau"); // "^b" yield return ("^b", "abc", RegexOptions.None, 0, 3, false, string.Empty); // Trim leading and trailing whitespace yield return (@"\s*(.*?)\s*$", " Hello World ", RegexOptions.None, 0, 13, true, " Hello World "); if (!RegexHelpers.IsNonBacktracking(engine)) { // Throws NotSupported with NonBacktracking engine because of the balancing group dog-0 yield return (@"(?<cat>cat)\w+(?<dog-0>dog)", "cat_Hello_World_dog", RegexOptions.None, 0, 19, false, string.Empty); } // Atomic Zero-Width Assertions \A \Z \z \b \B yield return (@"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.None, 0, 20, false, string.Empty); yield return (@"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.Multiline, 0, 20, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.ECMAScript, 0, 20, false, string.Empty); } yield return (@"(cat)\s+(dog)\Z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty); yield return (@"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty); } yield return (@"(cat)\s+(dog)\z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty); yield return (@"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty); } yield return (@"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.None, 0, 16, false, string.Empty); yield return (@"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.Multiline, 0, 16, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.ECMAScript, 0, 16, false, string.Empty); } yield return (@"\b@cat", "123START123;@catEND", RegexOptions.None, 0, 19, false, string.Empty); yield return (@"\b<cat", "123START123'<catEND", RegexOptions.None, 0, 19, false, string.Empty); yield return (@"\b,cat", "satwe,,,START',catEND", RegexOptions.None, 0, 21, false, string.Empty); yield return (@"\b\[cat", "`12START123'[catEND", RegexOptions.None, 0, 19, false, string.Empty); yield return (@"\B@cat", "123START123@catEND", RegexOptions.None, 0, 18, false, string.Empty); yield return (@"\B<cat", "123START123<catEND", RegexOptions.None, 0, 18, false, string.Empty); yield return (@"\B,cat", "satwe,,,START,catEND", RegexOptions.None, 0, 20, false, string.Empty); yield return (@"\B\[cat", "`12START123[catEND", RegexOptions.None, 0, 18, false, string.Empty); // Lazy operator Backtracking yield return (@"http://([a-zA-z0-9\-]*\.?)*?(:[0-9]*)??/", "http://www.msn.com", RegexOptions.IgnoreCase, 0, 18, false, string.Empty); // Grouping Constructs Invalid Regular Expressions if (!RegexHelpers.IsNonBacktracking(engine)) { yield return ("(?!)", "(?!)cat", RegexOptions.None, 0, 7, false, string.Empty); yield return ("(?<!)", "(?<!)cat", RegexOptions.None, 0, 8, false, string.Empty); } // Alternation construct foreach (string input in new[] { "abc", "def" }) { string upper = input.ToUpperInvariant(); // Two branches yield return (@"abc|def", input, RegexOptions.None, 0, input.Length, true, input); yield return (@"abc|def", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); yield return (@"abc|def", upper, RegexOptions.None, 0, input.Length, false, ""); // Three branches yield return (@"abc|agh|def", input, RegexOptions.None, 0, input.Length, true, input); yield return (@"abc|agh|def", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); yield return (@"abc|agh|def", upper, RegexOptions.None, 0, input.Length, false, ""); // Four branches yield return (@"abc|agh|def|aij", input, RegexOptions.None, 0, input.Length, true, input); yield return (@"abc|agh|def|aij", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); yield return (@"abc|agh|def|aij", upper, RegexOptions.None, 0, input.Length, false, ""); // Four branches (containing various other constructs) if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"abc|(agh)|(?=def)def|(?:(?(aij)aij|(?!)))", input, RegexOptions.None, 0, input.Length, true, input); yield return (@"abc|(agh)|(?=def)def|(?:(?(aij)aij|(?!)))", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); yield return (@"abc|(agh)|(?=def)def|(?:(?(aij)aij|(?!)))", upper, RegexOptions.None, 0, input.Length, false, ""); } // Sets in various positions in each branch yield return (@"a\wc|\wgh|de\w", input, RegexOptions.None, 0, input.Length, true, input); yield return (@"a\wc|\wgh|de\w", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); yield return (@"a\wc|\wgh|de\w", upper, RegexOptions.None, 0, input.Length, false, ""); } yield return ("[^a-z0-9]etag|[^a-z0-9]digest", "this string has .digest as a substring", RegexOptions.None, 16, 7, true, ".digest"); yield return (@"(\w+|\d+)a+[ab]+", "123123aa", RegexOptions.None, 0, 8, true, "123123aa"); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return ("(?(dog2))", "dog2", RegexOptions.None, 0, 4, true, string.Empty); yield return ("(?(a:b))", "a", RegexOptions.None, 0, 1, true, string.Empty); yield return ("(?(a:))", "a", RegexOptions.None, 0, 1, true, string.Empty); yield return ("(?(cat)cat|dog)", "cat", RegexOptions.None, 0, 3, true, "cat"); yield return ("(?((?=cat))cat|dog)", "cat", RegexOptions.None, 0, 3, true, "cat"); yield return ("(?(cat)|dog)", "cat", RegexOptions.None, 0, 3, true, string.Empty); yield return ("(?(cat)|dog)", "catdog", RegexOptions.None, 0, 6, true, string.Empty); yield return ("(?(cat)|dog)", "oof", RegexOptions.None, 0, 3, false, string.Empty); yield return ("(?(cat)dog1|dog2)", "catdog1", RegexOptions.None, 0, 7, false, string.Empty); yield return ("(?(cat)dog1|dog2)", "catdog2", RegexOptions.None, 0, 7, true, "dog2"); yield return ("(?(cat)dog1|dog2)", "catdog1dog2", RegexOptions.None, 0, 11, true, "dog2"); yield return (@"(?(\w+)\w+)dog", "catdog", RegexOptions.None, 0, 6, true, "catdog"); yield return (@"(?(abc)\w+|\w{0,2})dog", "catdog", RegexOptions.None, 0, 6, true, "atdog"); yield return (@"(?(abc)cat|\w{0,2})dog", "catdog", RegexOptions.None, 0, 6, true, "atdog"); yield return ("(a|ab|abc|abcd)d", "abcd", RegexOptions.RightToLeft, 0, 4, true, "abcd"); yield return ("(?>(?:a|ab|abc|abcd))d", "abcd", RegexOptions.None, 0, 4, false, string.Empty); yield return ("(?>(?:a|ab|abc|abcd))d", "abcd", RegexOptions.RightToLeft, 0, 4, true, "abcd"); } // No Negation yield return ("[abcd-[abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return ("[1234-[1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // All Negation yield return ("[^abcd-[^abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return ("[^1234-[^1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // No Negation yield return ("[a-z-[a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return ("[0-9-[0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // All Negation yield return ("[^a-z-[^a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return ("[^0-9-[^0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // No Negation yield return (@"[\w-[\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\W-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\s-[\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\S-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\d-[\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\D-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // All Negation yield return (@"[^\w-[^\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\W-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\s-[^\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\S-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\d-[^\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\D-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // MixedNegation yield return (@"[^\w-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\w-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\s-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\s-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\d-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\d-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // No Negation yield return (@"[\p{Ll}-[\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\P{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\p{Lu}-[\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\P{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\p{Nd}-[\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\P{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // All Negation yield return (@"[^\p{Ll}-[^\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\P{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\p{Lu}-[^\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\P{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\p{Nd}-[^\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\P{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // MixedNegation yield return (@"[^\p{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\p{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\p{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\p{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\p{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\p{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // Character Class Substraction yield return (@"[ab\-\[cd-[-[]]]]", "[]]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[ab\-\[cd-[-[]]]]", "-]]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[ab\-\[cd-[-[]]]]", "`]]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[ab\-\[cd-[-[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[ab\-\[cd-[[]]]]", "']]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[ab\-\[cd-[[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[a-[a-f]]", "abcdefghijklmnopqrstuvwxyz", RegexOptions.None, 0, 26, false, string.Empty); // \c if (!PlatformDetection.IsNetFramework) // missing fix for https://github.com/dotnet/runtime/issues/24759 { yield return (@"(cat)(\c[*)(dog)", "asdlkcat\u00FFdogiwod", RegexOptions.None, 0, 15, false, string.Empty); } // Surrogate pairs split up into UTF-16 code units. yield return (@"(\uD82F[\uDCA0-\uDCA3])", "\uD82F\uDCA2", RegexOptions.CultureInvariant, 0, 2, true, "\uD82F\uDCA2"); // Unicode text foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.RightToLeft, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant }) { if (engine != RegexEngine.NonBacktracking || options != RegexOptions.RightToLeft) { yield return ("\u05D0\u05D1\u05D2\u05D3(\u05D4\u05D5|\u05D6\u05D7|\u05D8)", "abc\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5def", options, 3, 6, true, "\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5"); yield return ("\u05D0(\u05D4\u05D5|\u05D6\u05D7|\u05D8)", "\u05D0\u05D8", options, 0, 2, true, "\u05D0\u05D8"); yield return ("\u05D0(?:\u05D1|\u05D2|\u05D3)", "\u05D0\u05D2", options, 0, 2, true, "\u05D0\u05D2"); yield return ("\u05D0(?:\u05D1|\u05D2|\u05D3)", "\u05D0\u05D4", options, 0, 0, false, ""); } } // .* : Case sensitive yield return (@".*\nfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@"a.*\nfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@".*\nFoo", $"\nFooThis should match", RegexOptions.None, 0, 21, true, "\nFoo"); yield return (@".*\nfoo", "\nfooThis should match", RegexOptions.None, 4, 17, false, ""); yield return (@".*?\nfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@"a.*?\nfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@".*?\nFoo", $"\nFooThis should match", RegexOptions.None, 0, 21, true, "\nFoo"); yield return (@".*?\nfoo", "\nfooThis should match", RegexOptions.None, 4, 17, false, ""); yield return (@".*\dfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@".*\dFoo", "This1Foo should match", RegexOptions.None, 0, 21, true, "This1Foo"); yield return (@".*\dFoo", "This1foo should 2Foo match", RegexOptions.None, 0, 26, true, "This1foo should 2Foo"); yield return (@".*\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None, 0, 29, false, ""); yield return (@".*\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None, 24, 5, false, ""); yield return (@".*?\dfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@".*?\dFoo", "This1Foo should match", RegexOptions.None, 0, 21, true, "This1Foo"); yield return (@".*?\dFoo", "This1foo should 2Foo match", RegexOptions.None, 0, 26, true, "This1foo should 2Foo"); yield return (@".*?\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None, 0, 29, false, ""); yield return (@".*?\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None, 24, 5, false, ""); yield return (@".*\dfoo", "1fooThis1foo should 1foo match", RegexOptions.None, 4, 9, true, "This1foo"); yield return (@".*\dfoo", "This shouldn't match 1foo", RegexOptions.None, 0, 20, false, ""); yield return (@".*?\dfoo", "1fooThis1foo should 1foo match", RegexOptions.None, 4, 9, true, "This1foo"); yield return (@".*?\dfoo", "This shouldn't match 1foo", RegexOptions.None, 0, 20, false, ""); // Turkish case sensitivity yield return (@"[\u0120-\u0130]", "\u0130", RegexOptions.None, 0, 1, true, "\u0130"); // .* : Case insensitive yield return (@".*\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase, 0, 21, true, "\nfoo"); yield return (@".*\dFoo", "This1foo should match", RegexOptions.IgnoreCase, 0, 21, true, "This1foo"); yield return (@".*\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo should 2FoO"); yield return (@".*\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo should 2fOo"); yield return (@".*\dfoo", "1fooThis1FOO should 1foo match", RegexOptions.IgnoreCase, 4, 9, true, "This1FOO"); yield return (@".*?\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase, 0, 21, true, "\nfoo"); yield return (@".*?\dFoo", "This1foo should match", RegexOptions.IgnoreCase, 0, 21, true, "This1foo"); yield return (@".*?\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo"); yield return (@".*?\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo"); yield return (@".*?\dFo{2}", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo"); yield return (@".*?\dFo{2}", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo"); yield return (@".*?\dfoo", "1fooThis1FOO should 1foo match", RegexOptions.IgnoreCase, 4, 9, true, "This1FOO"); if (!RegexHelpers.IsNonBacktracking(engine)) { // RightToLeft yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 0, 32, true, "foo4567890"); yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 22, true, "foo4567890"); yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 4, true, "foo4"); yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 3, false, string.Empty); yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 11, 21, false, string.Empty); yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 0, 32, true, "foo4567890"); yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 22, true, "foo4567890"); yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 4, true, "foo4"); yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 3, false, string.Empty); yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 11, 21, false, string.Empty); yield return (@"\s+\d+", "sdf 12sad", RegexOptions.RightToLeft, 0, 9, true, " 12"); yield return (@"\s+\d+", " asdf12 ", RegexOptions.RightToLeft, 0, 6, false, string.Empty); yield return ("aaa", "aaabbb", RegexOptions.None, 3, 3, false, string.Empty); yield return ("abc|def", "123def456", RegexOptions.RightToLeft | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 9, true, "def"); // .* : RTL, Case-sensitive yield return (@".*\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*\nfoo", "This should matchfoo\n", RegexOptions.None | RegexOptions.RightToLeft, 4, 13, false, ""); yield return (@"a.*\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*\nFoo", $"This should match\nFoo", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "This should match\nFoo"); yield return (@".*?\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*?\nfoo", "This should matchfoo\n", RegexOptions.None | RegexOptions.RightToLeft, 4, 13, false, ""); yield return (@"a.*?\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*?\nFoo", $"This should match\nFoo", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "\nFoo"); yield return (@".*\dfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*\dFoo", "This1Foo should match", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "This1Foo"); yield return (@".*\dFoo", "This1foo should 2Foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 26, true, "This1foo should 2Foo"); yield return (@".*\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 29, false, ""); yield return (@".*\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 19, 0, false, ""); yield return (@".*?\dfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*?\dFoo", "This1Foo should match", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "1Foo"); yield return (@".*?\dFoo", "This1foo should 2Foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 26, true, "2Foo"); yield return (@".*?\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 29, false, ""); yield return (@".*?\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 19, 0, false, ""); yield return (@".*\dfoo", "1fooThis2foo should 1foo match", RegexOptions.None | RegexOptions.RightToLeft, 8, 4, true, "2foo"); yield return (@".*\dfoo", "This shouldn't match 1foo", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*?\dfoo", "1fooThis2foo should 1foo match", RegexOptions.None | RegexOptions.RightToLeft, 8, 4, true, "2foo"); yield return (@".*?\dfoo", "This shouldn't match 1foo", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); // .* : RTL, case insensitive yield return (@".*\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "\nfoo"); yield return (@".*\dFoo", "This1foo should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "This1foo"); yield return (@".*\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 26, true, "This1foo should 2FoO"); yield return (@".*\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 26, true, "This1Foo should 2fOo"); yield return (@".*\dfoo", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 8, 4, true, "2FOO"); yield return (@"[\w\s].*", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "1fooThis2FOO should 1foo match"); yield return (@"i.*", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "is2FOO should 1foo match"); yield return (@".*?\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "\nfoo"); yield return (@".*?\dFoo", "This1foo should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "1foo"); yield return (@".*?\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 26, true, "2FoO"); yield return (@".*?\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 26, true, "2fOo"); yield return (@".*?\dfoo", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 8, 4, true, "2FOO"); yield return (@"[\w\s].*?", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "h"); yield return (@"i.*?", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "is2FOO should 1foo match"); } // [ActiveIssue("https://github.com/dotnet/runtime/issues/36149")] //if (PlatformDetection.IsNetCore) //{ // // Unicode symbols in character ranges. These are chars whose lowercase values cannot be found by using the offsets specified in s_lcTable. // yield return (@"^(?i:[\u00D7-\u00D8])$", '\u00F7'.ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u00C0-\u00DE])$", '\u00F7'.ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u00C0-\u00DE])$", ((char)('\u00C0' + 32)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u00C0' + 32)).ToString()); // yield return (@"^(?i:[\u00C0-\u00DE])$", ((char)('\u00DE' + 32)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u00DE' + 32)).ToString()); // yield return (@"^(?i:[\u0391-\u03AB])$", ((char)('\u03A2' + 32)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u0391-\u03AB])$", ((char)('\u0391' + 32)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u0391' + 32)).ToString()); // yield return (@"^(?i:[\u0391-\u03AB])$", ((char)('\u03AB' + 32)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u03AB' + 32)).ToString()); // yield return (@"^(?i:[\u1F18-\u1F1F])$", ((char)('\u1F1F' - 8)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u1F18-\u1F1F])$", ((char)('\u1F18' - 8)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u1F18' - 8)).ToString()); // yield return (@"^(?i:[\u10A0-\u10C5])$", ((char)('\u10A0' + 7264)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u10A0' + 7264)).ToString()); // yield return (@"^(?i:[\u10A0-\u10C5])$", ((char)('\u1F1F' + 48)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u24B6-\u24D0])$", ((char)('\u24D0' + 26)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u24B6-\u24D0])$", ((char)('\u24CF' + 26)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u24CF' + 26)).ToString()); //} // Long inputs string longCharacterRange = string.Concat(Enumerable.Range(1, 0x2000).Select(c => (char)c)); foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.IgnoreCase }) { yield return ("\u1000", longCharacterRange, options, 0, 0x2000, true, "\u1000"); yield return ("[\u1000-\u1001]", longCharacterRange, options, 0, 0x2000, true, "\u1000"); yield return ("[\u0FF0-\u0FFF][\u1000-\u1001]", longCharacterRange, options, 0, 0x2000, true, "\u0FFF\u1000"); yield return ("\uA640", longCharacterRange, options, 0, 0x2000, false, ""); yield return ("[\u3000-\u3001]", longCharacterRange, options, 0, 0x2000, false, ""); yield return ("[\uA640-\uA641][\u3000-\u3010]", longCharacterRange, options, 0, 0x2000, false, ""); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return ("\u1000", longCharacterRange, options | RegexOptions.RightToLeft, 0, 0x2000, true, "\u1000"); yield return ("[\u1000-\u1001]", longCharacterRange, options | RegexOptions.RightToLeft, 0, 0x2000, true, "\u1001"); yield return ("[\u1000][\u1001-\u1010]", longCharacterRange, options, 0, 0x2000, true, "\u1000\u1001"); yield return ("\uA640", longCharacterRange, options | RegexOptions.RightToLeft, 0, 0x2000, false, ""); yield return ("[\u3000-\u3001][\uA640-\uA641]", longCharacterRange, options | RegexOptions.RightToLeft, 0, 0x2000, false, ""); } } foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.Singleline }) { yield return (@"\W.*?\D", "seq 012 of 3 digits", options, 0, 19, true, " 012 "); yield return (@"\W.+?\D", "seq 012 of 3 digits", options, 0, 19, true, " 012 "); yield return (@"\W.{1,7}?\D", "seq 012 of 3 digits", options, 0, 19, true, " 012 "); yield return (@"\W.{1,2}?\D", "seq 012 of 3 digits", options, 0, 19, true, " of"); yield return (@"\W.*?\b", "digits:0123456789", options, 0, 17, true, ":"); yield return (@"\B.*?\B", "e.g:abc", options, 0, 7, true, ""); yield return (@"\B\W+?", "e.g:abc", options, 0, 7, false, ""); yield return (@"\B\W*?", "e.g:abc", options, 0, 7, true, ""); // While not lazy loops themselves, variants of the prior case that should give same results here yield return (@"\B\W*", "e.g:abc", options, 0, 7, true, ""); yield return (@"\B\W?", "e.g:abc", options, 0, 7, true, ""); //mixed lazy and eager counting yield return ("z(a{0,5}|a{0,10}?)", "xyzaaaaaaaaaxyz", options, 0, 15, true, "zaaaaa"); } } } [Theory] [MemberData(nameof(Match_MemberData))] public void Match(RegexEngine engine, string pattern, string input, RegexOptions options, Regex r, int beginning, int length, bool expectedSuccess, string expectedValue) { bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning); bool isDefaultCount = RegexHelpers.IsDefaultCount(input, options, length); // Test instance method overloads if (isDefaultStart && isDefaultCount) { VerifyMatch(r.Match(input)); VerifyIsMatch(r, input, expectedSuccess, Regex.InfiniteMatchTimeout); } if (beginning + length == input.Length && (options & RegexOptions.RightToLeft) == 0) { VerifyMatch(r.Match(input, beginning)); } VerifyMatch(r.Match(input, beginning, length)); // Test static method overloads if (isDefaultStart && isDefaultCount) { switch (engine) { case RegexEngine.Interpreter: case RegexEngine.Compiled: case RegexEngine.NonBacktracking: VerifyMatch(Regex.Match(input, pattern, options | RegexHelpers.OptionsFromEngine(engine))); VerifyIsMatch(null, input, expectedSuccess, Regex.InfiniteMatchTimeout, pattern, options | RegexHelpers.OptionsFromEngine(engine)); break; } } void VerifyMatch(Match match) { Assert.Equal(expectedSuccess, match.Success); RegexAssert.Equal(expectedValue, match); // Groups can never be empty Assert.True(match.Groups.Count >= 1); Assert.Equal(expectedSuccess, match.Groups[0].Success); RegexAssert.Equal(expectedValue, match.Groups[0]); } } private async Task CreateAndMatch(RegexEngine engine, string pattern, string input, RegexOptions options, int beginning, int length, bool expectedSuccess, string expectedValue) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); Match(engine, pattern, input, options, r, beginning, length, expectedSuccess, expectedValue); } public static IEnumerable<object[]> Match_VaryingLengthStrings_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { foreach (int length in new[] { 2, 3, 7, 8, 9, 64 }) { yield return new object[] { engine, RegexOptions.None, length }; yield return new object[] { engine, RegexOptions.IgnoreCase, length }; yield return new object[] { engine, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, length }; } } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Takes several minutes on .NET Framework")] [Theory] [MemberData(nameof(Match_VaryingLengthStrings_MemberData))] public async Task Match_VaryingLengthStrings(RegexEngine engine, RegexOptions options, int length) { bool caseInsensitive = (options & RegexOptions.IgnoreCase) != 0; string pattern = "[123]" + string.Concat(Enumerable.Range(0, length).Select(i => (char)('A' + (i % 26)))); string input = "2" + string.Concat(Enumerable.Range(0, length).Select(i => (char)((caseInsensitive ? 'a' : 'A') + (i % 26)))); Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); Match(engine, pattern, input, options, r, 0, input.Length, expectedSuccess: true, expectedValue: input); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Takes several minutes on .NET Framework")] [OuterLoop("Takes several seconds")] [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_VaryingLengthStrings_Huge(RegexEngine engine) { await Match_VaryingLengthStrings(engine, RegexOptions.None, 100_000); } public static IEnumerable<object[]> Match_DeepNesting_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { if (RegexHelpers.IsNonBacktracking(engine)) { // expression uses atomic group continue; } yield return new object[] { engine, 1 }; yield return new object[] { engine, 10 }; yield return new object[] { engine, 100 }; } } [Theory] [MemberData(nameof(Match_DeepNesting_MemberData))] public async void Match_DeepNesting(RegexEngine engine, int count) { const string Start = @"((?>abc|(?:def[ghi]", End = @")))"; const string Match = "defg"; string pattern = string.Concat(Enumerable.Repeat(Start, count)) + string.Concat(Enumerable.Repeat(End, count)); string input = string.Concat(Enumerable.Repeat(Match, count)); Regex r = await RegexHelpers.GetRegexAsync(engine, pattern); Match m = r.Match(input); Assert.True(m.Success); RegexAssert.Equal(input, m); Assert.Equal(count + 1, m.Groups.Count); } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_Timeout(RegexEngine engine) { Regex regex = await RegexHelpers.GetRegexAsync(engine, @"\p{Lu}", RegexOptions.IgnoreCase, TimeSpan.FromHours(1)); Match match = regex.Match("abc"); Assert.True(match.Success); RegexAssert.Equal("a", match); } /// <summary> /// Test that timeout exception is being thrown. /// </summary> [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] private async Task Match_TestThatTimeoutHappens(RegexEngine engine) { var rnd = new Random(42); var chars = new char[1_000_000]; for (int i = 0; i < chars.Length; i++) { byte b = (byte)rnd.Next(0, 256); chars[i] = b < 200 ? 'a' : (char)b; } string input = new string(chars); Regex re = await RegexHelpers.GetRegexAsync(engine, @"a.{20}^", RegexOptions.None, TimeSpan.FromMilliseconds(10)); Assert.Throws<RegexMatchTimeoutException>(() => { re.Match(input); }); } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_Timeout_Throws(RegexEngine engine) { if (RegexHelpers.IsNonBacktracking(engine)) { // test relies on backtracking taking a long time return; } const string Pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$"; string input = new string('a', 50) + "@a.a"; Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.None, TimeSpan.FromMilliseconds(100)); Assert.Throws<RegexMatchTimeoutException>(() => r.Match(input)); } // TODO: Figure out what to do with default timeouts for source generated regexes [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [InlineData(RegexOptions.None)] [InlineData(RegexOptions.Compiled)] public void Match_DefaultTimeout_Throws(RegexOptions options) { RemoteExecutor.Invoke(optionsString => { const string Pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$"; string input = new string('a', 50) + "@a.a"; AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, TimeSpan.FromMilliseconds(100)); if ((RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture) == RegexOptions.None) { Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern).Match(input)); Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern).IsMatch(input)); Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern).Matches(input).Count); Assert.Throws<RegexMatchTimeoutException>(() => Regex.Match(input, Pattern)); Assert.Throws<RegexMatchTimeoutException>(() => Regex.IsMatch(input, Pattern)); Assert.Throws<RegexMatchTimeoutException>(() => Regex.Matches(input, Pattern).Count); } Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture)).Match(input)); Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture)).IsMatch(input)); Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture)).Matches(input).Count); Assert.Throws<RegexMatchTimeoutException>(() => Regex.Match(input, Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture))); Assert.Throws<RegexMatchTimeoutException>(() => Regex.IsMatch(input, Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture))); Assert.Throws<RegexMatchTimeoutException>(() => Regex.Matches(input, Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture)).Count); }, ((int)options).ToString(CultureInfo.InvariantCulture)).Dispose(); } // TODO: Figure out what to do with default timeouts for source generated regexes [Theory] [InlineData(RegexOptions.None)] [InlineData(RegexOptions.Compiled)] public void Match_CachedPattern_NewTimeoutApplies(RegexOptions options) { const string PatternLeadingToLotsOfBacktracking = @"^(\w+\s?)*$"; VerifyIsMatch(null, "", true, TimeSpan.FromDays(1), PatternLeadingToLotsOfBacktracking, options); var sw = Stopwatch.StartNew(); VerifyIsMatchThrows<RegexMatchTimeoutException>(null, "An input string that takes a very very very very very very very very very very very long time!", TimeSpan.FromMilliseconds(1), PatternLeadingToLotsOfBacktracking, options); Assert.InRange(sw.Elapsed.TotalSeconds, 0, 10); // arbitrary upper bound that should be well above what's needed with a 1ms timeout } // On 32-bit we can't test these high inputs as they cause OutOfMemoryExceptions. // On Linux, we may get killed by the OOM Killer; on Windows, it will swap instead [OuterLoop("Can take several seconds")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess), nameof(PlatformDetection.IsWindows))] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_Timeout_Loop_Throws(RegexEngine engine) { if (RegexHelpers.IsNonBacktracking(engine)) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/60623")] return; } Regex regex = await RegexHelpers.GetRegexAsync(engine, @"a\s+", RegexOptions.None, TimeSpan.FromSeconds(1)); string input = "a" + new string(' ', 800_000_000) + " "; Assert.Throws<RegexMatchTimeoutException>(() => regex.Match(input)); } // On 32-bit we can't test these high inputs as they cause OutOfMemoryExceptions. // On Linux, we may get killed by the OOM Killer; on Windows, it will swap instead [OuterLoop("Can take several seconds")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess), nameof(PlatformDetection.IsWindows))] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_Timeout_Repetition_Throws(RegexEngine engine) { if (engine == RegexEngine.NonBacktracking) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/65991")] return; } int repetitionCount = 800_000_000; Regex regex = await RegexHelpers.GetRegexAsync(engine, @"a\s{" + repetitionCount + "}", RegexOptions.None, TimeSpan.FromSeconds(1)); string input = @"a" + new string(' ', repetitionCount) + @"b"; Assert.Throws<RegexMatchTimeoutException>(() => regex.Match(input)); } public static IEnumerable<object[]> Match_Advanced_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { // \B special character escape: ".*\\B(SUCCESS)\\B.*" yield return new object[] { engine, @".*\B(SUCCESS)\B.*", "adfadsfSUCCESSadsfadsf", RegexOptions.None, 0, 22, new CaptureData[] { new CaptureData("adfadsfSUCCESSadsfadsf", 0, 22), new CaptureData("SUCCESS", 7, 7) } }; // Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$" yield return new object[] { engine, "^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8, new CaptureData[] { new CaptureData("aaabb.cc", 0, 8), new CaptureData("bb.c", 3, 4), new CaptureData("c", 7, 1) } }; // Using greedy quantifiers: Actual - "(a+)(b*)(c?)" yield return new object[] { engine, "(a+)(b*)(c?)", "aaabbbccc", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("aaabbbc", 0, 7), new CaptureData("aaa", 0, 3), new CaptureData("bbb", 3, 3), new CaptureData("c", 6, 1) } }; // Using lazy quantifiers: Actual - "(d+?)(e*?)(f??)" // Interesting match from this pattern and input. If needed to go to the end of the string change the ? to + in the last lazy quantifier yield return new object[] { engine, "(d+?)(e*?)(f??)", "dddeeefff", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("d", 0, 1), new CaptureData("d", 0, 1), new CaptureData(string.Empty, 1, 0), new CaptureData(string.Empty, 1, 0) } }; yield return new object[] { engine, "(d+?)(e*?)(f+)", "dddeeefff", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("dddeeefff", 0, 9), new CaptureData("ddd", 0, 3), new CaptureData("eee", 3, 3), new CaptureData("fff", 6, 3), } }; // Noncapturing group : Actual - "(a+)(?:b*)(ccc)" yield return new object[] { engine, "(a+)(?:b*)(ccc)", "aaabbbccc", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("aaabbbccc", 0, 9), new CaptureData("aaa", 0, 3), new CaptureData("ccc", 6, 3), } }; // Alternation constructs: Actual - "(111|aaa)" yield return new object[] { engine, "(111|aaa)", "aaa", RegexOptions.None, 0, 3, new CaptureData[] { new CaptureData("aaa", 0, 3), new CaptureData("aaa", 0, 3) } }; // Using "n" Regex option. Only explicitly named groups should be captured: Actual - "([0-9]*)\\s(?<s>[a-z_A-Z]+)", "n" yield return new object[] { engine, @"([0-9]*)\s(?<s>[a-z_A-Z]+)", "200 dollars", RegexOptions.ExplicitCapture, 0, 11, new CaptureData[] { new CaptureData("200 dollars", 0, 11), new CaptureData("dollars", 4, 7) } }; // Single line mode "s". Includes new line character: Actual - "([^/]+)","s" yield return new object[] { engine, "(.*)", "abc\nsfc", RegexOptions.Singleline, 0, 7, new CaptureData[] { new CaptureData("abc\nsfc", 0, 7), new CaptureData("abc\nsfc", 0, 7), } }; // "([0-9]+(\\.[0-9]+){3})" yield return new object[] { engine, @"([0-9]+(\.[0-9]+){3})", "209.25.0.111", RegexOptions.None, 0, 12, new CaptureData[] { new CaptureData("209.25.0.111", 0, 12), new CaptureData("209.25.0.111", 0, 12), new CaptureData(".111", 8, 4, new CaptureData[] { new CaptureData(".25", 3, 3), new CaptureData(".0", 6, 2), new CaptureData(".111", 8, 4), }), } }; // Groups and captures yield return new object[] { engine, @"(?<A1>a*)(?<A2>b*)(?<A3>c*)", "aaabbccccccccccaaaabc", RegexOptions.None, 0, 21, new CaptureData[] { new CaptureData("aaabbcccccccccc", 0, 15), new CaptureData("aaa", 0, 3), new CaptureData("bb", 3, 2), new CaptureData("cccccccccc", 5, 10) } }; yield return new object[] { engine, @"(?<A1>A*)(?<A2>B*)(?<A3>C*)", "aaabbccccccccccaaaabc", RegexOptions.IgnoreCase, 0, 21, new CaptureData[] { new CaptureData("aaabbcccccccccc", 0, 15), new CaptureData("aaa", 0, 3), new CaptureData("bb", 3, 2), new CaptureData("cccccccccc", 5, 10) } }; // Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$" yield return new object[] { engine, "^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8, new CaptureData[] { new CaptureData("aaabb.cc", 0, 8), new CaptureData("bb.c", 3, 4), new CaptureData("c", 7, 1) } }; // Actual - ".*\\b(\\w+)\\b" yield return new object[] { engine, @".*\b(\w+)\b", "XSP_TEST_FAILURE SUCCESS", RegexOptions.None, 0, 24, new CaptureData[] { new CaptureData("XSP_TEST_FAILURE SUCCESS", 0, 24), new CaptureData("SUCCESS", 17, 7) } }; // Multiline yield return new object[] { engine, "(line2$\n)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; // Multiline yield return new object[] { engine, "(line2\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; // Multiline yield return new object[] { engine, "(line3\n$\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line3\n\nline4", 12, 12), new CaptureData("line3\n\n", 12, 7) } }; // Multiline yield return new object[] { engine, "(line3\n^\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line3\n\nline4", 12, 12), new CaptureData("line3\n\n", 12, 7) } }; // Multiline yield return new object[] { engine, "(line2$\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; if (!RegexHelpers.IsNonBacktracking(engine)) { // Zero-width positive lookahead assertion: Actual - "abc(?=XXX)\\w+" yield return new object[] { engine, @"abc(?=XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("abcXXXdef", 0, 9) } }; // Backreferences : Actual - "(\\w)\\1" yield return new object[] { engine, @"(\w)\1", "aa", RegexOptions.None, 0, 2, new CaptureData[] { new CaptureData("aa", 0, 2), new CaptureData("a", 0, 1), } }; // Actual - "(?<1>\\d+)abc(?(1)222|111)" yield return new object[] { engine, @"(?<MyDigits>\d+)abc(?(MyDigits)222|111)", "111abc222", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("111abc222", 0, 9), new CaptureData("111", 0, 3) } }; // RightToLeft yield return new object[] { engine, "aaa", "aaabbb", RegexOptions.RightToLeft, 3, 3, new CaptureData[] { new CaptureData("aaa", 0, 3) } }; // RightToLeft with anchor yield return new object[] { engine, "^aaa", "aaabbb", RegexOptions.RightToLeft, 3, 3, new CaptureData[] { new CaptureData("aaa", 0, 3) } }; yield return new object[] { engine, "bbb$", "aaabbb", RegexOptions.RightToLeft, 0, 3, new CaptureData[] { new CaptureData("bbb", 0, 3) } }; } } } [Theory] [MemberData(nameof(Match_Advanced_TestData))] public async Task Match_Advanced(RegexEngine engine, string pattern, string input, RegexOptions options, int beginning, int length, CaptureData[] expected) { bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning); bool isDefaultCount = RegexHelpers.IsDefaultStart(input, options, length); Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); if (isDefaultStart && isDefaultCount) { // Use Match(string) or Match(string, string, RegexOptions) VerifyMatch(r.Match(input)); VerifyMatch(Regex.Match(input, pattern, options)); VerifyIsMatch(null, input, true, Regex.InfiniteMatchTimeout, pattern, options); } if (beginning + length == input.Length) { // Use Match(string, int) VerifyMatch(r.Match(input, beginning)); } if ((options & RegexOptions.RightToLeft) == 0) { // Use Match(string, int, int) VerifyMatch(r.Match(input, beginning, length)); } void VerifyMatch(Match match) { Assert.True(match.Success); RegexAssert.Equal(expected[0].Value, match); Assert.Equal(expected[0].Index, match.Index); Assert.Equal(expected[0].Length, match.Length); Assert.Equal(1, match.Captures.Count); RegexAssert.Equal(expected[0].Value, match.Captures[0]); Assert.Equal(expected[0].Index, match.Captures[0].Index); Assert.Equal(expected[0].Length, match.Captures[0].Length); Assert.Equal(expected.Length, match.Groups.Count); for (int i = 0; i < match.Groups.Count; i++) { Assert.True(match.Groups[i].Success); RegexAssert.Equal(expected[i].Value, match.Groups[i]); Assert.Equal(expected[i].Index, match.Groups[i].Index); Assert.Equal(expected[i].Length, match.Groups[i].Length); if (!RegexHelpers.IsNonBacktracking(engine)) { Assert.Equal(expected[i].Captures.Length, match.Groups[i].Captures.Count); for (int j = 0; j < match.Groups[i].Captures.Count; j++) { RegexAssert.Equal(expected[i].Captures[j].Value, match.Groups[i].Captures[j]); Assert.Equal(expected[i].Captures[j].Index, match.Groups[i].Captures[j].Index); Assert.Equal(expected[i].Captures[j].Length, match.Groups[i].Captures[j].Length); } } else { // NonBacktracking does not support multiple captures Assert.Equal(1, match.Groups[i].Captures.Count); int lastExpected = expected[i].Captures.Length - 1; RegexAssert.Equal(expected[i].Captures[lastExpected].Value, match.Groups[i].Captures[0]); Assert.Equal(expected[i].Captures[lastExpected].Index, match.Groups[i].Captures[0].Index); Assert.Equal(expected[i].Captures[lastExpected].Length, match.Groups[i].Captures[0].Length); } } } } public static IEnumerable<object[]> Match_StartatDiffersFromBeginning_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.Singleline, RegexOptions.Multiline, RegexOptions.Singleline | RegexOptions.Multiline }) { // Anchors yield return new object[] { engine, @"^.*", "abc", options, 0, true, true }; yield return new object[] { engine, @"^.*", "abc", options, 1, false, true }; } if (!RegexHelpers.IsNonBacktracking(engine)) { // Positive and negative lookbehinds yield return new object[] { engine, @"(?<=abc)def", "abcdef", RegexOptions.None, 3, true, false }; yield return new object[] { engine, @"(?<!abc)def", "abcdef", RegexOptions.None, 3, false, true }; } } } [Theory] [MemberData(nameof(Match_StartatDiffersFromBeginning_MemberData))] public async Task Match_StartatDiffersFromBeginning(RegexEngine engine, string pattern, string input, RegexOptions options, int startat, bool expectedSuccessStartAt, bool expectedSuccessBeginning) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); Assert.Equal(expectedSuccessStartAt, r.IsMatch(input, startat)); Assert.Equal(expectedSuccessStartAt, r.Match(input, startat).Success); Assert.Equal(expectedSuccessBeginning, r.Match(input.Substring(startat)).Success); Assert.Equal(expectedSuccessBeginning, r.Match(input, startat, input.Length - startat).Success); } [Theory] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${time}", "16:00")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${1}", "08")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${2}", "10")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${3}", "99")] [InlineData("abc", "abc", "abc", "abc")] public void Result(string pattern, string input, string replacement, string expected) { Assert.Equal(expected, new Regex(pattern).Match(input).Result(replacement)); } [Fact] public void Result_Invalid() { Match match = Regex.Match("foo", "foo"); AssertExtensions.Throws<ArgumentNullException>("replacement", () => match.Result(null)); Assert.Throws<NotSupportedException>(() => RegularExpressions.Match.Empty.Result("any")); } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_SpecialUnicodeCharacters_enUS(RegexEngine engine) { using (new ThreadCultureChange("en-US")) { await CreateAndMatch(engine, "\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); await CreateAndMatch(engine, "\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); } } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_SpecialUnicodeCharacters_Invariant(RegexEngine engine) { using (new ThreadCultureChange(CultureInfo.InvariantCulture)) { await CreateAndMatch(engine, "\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); await CreateAndMatch(engine, "\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); await CreateAndMatch(engine, "\u0130", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); await CreateAndMatch(engine, "\u0130", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); } } private static bool IsNotArmProcessAndRemoteExecutorSupported => PlatformDetection.IsNotArmProcess && RemoteExecutor.IsSupported; [ConditionalTheory(nameof(IsNotArmProcessAndRemoteExecutorSupported))] // times out on ARM [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework does not have fix for https://github.com/dotnet/runtime/issues/24749")] [SkipOnCoreClr("Long running tests: https://github.com/dotnet/runtime/issues/10680", ~RuntimeConfiguration.Release)] [SkipOnCoreClr("Long running tests: https://github.com/dotnet/runtime/issues/10680", RuntimeTestModes.JitMinOpts)] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public void Match_ExcessPrefix(RegexEngine engine) { RemoteExecutor.Invoke(async engineString => { var engine = (RegexEngine)Enum.Parse(typeof(RegexEngine), engineString); // Should not throw out of memory // Repeaters VerifyIsMatch((await RegexHelpers.GetRegexAsync(engine, @"a{2147483647,}")), "a", false, Regex.InfiniteMatchTimeout); VerifyIsMatch((await RegexHelpers.GetRegexAsync(engine, @"a{50,}")), "a", false, Regex.InfiniteMatchTimeout); VerifyIsMatch((await RegexHelpers.GetRegexAsync(engine, @"a{50_000,}")), "a", false, Regex.InfiniteMatchTimeout); // cutoff for Boyer-Moore prefix in release // Multis foreach (int length in new[] { 50, 50_000, char.MaxValue + 1 }) { // The large counters are too slow for counting a's in NonBacktracking engine // They will incur a constant of size length because in .*a{k} after reading n a's the // state will be .*a{k}|a{k-1}|...|a{k-n} which could be compacted to // .*a{k}|a{k-n,k-1} but is not currently being compacted if (!RegexHelpers.IsNonBacktracking(engine) || length < 50_000) { string s = "bcd" + new string('a', length) + "efg"; VerifyIsMatch((await RegexHelpers.GetRegexAsync(engine, @$"a{{{length}}}")), s, true, Regex.InfiniteMatchTimeout); } } }, engine.ToString()).Dispose(); } [Fact] public void Match_Invalid() { var r = new Regex("pattern"); // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => r.Match(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => r.Match(null, 0)); AssertExtensions.Throws<ArgumentNullException>("input", () => r.Match(null, 0, 0)); // Pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None, TimeSpan.FromSeconds(1))); // Start is invalid Assert.Throws<ArgumentOutOfRangeException>(() => r.Match("input", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => r.Match("input", -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => r.Match("input", 6)); Assert.Throws<ArgumentOutOfRangeException>(() => r.Match("input", 6, 0)); // Length is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => r.Match("input", 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => r.Match("input", 0, 6)); } [Fact] public void IsMatch_Invalid() { var r = new Regex("pattern"); // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => r.IsMatch(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => r.IsMatch(null, 0)); // Pattern is null VerifyIsMatchThrows<ArgumentNullException>(null, "input", Regex.InfiniteMatchTimeout, pattern: null); VerifyIsMatchThrows<ArgumentNullException>(null, "input", Regex.InfiniteMatchTimeout, pattern: null, RegexOptions.None); VerifyIsMatchThrows<ArgumentNullException>(null, "input", TimeSpan.FromSeconds(1), pattern: null, RegexOptions.None); // Start is invalid Assert.Throws<ArgumentOutOfRangeException>(() => r.IsMatch("input", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => r.IsMatch("input", 6)); } public static IEnumerable<object[]> IsMatch_SucceedQuicklyDueToLoopReduction_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, @"(?:\w*)+\.", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false }; yield return new object[] { engine, @"(?:a+)+b", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false }; yield return new object[] { engine, @"(?:x+x+)+y", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", false }; } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // take too long due to backtracking [Theory] [MemberData(nameof(IsMatch_SucceedQuicklyDueToLoopReduction_MemberData))] public async Task IsMatch_SucceedQuicklyDueToLoopReduction(RegexEngine engine, string pattern, string input, bool expected) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern); VerifyIsMatch(r, input, expected, Regex.InfiniteMatchTimeout); } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task TestCharIsLowerCultureEdgeCasesAroundTurkishCharacters(RegexEngine engine) { Regex r1 = await RegexHelpers.GetRegexAsync(engine, "[\u012F-\u0130]", RegexOptions.IgnoreCase); Regex r2 = await RegexHelpers.GetRegexAsync(engine, "[\u012F\u0130]", RegexOptions.IgnoreCase); Assert.Equal(r1.IsMatch("\u0130"), r2.IsMatch("\u0130")); #if NET7_0_OR_GREATER Assert.Equal(r1.IsMatch("\u0130".AsSpan()), r2.IsMatch("\u0130".AsSpan())); #endif } [Fact] public void Synchronized() { var m = new Regex("abc").Match("abc"); Assert.True(m.Success); RegexAssert.Equal("abc", m); var m2 = System.Text.RegularExpressions.Match.Synchronized(m); Assert.Same(m, m2); Assert.True(m2.Success); RegexAssert.Equal("abc", m2); AssertExtensions.Throws<ArgumentNullException>("inner", () => System.Text.RegularExpressions.Match.Synchronized(null)); } /// <summary> /// Tests current inconsistent treatment of \b and \w. /// The match fails because \u200c and \u200d do not belong to \w. /// At the same time \u200c and \u200d are considered as word characters for the \b and \B anchors. /// The test checks that the same behavior applies to all backends. /// </summary> [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_Boundary(RegexEngine engine) { Regex r = await RegexHelpers.GetRegexAsync(engine, @"\b\w+\b"); VerifyIsMatch(r, " AB\u200cCD ", false, Regex.InfiniteMatchTimeout); VerifyIsMatch(r, " AB\u200dCD ", false, Regex.InfiniteMatchTimeout); } public static IEnumerable<object[]> Match_Count_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, @"\b\w+\b", "one two three", 3 }; yield return new object[] { engine, @"\b\w+\b", "on\u200ce two three", 2 }; yield return new object[] { engine, @"\b\w+\b", "one tw\u200do three", 2 }; } string b1 = @"((?<=\w)(?!\w)|(?<!\w)(?=\w))"; string b2 = @"((?<=\w)(?=\W)|(?<=\W)(?=\w))"; // Lookarounds are currently not supported in the NonBacktracking engine foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { if (engine == RegexEngine.NonBacktracking) continue; // b1 is semantically identical to \b except for \u200c and \u200d yield return new object[] { engine, $@"{b1}\w+{b1}", "one two three", 3 }; yield return new object[] { engine, $@"{b1}\w+{b1}", "on\u200ce two three", 4 }; // contrast between using \W = [^\w] vs negative lookaround !\w yield return new object[] { engine, $@"{b2}\w+{b2}", "one two three", 1 }; yield return new object[] { engine, $@"{b2}\w+{b2}", "one two", 0 }; } } [Theory] [MemberData(nameof(Match_Count_TestData))] public async Task Match_Count(RegexEngine engine, string pattern, string input, int expectedCount) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern); Assert.Equal(expectedCount,r.Matches(input).Count); } public static IEnumerable<object[]> StressTestDeepNestingOfConcat_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, "[a-z]", "", "abcde", 2000, 400 }; yield return new object[] { engine, "[a-e]*", "$", "abcde", 2000, 20 }; yield return new object[] { engine, "[a-d]?[a-e]?[a-f]?[a-g]?[a-h]?", "$", "abcda", 400, 4 }; yield return new object[] { engine, "(a|A)", "", "aAaAa", 2000, 400 }; } } [OuterLoop("Can take over a minute")] [Theory] [MemberData(nameof(StressTestDeepNestingOfConcat_TestData))] public async Task StressTestDeepNestingOfConcat(RegexEngine engine, string pattern, string anchor, string input, int pattern_repetition, int input_repetition) { if (engine == RegexEngine.SourceGenerated) { // Currently too stressful for Roslyn. return; } if (engine == RegexEngine.NonBacktracking) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/60645")] return; } string fullpattern = string.Concat(string.Concat(Enumerable.Repeat($"({pattern}", pattern_repetition).Concat(Enumerable.Repeat(")", pattern_repetition))), anchor); string fullinput = string.Concat(Enumerable.Repeat(input, input_repetition)); Regex re = await RegexHelpers.GetRegexAsync(engine, fullpattern); Assert.True(re.Match(fullinput).Success); } public static IEnumerable<object[]> StressTestDeepNestingOfLoops_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, "(", "a", ")*", RegexOptions.None, "a", 2000, 1000 }; yield return new object[] { engine, "(", "[aA]", ")+", RegexOptions.None, "aA", 2000, 3000 }; yield return new object[] { engine, "(", "ab", "){0,1}", RegexOptions.None, "ab", 2000, 1000 }; } } [OuterLoop("Can take over 10 seconds")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))] // consumes a lot of memory [MemberData(nameof(StressTestDeepNestingOfLoops_TestData))] public async Task StressTestDeepNestingOfLoops(RegexEngine engine, string begin, string inner, string end, RegexOptions options, string input, int pattern_repetition, int input_repetition) { if (engine == RegexEngine.SourceGenerated) { // Currently too stressful for Roslyn. return; } string fullpattern = string.Concat(Enumerable.Repeat(begin, pattern_repetition)) + inner + string.Concat(Enumerable.Repeat(end, pattern_repetition)); string fullinput = string.Concat(Enumerable.Repeat(input, input_repetition)); var re = await RegexHelpers.GetRegexAsync(engine, fullpattern, options); Assert.True(re.Match(fullinput).Success); } public static IEnumerable<object[]> StressTestNfaMode_TestData() { yield return new object[] { "(?:a|aa|[abc]?[ab]?[abcd]).{20}$", "aaa01234567890123456789", 23 }; yield return new object[] { "(?:a|AA|BCD).{20}$", "a01234567890123456789", 21 }; yield return new object[] { "(?:a.{20}|a.{10})bc$", "a01234567890123456789bc", 23 }; } /// <summary> /// Causes NonBacktracking engine to switch to NFA mode internally. /// NFA mode is otherwise never triggered by typical cases. /// </summary> [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Doesn't support NonBacktracking")] [MemberData(nameof(StressTestNfaMode_TestData))] public async Task StressTestNfaMode(string pattern, string input_suffix, int expected_matchlength) { Random random = new Random(0); byte[] buffer = new byte[50_000]; random.NextBytes(buffer); // Consider a random string of 50_000 a's and b's var input = new string(Array.ConvertAll(buffer, b => (b <= 0x7F ? 'a' : 'b'))); input += input_suffix; Regex re = await RegexHelpers.GetRegexAsync(RegexEngine.NonBacktracking, pattern, RegexOptions.Singleline); Match m = re.Match(input); Assert.True(m.Success); Assert.Equal(buffer.Length, m.Index); Assert.Equal(expected_matchlength, m.Length); } public static IEnumerable<object[]> AllMatches_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { // Basic yield return new object[] { engine, @"a+", RegexOptions.None, "xxxxxaaaaxxxxxxxxxxaaaaaa", new (int, int, string)[] { (5, 4, "aaaa"), (19, 6, "aaaaaa") } }; yield return new object[] { engine, @"(...)+", RegexOptions.None, "abcd\nfghijklm", new (int, int, string)[] { (0, 3, "abc"), (5, 6, "fghijk") } }; yield return new object[] { engine, @"something", RegexOptions.None, "nothing", null }; yield return new object[] { engine, "(a|ba)c", RegexOptions.None, "bac", new (int, int, string)[] { (0, 3, "bac") } }; yield return new object[] { engine, "(a|ba)c", RegexOptions.None, "ac", new (int, int, string)[] { (0, 2, "ac") } }; yield return new object[] { engine, "(a|ba)c", RegexOptions.None, "baacd", new (int, int, string)[] { (2, 2, "ac") } }; yield return new object[] { engine, "\n", RegexOptions.None, "\n", new (int, int, string)[] { (0, 1, "\n") } }; yield return new object[] { engine, "[^a]", RegexOptions.None, "\n", new (int, int, string)[] { (0, 1, "\n") } }; // In Singleline mode . includes all characters, also \n yield return new object[] { engine, @"(...)+", RegexOptions.None | RegexOptions.Singleline, "abcd\nfghijklm", new (int, int, string)[] { (0, 12, "abcd\nfghijkl") } }; // Ignoring case yield return new object[] { engine, @"a+", RegexOptions.None | RegexOptions.IgnoreCase, "xxxxxaAAaxxxxxxxxxxaaaaAa", new (int, int, string)[] { (5, 4, "aAAa"), (19, 6, "aaaaAa") } }; // NonASCII characters yield return new object[] { engine, @"(\uFFFE\uFFFF)+", RegexOptions.None, "=====\uFFFE\uFFFF\uFFFE\uFFFF\uFFFE====", new (int, int, string)[] { (5, 4, "\uFFFE\uFFFF\uFFFE\uFFFF") } }; yield return new object[] { engine, @"\d\s\w+", RegexOptions.None, "=====1\v\u212A4==========1\ta\u0130Aa", new (int, int, string)[] { (5, 4, "1\v\u212A4"), (19, 6, "1\ta\u0130Aa") } }; yield return new object[] { engine, @"\u221E|\u2713", RegexOptions.None, "infinity \u221E and checkmark \u2713 are contained here", new (int, int, string)[] { (9, 1, "\u221E"), (25, 1, "\u2713") } }; // Whitespace yield return new object[] { engine, @"\s+", RegexOptions.None, "===== \n\t\v\r ====", new (int, int, string)[] { (5, 6, " \n\t\v\r ") } }; // Unicode character classes, the input string uses the first element of each character class yield return new object[] { engine, @"\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Mn}\p{Mc}\p{Me}\p{Nd}\p{Nl}", RegexOptions.None, "=====Aa\u01C5\u02B0\u01BB\u0300\u0903\u04880\u16EE===", new (int, int, string)[] { (5, 10, "Aa\u01C5\u02B0\u01BB\u0300\u0903\u04880\u16EE") } }; yield return new object[] { engine, @"\p{No}\p{Zs}\p{Zl}\p{Zp}\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Pc}\p{Pd}", RegexOptions.None, "=====\u00B2 \u2028\u2029\0\u0600\uD800\uE000_\u002D===", new (int, int, string)[] { (5, 10, "\u00B2 \u2028\u2029\0\u0600\uD800\uE000_\u002D") } }; yield return new object[] { engine, @"\p{Ps}\p{Pe}\p{Pi}\p{Pf}\p{Po}\p{Sm}\p{Sc}\p{Sk}\p{So}\p{Cn}", RegexOptions.None, "=====()\xAB\xBB!+$^\xA6\u0378===", new (int, int, string)[] { (5, 10, "()\xAB\xBB!+$^\xA6\u0378") } }; yield return new object[] { engine, @"\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Mn}\p{Mc}\p{Me}\p{Nd}\p{Nl}\p{No}\p{Zs}\p{Zl}\p{Zp}\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Pc}\p{Pd}\p{Ps}\p{Pe}\p{Pi}\p{Pf}\p{Po}\p{Sm}\p{Sc}\p{Sk}\p{So}\p{Cn}", RegexOptions.None, "=====Aa\u01C5\u02B0\u01BB\u0300\u0903\u04880\u16EE\xB2 \u2028\u2029\0\u0600\uD800\uE000_\x2D()\xAB\xBB!+$^\xA6\u0378===", new (int, int, string)[] { (5, 30, "Aa\u01C5\u02B0\u01BB\u0300\u0903\u04880\u16EE\xB2 \u2028\u2029\0\u0600\uD800\uE000_\x2D()\xAB\xBB!+$^\xA6\u0378") } }; // Case insensitive cases by using ?i and some non-ASCII characters like Kelvin sign and applying ?i over negated character classes yield return new object[] { engine, "(?i:[a-d\u00D5]+k*)", RegexOptions.None, "xyxaB\u00F5c\u212AKAyy", new (int, int, string)[] { (3, 6, "aB\u00F5c\u212AK"), (9, 1, "A") } }; yield return new object[] { engine, "(?i:[a-d]+)", RegexOptions.None, "xyxaBcyy", new (int, int, string)[] { (3, 3, "aBc") } }; yield return new object[] { engine, "(?i:[\0-@B-\uFFFF]+)", RegexOptions.None, "xaAaAy", new (int, int, string)[] { (0, 6, "xaAaAy") } }; // this is the same as .+ yield return new object[] { engine, "(?i:[\0-ac-\uFFFF])", RegexOptions.None, "b", new (int, int, string)[] { (0, 1, "b") } }; yield return new object[] { engine, "(?i:[\0-PR-\uFFFF])", RegexOptions.None, "Q", new (int, int, string)[] { (0, 1, "Q") } }; yield return new object[] { engine, "(?i:[\0-pr-\uFFFF])", RegexOptions.None, "q", new (int, int, string)[] { (0, 1, "q") } }; yield return new object[] { engine, "(?i:[^a])", RegexOptions.None, "aAaA", null }; // this correponds to not{a,A} yield return new object[] { engine, "(?i:[\0-\uFFFF-[A]])", RegexOptions.None, "aAaA", null }; // this correponds to not{a,A} yield return new object[] { engine, "(?i:[^Q])", RegexOptions.None, "q", null }; yield return new object[] { engine, "(?i:[^b])", RegexOptions.None, "b", null }; // Use of anchors yield return new object[] { engine, @"\b\w+nn\b", RegexOptions.None, "both Anne and Ann are names that contain nn", new (int, int, string)[] { (14, 3, "Ann") } }; yield return new object[] { engine, @"\B x", RegexOptions.None, " xx", new (int, int, string)[] { (0, 2, " x") } }; yield return new object[] { engine, @"\bxx\b", RegexOptions.None, " zxx:xx", new (int, int, string)[] { (5, 2, "xx") } }; yield return new object[] { engine, @"^abc*\B", RegexOptions.None | RegexOptions.Multiline, "\nabcc \nabcccd\n", new (int, int, string)[] { (1, 3, "abc"), (7, 5, "abccc") } }; yield return new object[] { engine, "^abc", RegexOptions.None, "abcccc", new (int, int, string)[] { (0, 3, "abc") } }; yield return new object[] { engine, "^abc", RegexOptions.None, "aabcccc", null }; yield return new object[] { engine, "abc$", RegexOptions.None, "aabcccc", null }; yield return new object[] { engine, @"abc\z", RegexOptions.None, "aabc\n", null }; yield return new object[] { engine, @"abc\Z", RegexOptions.None, "aabc\n", new (int, int, string)[] { (1, 3, "abc") } }; yield return new object[] { engine, "abc$", RegexOptions.None, "aabc\nabc", new (int, int, string)[] { (5, 3, "abc") } }; yield return new object[] { engine, "abc$", RegexOptions.None | RegexOptions.Multiline, "aabc\nabc", new (int, int, string)[] { (1, 3, "abc"), (5, 3, "abc") } }; yield return new object[] { engine, @"a\bb", RegexOptions.None, "ab", null }; yield return new object[] { engine, @"a\Bb", RegexOptions.None, "ab", new (int, int, string)[] { (0, 2, "ab") } }; yield return new object[] { engine, @"(a\Bb|a\bb)", RegexOptions.None, "ab", new (int, int, string)[] { (0, 2, "ab") } }; yield return new object[] { engine, @"a$", RegexOptions.None | RegexOptions.Multiline, "b\na", new (int, int, string)[] { (2, 1, "a") } }; // Various loop constructs yield return new object[] { engine, "a[bcd]{4,5}(.)", RegexOptions.None, "acdbcdbe", new (int, int, string)[] { (0, 7, "acdbcdb") } }; yield return new object[] { engine, "a[bcd]{4,5}?(.)", RegexOptions.None, "acdbcdbe", new (int, int, string)[] { (0, 6, "acdbcd") } }; yield return new object[] { engine, "(x{3})+", RegexOptions.None, "abcxxxxxxxxacacaca", new (int, int, string)[] { (3, 6, "xxxxxx") } }; yield return new object[] { engine, "(x{3})+?", RegexOptions.None, "abcxxxxxxxxacacaca", new (int, int, string)[] { (3, 3, "xxx"), (6, 3, "xxx") } }; yield return new object[] { engine, "a[0-9]+0", RegexOptions.None, "ababca123000xyz", new (int, int, string)[] { (5, 7, "a123000") } }; yield return new object[] { engine, "a[0-9]+?0", RegexOptions.None, "ababca123000xyz", new (int, int, string)[] { (5, 5, "a1230") } }; // Mixed lazy/eager loop yield return new object[] { engine, "a[0-9]+?0|b[0-9]+0", RegexOptions.None, "ababca123000xyzababcb123000xyz", new (int, int, string)[] { (5, 5, "a1230"), (20, 7, "b123000") } }; // Loops around alternations yield return new object[] { engine, "^(?:aaa|aa)*$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; yield return new object[] { engine, "^(?:aaa|aa)*?$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; yield return new object[] { engine, "^(?:aaa|aa){1,5}$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; yield return new object[] { engine, "^(?:aaa|aa){1,5}?$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; yield return new object[] { engine, "^(?:aaa|aa){4}$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; yield return new object[] { engine, "^(?:aaa|aa){4}?$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; // Mostly empty matches using unusual regexes consisting mostly of anchors only yield return new object[] { engine, "^", RegexOptions.None, "", new (int, int, string)[] { (0, 0, "") } }; yield return new object[] { engine, "$", RegexOptions.None, "", new (int, int, string)[] { (0, 0, "") } }; yield return new object[] { engine, "^$", RegexOptions.None, "", new (int, int, string)[] { (0, 0, "") } }; yield return new object[] { engine, "$^", RegexOptions.None, "", new (int, int, string)[] { (0, 0, "") } }; yield return new object[] { engine, "$^$$^^$^$", RegexOptions.None, "", new (int, int, string)[] { (0, 0, "") } }; yield return new object[] { engine, "a*", RegexOptions.None, "bbb", new (int, int, string)[] { (0, 0, ""), (1, 0, ""), (2, 0, ""), (3, 0, "") } }; yield return new object[] { engine, "a*", RegexOptions.None, "baaabb", new (int, int, string)[] { (0, 0, ""), (1, 3, "aaa"), (4, 0, ""), (5, 0, ""), (6, 0, "") } }; yield return new object[] { engine, @"\b", RegexOptions.None, "hello--world", new (int, int, string)[] { (0, 0, ""), (5, 0, ""), (7, 0, ""), (12, 0, "") } }; yield return new object[] { engine, @"\B", RegexOptions.None, "hello--world", new (int, int, string)[] { (1, 0, ""), (2, 0, ""), (3, 0, ""), (4, 0, ""), (6, 0, ""), (8, 0, ""), (9, 0, ""), (10, 0, ""), (11, 0, "") } }; // Involving many different characters in the same regex yield return new object[] { engine, @"(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>:;@)+", RegexOptions.None, "=====abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>:;@abcdefg======", new (int, int, string)[] { (5, 67, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>:;@") } }; //this will need a total of 2x70 + 2 parts in the partition of NonBacktracking string pattern_orig = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>:;&@%!"; string pattern_WL = new String(Array.ConvertAll(pattern_orig.ToCharArray(), c => (char)((int)c + 0xFF00 - 32))); string pattern = "(" + pattern_orig + "===" + pattern_WL + ")+"; string input = "=====" + pattern_orig + "===" + pattern_WL + pattern_orig + "===" + pattern_WL + "===" + pattern_orig + "===" + pattern_orig; int length = 2 * (pattern_orig.Length + 3 + pattern_WL.Length); yield return new object[] { engine, pattern, RegexOptions.None, input, new (int, int, string)[]{(5, length, input.Substring(5, length)) } }; } } /// <summary> /// Test all top level matches for given pattern and options. /// </summary> [Theory] [MemberData(nameof(AllMatches_TestData))] public async Task AllMatches(RegexEngine engine, string pattern, RegexOptions options, string input, (int, int, string)[] matches) { Regex re = await RegexHelpers.GetRegexAsync(engine, pattern, options); Match m = re.Match(input); if (matches == null) { Assert.False(m.Success); } else { int i = 0; do { Assert.True(m.Success); Assert.True(i < matches.Length); Assert.Equal(matches[i].Item1, m.Index); Assert.Equal(matches[i].Item2, m.Length); Assert.Equal(matches[i++].Item3, m.Value); m = m.NextMatch(); } while (m.Success); Assert.Equal(matches.Length, i); } } [Theory] [InlineData(@"\w")] [InlineData(@"\s")] [InlineData(@"\d")] public async Task StandardCharSets_SameMeaningAcrossAllEngines(string singleCharPattern) { var regexes = new List<Regex>(); foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { regexes.Add(await RegexHelpers.GetRegexAsync(engine, singleCharPattern)); } if (regexes.Count < 2) { return; } for (int c = '\0'; c <= '\uFFFF'; c++) { string s = ((char)c).ToString(); bool baseline = regexes[0].IsMatch(s); for (int i = 1; i < regexes.Count; i++) { VerifyIsMatch(regexes[i], s, baseline, Regex.InfiniteMatchTimeout); } } } private static void VerifyIsMatchThrows<T>(Regex? r, string input, TimeSpan timeout, string? pattern = null, RegexOptions options = RegexOptions.None) where T : Exception { if (r == null) { Assert.Throws<T>(() => timeout == Regex.InfiniteMatchTimeout ? Regex.IsMatch(input, pattern, options) : Regex.IsMatch(input, pattern, options, timeout)); #if NET7_0_OR_GREATER Assert.Throws<T>(() => timeout == Regex.InfiniteMatchTimeout ? Regex.IsMatch(input.AsSpan(), pattern, options) : Regex.IsMatch(input.AsSpan(), pattern, options, timeout)); #endif } else { Assert.Throws<T>(() => r.IsMatch(input)); #if NET7_0_OR_GREATER Assert.Throws<T>(() => r.IsMatch(input.AsSpan())); #endif } } private static void VerifyIsMatch(Regex? r, string input, bool expected, TimeSpan timeout, string? pattern = null, RegexOptions options = RegexOptions.None) { if (r == null) { Assert.Equal(expected, timeout == Regex.InfiniteMatchTimeout ? Regex.IsMatch(input, pattern, options) : Regex.IsMatch(input, pattern, options, timeout)); if (options == RegexOptions.None) { Assert.Equal(expected, Regex.IsMatch(input, pattern)); } #if NET7_0_OR_GREATER Assert.Equal(expected, timeout == Regex.InfiniteMatchTimeout ? Regex.IsMatch(input.AsSpan(), pattern, options) : Regex.IsMatch(input.AsSpan(), pattern, options, timeout)); if (options == RegexOptions.None) { Assert.Equal(expected, Regex.IsMatch(input.AsSpan(), pattern)); } #endif } else { Assert.Equal(expected, r.IsMatch(input)); #if NET7_0_OR_GREATER Assert.Equal(expected, r.IsMatch(input.AsSpan())); #endif } } public static IEnumerable<object[]> Match_DisjunctionOverCounting_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, "a[abc]{0,10}", "a[abc]{0,3}", "xxxabbbbbbbyyy", true, "abbbbbbb" }; yield return new object[] { engine, "a[abc]{0,10}?", "a[abc]{0,3}?", "xxxabbbbbbbyyy", true, "a" }; } } [Theory] [MemberData(nameof(Match_DisjunctionOverCounting_TestData))] public async Task Match_DisjunctionOverCounting(RegexEngine engine, string disjunct1, string disjunct2, string input, bool success, string match) { Regex re = await RegexHelpers.GetRegexAsync(engine, disjunct1 + "|" + disjunct2); Match m = re.Match(input); Assert.Equal(success, m.Success); Assert.Equal(match, m.Value); } public static IEnumerable<object[]> MatchAmbiguousRegexes_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, "(a|ab|c|bcd){0,}d*", "ababcd", (0, 1) }; yield return new object[] { engine, "(a|ab|c|bcd){0,10}d*", "ababcd", (0, 1) }; yield return new object[] { engine, "(a|ab|c|bcd)*d*", "ababcd", (0, 1) }; yield return new object[] { engine, @"(the)\s*([12][0-9]|3[01]|0?[1-9])", "it is the 10:00 time", (6, 6) }; yield return new object[] { engine, "(ab|a|bcd|c){0,}d*", "ababcd", (0, 6) }; yield return new object[] { engine, "(ab|a|bcd|c){0,10}d*", "ababcd", (0, 6) }; yield return new object[] { engine, "(ab|a|bcd|c)*d*", "ababcd", (0, 6) }; yield return new object[] { engine, @"(the)\s*(0?[1-9]|[12][0-9]|3[01])", "it is the 10:00 time", (6, 5) }; } } [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Doesn't support NonBacktracking")] [MemberData(nameof(MatchAmbiguousRegexes_TestData))] public async Task MatchAmbiguousRegexes(RegexEngine engine, string pattern, string input, (int,int) expected_match) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern); var match = r.Match(input); Assert.Equal(expected_match.Item1, match.Index); Assert.Equal(expected_match.Item2, match.Length); } public static IEnumerable<object[]> UseRegexConcurrently_ThreadSafe_Success_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, Timeout.InfiniteTimeSpan }; yield return new object[] { engine, TimeSpan.FromMinutes(1) }; } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [OuterLoop("Takes several seconds")] [MemberData(nameof(UseRegexConcurrently_ThreadSafe_Success_MemberData))] public async Task UseRegexConcurrently_ThreadSafe_Success(RegexEngine engine, TimeSpan timeout) { const string Input = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Aenean nec lorem. In porttitor. abcdefghijklmnx Donec laoreet nonummy augue. Suspendisse dui purus, scelerisque at, vulputate vitae, pretium mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut nonummy. Fusce aliquet pede non pede. Suspendisse dapibus lorem pellentesque magna. Integer nulla. Donec blandit feugiat ligula. Donec hendrerit, felis et imperdiet euismod, purus ipsum pretium metus, in lacinia nulla nisl eget sapien. Donec ut est in lectus consequat consequat. Etiam eget dui. Aliquam erat volutpat. Sed at lorem in nunc porta tristique. Proin nec augue. Quisque aliquam tempor magna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nunc ac magna. Maecenas odio dolor, vulputate vel, auctor ac, accumsan id, felis. Pellentesque cursus sagittis felis. Pellentesque porttitor, velit lacinia egestas auctor, diam eros tempus arcu, nec vulputate augue magna vel risus.nmlkjihgfedcbax"; const int Trials = 100; const int IterationsPerTask = 10; using var b = new Barrier(Environment.ProcessorCount); for (int trial = 0; trial < Trials; trial++) { Regex r = await RegexHelpers.GetRegexAsync(engine, "[a-q][^u-z]{13}x", RegexOptions.None, timeout); Task.WaitAll(Enumerable.Range(0, b.ParticipantCount).Select(_ => Task.Factory.StartNew(() => { b.SignalAndWait(); for (int i = 0; i < IterationsPerTask; i++) { Match m = r.Match(Input); Assert.NotNull(m); Assert.True(m.Success); Assert.Equal("abcdefghijklmnx", m.Value); m = m.NextMatch(); Assert.NotNull(m); Assert.True(m.Success); Assert.Equal("nmlkjihgfedcbax", m.Value); m = m.NextMatch(); Assert.NotNull(m); Assert.False(m.Success); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray()); } } [Theory] [MemberData(nameof(MatchWordsInAnchoredRegexes_TestData))] public async Task MatchWordsInAnchoredRegexes(RegexEngine engine, RegexOptions options, string pattern, string input, (int, int)[] matches) { // The aim of these test is to test corner cases of matches involving anchors // For NonBacktracking these tests are meant to // cover most contexts in _nullabilityForContext in SymbolicRegexNode Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); MatchCollection ms = r.Matches(input); Assert.Equal(matches.Length, ms.Count); for (int i = 0; i < matches.Length; i++) { Assert.Equal(ms[i].Index, matches[i].Item1); Assert.Equal(ms[i].Length, matches[i].Item2); } } public static IEnumerable<object[]> MatchWordsInAnchoredRegexes_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, RegexOptions.None, @"\b\w{10,}\b", "this is a complicated word in a\nnontrivial sentence", new (int, int)[] { (10, 11), (32, 10) } }; yield return new object[] { engine, RegexOptions.Multiline, @"^\w{10,}\b", "this is a\ncomplicated word in a\nnontrivial sentence", new (int, int)[] { (10, 11), (32, 10) } }; yield return new object[] { engine, RegexOptions.None, @"\b\d{1,2}\/\d{1,2}\/\d{2,4}\b", "date 10/12/1966 and 10/12/66 are the same", new (int, int)[] { (5, 10), (20, 8) } }; yield return new object[] { engine, RegexOptions.Multiline, @"\b\d{1,2}\/\d{1,2}\/\d{2,4}$", "date 10/12/1966\nand 10/12/66\nare the same", new (int, int)[] { (5, 10), (20, 8) } }; } } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using System.Tests; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Text.RegularExpressions.Tests { public class RegexMatchTests { public static IEnumerable<object[]> Match_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { (string Pattern, string Input, RegexOptions Options, int Beginning, int Length, bool ExpectedSuccess, string ExpectedValue)[] cases = Cases(engine).ToArray(); Regex[] regexes = RegexHelpers.GetRegexesAsync(engine, cases.Select(c => (c.Pattern, (RegexOptions?)c.Options, (TimeSpan?)null)).ToArray()).Result; for (int i = 0; i < regexes.Length; i++) { yield return new object[] { engine, cases[i].Pattern, cases[i].Input, cases[i].Options, regexes[i], cases[i].Beginning, cases[i].Length, cases[i].ExpectedSuccess, cases[i].ExpectedValue }; } } static IEnumerable<(string Pattern, string Input, RegexOptions Options, int Beginning, int Length, bool ExpectedSuccess, string ExpectedValue)> Cases(RegexEngine engine) { // pattern, input, options, beginning, length, expectedSuccess, expectedValue yield return (@"H#", "#H#", RegexOptions.IgnoreCase, 0, 3, true, "H#"); // https://github.com/dotnet/runtime/issues/39390 yield return (@"H#", "#H#", RegexOptions.None, 0, 3, true, "H#"); // Testing octal sequence matches: "\\060(\\061)?\\061" // Octal \061 is ASCII 49 ('1') yield return (@"\060(\061)?\061", "011", RegexOptions.None, 0, 3, true, "011"); // Testing hexadecimal sequence matches: "(\\x30\\x31\\x32)" // Hex \x31 is ASCII 49 ('1') yield return (@"(\x30\x31\x32)", "012", RegexOptions.None, 0, 3, true, "012"); // Testing control character escapes???: "2", "(\u0032)" yield return ("(\u0034)", "4", RegexOptions.None, 0, 1, true, "4"); // Using long loop prefix yield return (@"a{10}", new string('a', 10), RegexOptions.None, 0, 10, true, new string('a', 10)); yield return (@"a{100}", new string('a', 100), RegexOptions.None, 0, 100, true, new string('a', 100)); yield return (@"a{10}b", new string('a', 10) + "bc", RegexOptions.None, 0, 12, true, new string('a', 10) + "b"); yield return (@"a{100}b", new string('a', 100) + "bc", RegexOptions.None, 0, 102, true, new string('a', 100) + "b"); yield return (@"a{11}b", new string('a', 10) + "bc", RegexOptions.None, 0, 12, false, string.Empty); yield return (@"a{101}b", new string('a', 100) + "bc", RegexOptions.None, 0, 102, false, string.Empty); yield return (@"a{1,3}b", "bc", RegexOptions.None, 0, 2, false, string.Empty); yield return (@"a{1,3}b", "abc", RegexOptions.None, 0, 3, true, "ab"); yield return (@"a{1,3}b", "aaabc", RegexOptions.None, 0, 5, true, "aaab"); yield return (@"a{1,3}b", "aaaabc", RegexOptions.None, 0, 6, true, "aaab"); yield return (@"a{1,3}?b", "bc", RegexOptions.None, 0, 2, false, string.Empty); yield return (@"a{1,3}?b", "abc", RegexOptions.None, 0, 3, true, "ab"); yield return (@"a{1,3}?b", "aaabc", RegexOptions.None, 0, 5, true, "aaab"); yield return (@"a{1,3}?b", "aaaabc", RegexOptions.None, 0, 6, true, "aaab"); yield return (@"a{2,}b", "abc", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"a{2,}b", "aabc", RegexOptions.None, 0, 4, true, "aab"); yield return (@"a{2,}?b", "abc", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"a{2,}?b", "aabc", RegexOptions.None, 0, 4, true, "aab"); // {,n} is treated as a literal rather than {0,n} as it should be yield return (@"a{,3}b", "a{,3}bc", RegexOptions.None, 0, 6, true, "a{,3}b"); yield return (@"a{,3}b", "aaabc", RegexOptions.None, 0, 5, false, string.Empty); // Using [a-z], \s, \w: Actual - "([a-zA-Z]+)\\s(\\w+)" yield return (@"([a-zA-Z]+)\s(\w+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau"); yield return (@"([a-zA-Z]+?)\s(\w+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau"); // \\S, \\d, \\D, \\W: Actual - "(\\S+):\\W(\\d+)\\s(\\D+)" yield return (@"(\S+):\W(\d+)\s(\D+)", "Price: 5 dollars", RegexOptions.None, 0, 16, true, "Price: 5 dollars"); // \\S, \\d, \\D, \\W: Actual - "[^0-9]+(\\d+)" yield return (@"[^0-9]+(\d+)", "Price: 30 dollars", RegexOptions.None, 0, 17, true, "Price: 30"); if (!RegexHelpers.IsNonBacktracking(engine)) { // Zero-width negative lookahead assertion yield return (@"abc(?!XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, false, string.Empty); // Zero-width positive lookbehind assertion yield return (@"(\w){6}(?<=XXX)def", "abcXXXdef", RegexOptions.None, 0, 9, true, "abcXXXdef"); yield return (@"(?<=c)def", "123abcdef", RegexOptions.None, 0, 9, true, "def"); yield return (@"(?<=abc)def", "123abcdef", RegexOptions.None, 0, 9, true, "def"); yield return (@"(?<=a\wc)def", "123abcdef", RegexOptions.None, 0, 9, true, "def"); yield return (@"(?<=\ba\wc)def", "123 abcdef", RegexOptions.None, 0, 10, true, "def"); yield return (@"(?<=.\ba\wc\B)def", "123 abcdef", RegexOptions.None, 0, 10, true, "def"); yield return (@"(?<=^123 abc)def", "123 abcdef", RegexOptions.None, 0, 10, true, "def"); yield return (@"(?<=^123 abc)def", "123 abcdef", RegexOptions.Multiline, 0, 10, true, "def"); yield return (@"(?<=123$\nabc)def", "123\nabcdef", RegexOptions.Multiline, 0, 10, true, "def"); yield return (@"\w{3}(?<=^xyz|^abc)defg", "abcdefg", RegexOptions.None, 0, 7, true, "abcdefg"); yield return (@"(abc)\w(?<=(?(1)d|e))", "abcdabc", RegexOptions.None, 0, 7, true, "abcd"); yield return (@"(abc)\w(?<=(?(cd)d|e))", "abcdabc", RegexOptions.None, 0, 7, true, "abcd"); yield return (@"\w{3}(?<=(\w){6,8})", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "def"); yield return (@"\w{3}(?<=(?:\d\w){4})", "a1b2c3d4e5", RegexOptions.None, 0, 10, true, "d4e"); yield return (@"\w{3}(?<=(\w){6,8}?)", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "def"); yield return (@"\w{3}(?<=(?:\d\w){3,4}?\d)", "a1b2c3d4e5", RegexOptions.None, 0, 10, true, "3d4"); yield return (@"(\w{3})\w*(?<=\1)", "---abcdefababc123", RegexOptions.None, 0, 17, true, "abcdefababc"); yield return (@"(?<=\w{3})\w{4}", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "defg"); yield return (@"(?<=\w{3,8})\w{4}", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "defg"); yield return (@"(?<=\w*)\w{4}", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "abcd"); yield return (@"(?<=\w?)\w{4}", "abcdefghijklmnop", RegexOptions.None, 0, 16, true, "abcd"); yield return (@"(?<=\d?)a{4}", "123aaaaaaaaa", RegexOptions.None, 0, 12, true, "aaaa"); yield return (@"(?<=a{3,5}[ab]*)1234", "aaaaaaa1234", RegexOptions.None, 0, 11, true, "1234"); // Zero-width negative lookbehind assertion: Actual - "(\\w){6}(?<!XXX)def" yield return (@"(\w){6}(?<!XXX)def", "XXXabcdef", RegexOptions.None, 0, 9, true, "XXXabcdef"); yield return (@"123(?<!$) abcdef", "123 abcdef", RegexOptions.None, 0, 10, true, "123 abcdef"); yield return (@"(abc)\w(?<!(?(1)e|d))", "abcdabc", RegexOptions.None, 0, 7, true, "abcd"); yield return (@"(abc)\w(?<!(?(cd)e|d))", "abcdabc", RegexOptions.None, 0, 7, true, "abcd"); // Nonbacktracking subexpression: Actual - "[^0-9]+(?>[0-9]+)3" // The last 3 causes the match to fail, since the non backtracking subexpression does not give up the last digit it matched // for it to be a success. For a correct match, remove the last character, '3' from the pattern yield return ("[^0-9]+(?>[0-9]+)3", "abc123", RegexOptions.None, 0, 6, false, string.Empty); yield return ("[^0-9]+(?>[0-9]+)", "abc123", RegexOptions.None, 0, 6, true, "abc123"); yield return (@"(?!.*a)\w*g", "bcaefg", RegexOptions.None, 0, 6, true, "efg"); yield return (@"(?!.*a)\w*g", "aaaaag", RegexOptions.None, 0, 6, true, "g"); yield return (@"(?!.*a)\w*g", "aaaaaa", RegexOptions.None, 0, 6, false, string.Empty); } // More nonbacktracking expressions foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.IgnoreCase }) { string Case(string s) => (options & RegexOptions.IgnoreCase) != 0 ? s.ToUpper() : s; yield return (Case("(?:hi|hello|hey)hi"), "hellohi", options, 0, 7, true, "hellohi"); // allow backtracking and it succeeds yield return (Case(@"a[^wyz]*w"), "abczw", RegexOptions.IgnoreCase, 0, 0, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { // Atomic greedy yield return (Case("(?>[0-9]+)abc"), "abc12345abc", options, 3, 8, true, "12345abc"); yield return (Case("(?>(?>[0-9]+))abc"), "abc12345abc", options, 3, 8, true, "12345abc"); yield return (Case("(?>[0-9]*)abc"), "abc12345abc", options, 3, 8, true, "12345abc"); yield return (Case("(?>[^z]+)z"), "zzzzxyxyxyz123", options, 4, 9, true, "xyxyxyz"); yield return (Case("(?>(?>[^z]+))z"), "zzzzxyxyxyz123", options, 4, 9, true, "xyxyxyz"); yield return (Case("(?>[^z]*)z123"), "zzzzxyxyxyz123", options, 4, 10, true, "xyxyxyz123"); yield return (Case("(?>[^12]+)1"), "121231", options, 0, 6, true, "31"); yield return (Case("(?>[^123]+)1"), "12312341", options, 0, 8, true, "41"); yield return (Case("(?>[^1234]+)1"), "1234123451", options, 0, 10, true, "51"); yield return (Case("(?>[^12345]+)1"), "123451234561", options, 0, 12, true, "61"); yield return (Case("(?>[^123456]+)1"), "12345612345671", options, 0, 14, true, "71"); yield return (Case("(?>a+)123"), "aa1234", options, 0, 5, true, "aa123"); yield return (Case("(?>a*)123"), "aa1234", options, 0, 5, true, "aa123"); yield return (Case("(?>(?>a*))123"), "aa1234", options, 0, 5, true, "aa123"); yield return (Case("(?>a{2,})b"), "aaab", options, 0, 4, true, "aaab"); yield return (Case("[a-z]{0,4}(?>[x-z]*.)(?=xyz1)"), "abcdxyz1", options, 0, 8, true, "abcd"); yield return (Case("[a-z]{0,4}(?=[x-z]*.)(?=cd)"), "abcdxyz1", options, 0, 8, true, "ab"); yield return (Case("[a-z]{0,4}(?![x-z]*[wx])(?=cd)"), "abcdxyz1", options, 0, 8, true, "ab"); // Atomic lazy yield return (Case("(?>[0-9]+?)abc"), "abc12345abc", options, 3, 8, true, "5abc"); yield return (Case("(?>(?>[0-9]+?))abc"), "abc12345abc", options, 3, 8, true, "5abc"); yield return (Case("(?>[0-9]*?)abc"), "abc12345abc", options, 3, 8, true, "abc"); yield return (Case("(?>[^z]+?)z"), "zzzzxyxyxyz123", options, 4, 9, true, "yz"); yield return (Case("(?>(?>[^z]+?))z"), "zzzzxyxyxyz123", options, 4, 9, true, "yz"); yield return (Case("(?>[^z]*?)z123"), "zzzzxyxyxyz123", options, 4, 10, true, "z123"); yield return (Case("(?>a+?)123"), "aa1234", options, 0, 5, true, "a123"); yield return (Case("(?>a*?)123"), "aa1234", options, 0, 5, true, "123"); yield return (Case("(?>(?>a*?))123"), "aa1234", options, 0, 5, true, "123"); yield return (Case("(?>a{2,}?)b"), "aaab", options, 0, 4, true, "aab"); // Alternations yield return (Case("(?>hi|hello|hey)hi"), "hellohi", options, 0, 0, false, string.Empty); yield return (Case("(?>hi|hello|hey)hi"), "hihi", options, 0, 4, true, "hihi"); } } // Loops at beginning of expressions yield return (@"a+", "aaa", RegexOptions.None, 0, 3, true, "aaa"); yield return (@"a+\d+", "a1", RegexOptions.None, 0, 2, true, "a1"); yield return (@".+\d+", "a1", RegexOptions.None, 0, 2, true, "a1"); yield return (".+\nabc", "a\nabc", RegexOptions.None, 0, 5, true, "a\nabc"); yield return (@"\d+", "abcd123efg", RegexOptions.None, 0, 10, true, "123"); yield return (@"\d+\d+", "abcd123efg", RegexOptions.None, 0, 10, true, "123"); yield return (@"\w+123\w+", "abcd123efg", RegexOptions.None, 0, 10, true, "abcd123efg"); yield return (@"\d+\w+", "abcd123efg", RegexOptions.None, 0, 10, true, "123efg"); yield return (@"\w+@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{3,}@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{4,}@\w+.com", "[email protected]", RegexOptions.None, 0, 11, false, string.Empty); yield return (@"\w{2,5}@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{3}@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{0,3}@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{0,2}c@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w*@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"(\w+)@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"((\w+))@\w+.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"(\w+)c@\w+.com", "[email protected]", RegexOptions.None, 0, 17, true, "[email protected]"); yield return (@"\w+://\w+\.\w+", "test https://dot.net test", RegexOptions.None, 0, 25, true, "https://dot.net"); yield return (@"\w+[:|]//\w+\.\w+", "test https://dot.net test", RegexOptions.None, 0, 25, true, "https://dot.net"); yield return (@"\w+[|:$]//\w+\.\w+", "test https://dot.net test", RegexOptions.None, 0, 25, true, "https://dot.net"); yield return (@"\w+[|$:*]//\w+\.\w+", "test https://dot.net test", RegexOptions.None, 0, 25, true, "https://dot.net"); yield return (@"\w+[|$*:&]//\w+\.\w+", "test https://dot.net test", RegexOptions.None, 0, 25, true, "https://dot.net"); yield return (@".+a", "baa", RegexOptions.None, 0, 3, true, "baa"); yield return (@"[ab]+a", "cacbaac", RegexOptions.None, 0, 7, true, "baa"); yield return (@"^(\d{2,3}){2}$", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(\d{2,3}){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"((\d{2,3})){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(abc\d{2,3}){2}", "abc123abc4567", RegexOptions.None, 0, 12, true, "abc123abc456"); // Lazy versions of those loops yield return (@"a+?", "aaa", RegexOptions.None, 0, 3, true, "a"); yield return (@"a+?\d+?", "a1", RegexOptions.None, 0, 2, true, "a1"); yield return (@".+?\d+?", "a1", RegexOptions.None, 0, 2, true, "a1"); yield return (".+?\nabc", "a\nabc", RegexOptions.None, 0, 5, true, "a\nabc"); yield return (@"\d+?", "abcd123efg", RegexOptions.None, 0, 10, true, "1"); yield return (@"\d+?\d+?", "abcd123efg", RegexOptions.None, 0, 10, true, "12"); yield return (@"\w+?123\w+?", "abcd123efg", RegexOptions.None, 0, 10, true, "abcd123e"); yield return (@"\d+?\w+?", "abcd123efg", RegexOptions.None, 0, 10, true, "12"); yield return (@"\w+?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{3,}?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{4,}?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, false, string.Empty); yield return (@"\w{2,5}?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{3}?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{0,3}?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w{0,2}?c@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"\w*?@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"(\w+?)@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"((\w+?))@\w+?\.com", "[email protected]", RegexOptions.None, 0, 11, true, "[email protected]"); yield return (@"(\w+?)c@\w+?\.com", "[email protected]", RegexOptions.None, 0, 17, true, "[email protected]"); yield return (@".+?a", "baa", RegexOptions.None, 0, 3, true, "ba"); yield return (@"[ab]+?a", "cacbaac", RegexOptions.None, 0, 7, true, "ba"); yield return (@"^(\d{2,3}?){2}$", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(\d{2,3}?){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"((\d{2,3}?)){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(abc\d{2,3}?){2}", "abc123abc4567", RegexOptions.None, 0, 12, true, "abc123abc45"); // Testing selected FindOptimizations finds the right prefix yield return (@"(^|a+)bc", " aabc", RegexOptions.None, 0, 5, true, "aabc"); yield return (@"(^|($|a+))bc", " aabc", RegexOptions.None, 0, 5, true, "aabc"); yield return (@"yz(^|a+)bc", " yzaabc", RegexOptions.None, 0, 7, true, "yzaabc"); yield return (@"(^a|a$) bc", "a bc", RegexOptions.None, 0, 4, true, "a bc"); yield return (@"(abcdefg|abcdef|abc|a)h", " ah ", RegexOptions.None, 0, 8, true, "ah"); yield return (@"(^abcdefg|abcdef|^abc|a)h", " abcdefh ", RegexOptions.None, 0, 13, true, "abcdefh"); yield return (@"(a|^abcdefg|abcdef|^abc)h", " abcdefh ", RegexOptions.None, 0, 13, true, "abcdefh"); yield return (@"(abcdefg|abcdef)h", " abcdefghij ", RegexOptions.None, 0, 16, true, "abcdefgh"); if (!RegexHelpers.IsNonBacktracking(engine)) { // Back references not support with NonBacktracking yield return (@"(\w+)c@\w+.com\1", "[email protected]", RegexOptions.None, 0, 17, true, "[email protected]"); yield return (@"(\w+)@def.com\1", "[email protected]", RegexOptions.None, 0, 13, false, string.Empty); yield return (@"(\w+)@def.com\1", "[email protected]", RegexOptions.None, 0, 13, true, "[email protected]"); yield return (@"(\w*)@def.com\1", "[email protected]", RegexOptions.None, 0, 11, true, "@def.com"); yield return (@"\w+(?<!a)", "a", RegexOptions.None, 0, 1, false, string.Empty); yield return (@"\w+(?<!a)", "aa", RegexOptions.None, 0, 2, false, string.Empty); yield return (@"(?>\w+)(?<!a)", "a", RegexOptions.None, 0, 1, false, string.Empty); yield return (@"(?>\w+)(?<!a)", "aa", RegexOptions.None, 0, 2, false, string.Empty); yield return (@"(\w+?)c@\w+?.com\1", "[email protected]", RegexOptions.None, 0, 17, true, "[email protected]"); yield return (@"(\w+?)@def.com\1", "[email protected]", RegexOptions.None, 0, 13, false, string.Empty); yield return (@"(\w+?)@def.com\1", "[email protected]", RegexOptions.None, 0, 13, true, "[email protected]"); yield return (@"(\w*?)@def.com\1", "[email protected]", RegexOptions.None, 0, 11, true, "@def.com"); yield return (@"\w+?(?<!a)", "a", RegexOptions.None, 0, 1, false, string.Empty); yield return (@"\w+?(?<!a)", "aa", RegexOptions.None, 0, 2, false, string.Empty); yield return (@"(?>\w+?)(?<!a)", "a", RegexOptions.None, 0, 1, false, string.Empty); yield return (@"(?>\w+?)(?<!a)", "aa", RegexOptions.None, 0, 2, false, string.Empty); } yield return (@"(\d{2,3})+", "1234", RegexOptions.None, 0, 4, true, "123"); yield return (@"(\d{2,3})*", "123456", RegexOptions.None, 0, 4, true, "123"); yield return (@"(\d{2,3})+?", "1234", RegexOptions.None, 0, 4, true, "123"); yield return (@"(\d{2,3})*?", "123456", RegexOptions.None, 0, 4, true, ""); yield return (@"(\d{2,3}?)+", "1234", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(\d{2,3}?)*", "123456", RegexOptions.None, 0, 4, true, "1234"); yield return (@"(\d{2,3}?)+?", "1234", RegexOptions.None, 0, 4, true, "12"); yield return (@"(\d{2,3}?)*?", "123456", RegexOptions.None, 0, 4, true, ""); foreach (RegexOptions lineOption in new[] { RegexOptions.None, RegexOptions.Singleline }) { yield return (@".*", "abc", lineOption, 1, 2, true, "bc"); yield return (@".*c", "abc", lineOption, 1, 2, true, "bc"); yield return (@"b.*", "abc", lineOption, 1, 2, true, "bc"); yield return (@".*", "abc", lineOption, 2, 1, true, "c"); yield return (@"a.*[bc]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*[bc]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*[bc]", "xyza12345d6789", lineOption, 0, 14, false, ""); yield return (@"a.*[bcd]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*[bcd]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*[bcd]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*[bcd]", "xyza12345e6789", lineOption, 0, 14, false, ""); yield return (@"a.*[bcde]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*[bcde]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*[bcde]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*[bcde]", "xyza12345e6789", lineOption, 0, 14, true, "a12345e"); yield return (@"a.*[bcde]", "xyza12345f6789", lineOption, 0, 14, false, ""); yield return (@"a.*[bcdef]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*[bcdef]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*[bcdef]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*[bcdef]", "xyza12345e6789", lineOption, 0, 14, true, "a12345e"); yield return (@"a.*[bcdef]", "xyza12345f6789", lineOption, 0, 14, true, "a12345f"); yield return (@"a.*[bcdef]", "xyza12345g6789", lineOption, 0, 14, false, ""); yield return (@".*?", "abc", lineOption, 1, 2, true, ""); yield return (@".*?c", "abc", lineOption, 1, 2, true, "bc"); yield return (@"b.*?", "abc", lineOption, 1, 2, true, "b"); yield return (@".*?", "abc", lineOption, 2, 1, true, ""); yield return (@"a.*?[bc]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*?[bc]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*?[bc]", "xyza12345d6789", lineOption, 0, 14, false, ""); yield return (@"a.*?[bcd]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*?[bcd]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*?[bcd]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*?[bcd]", "xyza12345e6789", lineOption, 0, 14, false, ""); yield return (@"a.*?[bcde]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*?[bcde]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*?[bcde]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*?[bcde]", "xyza12345e6789", lineOption, 0, 14, true, "a12345e"); yield return (@"a.*?[bcde]", "xyza12345f6789", lineOption, 0, 14, false, ""); yield return (@"a.*?[bcdef]", "xyza12345b6789", lineOption, 0, 14, true, "a12345b"); yield return (@"a.*?[bcdef]", "xyza12345c6789", lineOption, 0, 14, true, "a12345c"); yield return (@"a.*?[bcdef]", "xyza12345d6789", lineOption, 0, 14, true, "a12345d"); yield return (@"a.*?[bcdef]", "xyza12345e6789", lineOption, 0, 14, true, "a12345e"); yield return (@"a.*?[bcdef]", "xyza12345f6789", lineOption, 0, 14, true, "a12345f"); yield return (@"a.*?[bcdef]", "xyza12345g6789", lineOption, 0, 14, false, ""); } // Nested loops yield return ("a*(?:a[ab]*)*", "aaaababbbbbbabababababaaabbb", RegexOptions.None, 0, 28, true, "aaaa"); yield return ("a*(?:a[ab]*?)*?", "aaaababbbbbbabababababaaabbb", RegexOptions.None, 0, 28, true, "aaaa"); // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return (@"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzz", RegexOptions.IgnoreCase, 0, 17, true, "aaaasdfajsdlfjzzz"); yield return (@"\Aaaaaa\w+zzz\Z", "aaaa", RegexOptions.IgnoreCase, 0, 4, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"\Aaaaaa\w+zzz\Z", "aaaa", RegexOptions.RightToLeft, 0, 4, false, string.Empty); yield return (@"\Aaaaaa\w+zzzzz\Z", "aaaa", RegexOptions.RightToLeft, 0, 4, false, string.Empty); yield return (@"\Aaaaaa\w+zzz\Z", "aaaa", RegexOptions.RightToLeft | RegexOptions.IgnoreCase, 0, 4, false, string.Empty); } yield return (@"abc\Adef", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); yield return (@"abc\adef", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"abc\Gdef", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); } yield return (@"abc^def", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); yield return (@"abc\Zef", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); yield return (@"abc\zef", "abcdef", RegexOptions.None, 0, 0, false, string.Empty); // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return (@"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzza", RegexOptions.None, 0, 18, false, string.Empty); // Anchors foreach (RegexOptions anchorOptions in new[] { RegexOptions.None, RegexOptions.Multiline }) { yield return (@"^abc", "abc", anchorOptions, 0, 3, true, "abc"); yield return (@"^abc", " abc", anchorOptions, 0, 4, false, ""); yield return (@"^abc|^def", "def", anchorOptions, 0, 3, true, "def"); yield return (@"^abc|^def", " abc", anchorOptions, 0, 4, false, ""); yield return (@"^abc|^def", " def", anchorOptions, 0, 4, false, ""); yield return (@"abc|^def", " abc", anchorOptions, 0, 4, true, "abc"); yield return (@"abc|^def|^efg", " abc", anchorOptions, 0, 4, true, "abc"); yield return (@"^abc|def|^efg", " def", anchorOptions, 0, 4, true, "def"); yield return (@"^abc|def", " def", anchorOptions, 0, 4, true, "def"); yield return (@"abcd$", "1234567890abcd", anchorOptions, 0, 14, true, "abcd"); foreach (string endAnchor in new[] { @"$", @"\Z", @"\z" }) { yield return (@"abc{1,4}d" + endAnchor, "1234567890abcd", anchorOptions, 0, 14, true, "abcd"); yield return (@"abc{1,4}d" + endAnchor, "1234567890abccccd", anchorOptions, 0, 17, true, "abccccd"); } } if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"\Gabc", "abc", RegexOptions.None, 0, 3, true, "abc"); yield return (@"\Gabc", " abc", RegexOptions.None, 0, 4, false, ""); yield return (@"\Gabc", " abc", RegexOptions.None, 1, 3, true, "abc"); yield return (@"\Gabc|\Gdef", "def", RegexOptions.None, 0, 3, true, "def"); yield return (@"\Gabc|\Gdef", " abc", RegexOptions.None, 0, 4, false, ""); yield return (@"\Gabc|\Gdef", " def", RegexOptions.None, 0, 4, false, ""); yield return (@"\Gabc|\Gdef", " abc", RegexOptions.None, 1, 3, true, "abc"); yield return (@"\Gabc|\Gdef", " def", RegexOptions.None, 1, 3, true, "def"); yield return (@"abc|\Gdef", " abc", RegexOptions.None, 0, 4, true, "abc"); yield return (@"\Gabc|def", " def", RegexOptions.None, 0, 4, true, "def"); } // Anchors and multiline yield return (@"^A$", "A\n", RegexOptions.Multiline, 0, 2, true, "A"); yield return (@"^A$", "ABC\n", RegexOptions.Multiline, 0, 4, false, string.Empty); yield return (@"^A$", "123\nA", RegexOptions.Multiline, 0, 5, true, "A"); yield return (@"^A$", "123\nA\n456", RegexOptions.Multiline, 0, 9, true, "A"); yield return (@"^A$|^B$", "123\nB\n456", RegexOptions.Multiline, 0, 9, true, "B"); // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return (@"\A(line2\n)line3\Z", "line2\nline3\n", RegexOptions.Multiline, 0, 12, true, "line2\nline3"); // Using beginning/end of string chars ^: Actual - "^b" yield return ("^b", "ab", RegexOptions.None, 0, 2, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { // Actual - "(?<char>\\w)\\<char>" yield return (@"(?<char>\w)\<char>", "aa", RegexOptions.None, 0, 2, true, "aa"); // Actual - "(?<43>\\w)\\43" yield return (@"(?<43>\w)\43", "aa", RegexOptions.None, 0, 2, true, "aa"); // Actual - "abc(?(1)111|222)" yield return ("(abbc)(?(1)111|222)", "abbc222", RegexOptions.None, 0, 7, false, string.Empty); } // "x" option. Removes unescaped whitespace from the pattern: Actual - " ([^/]+) ","x" yield return (" ((.)+) #comment ", "abc", RegexOptions.IgnorePatternWhitespace, 0, 3, true, "abc"); // "x" option. Removes unescaped whitespace from the pattern. : Actual - "\x20([^/]+)\x20","x" yield return ("\x20([^/]+)\x20\x20\x20\x20\x20\x20\x20", " abc ", RegexOptions.IgnorePatternWhitespace, 0, 10, true, " abc "); // Turning on case insensitive option in mid-pattern : Actual - "aaa(?i:match this)bbb" if ("i".ToUpper() == "I") { yield return ("aaa(?i:match this)bbb", "aaaMaTcH ThIsbbb", RegexOptions.None, 0, 16, true, "aaaMaTcH ThIsbbb"); } yield return ("(?i:a)b(?i:c)d", "aaaaAbCdddd", RegexOptions.None, 0, 11, true, "AbCd"); yield return ("(?i:[\u0000-\u1000])[Bb]", "aaaaAbCdddd", RegexOptions.None, 0, 11, true, "Ab"); // Turning off case insensitive option in mid-pattern : Actual - "aaa(?-i:match this)bbb", "i" yield return ("aAa(?-i:match this)bbb", "AaAmatch thisBBb", RegexOptions.IgnoreCase, 0, 16, true, "AaAmatch thisBBb"); // Turning on/off all the options at once : Actual - "aaa(?imnsx-imnsx:match this)bbb", "i" yield return ("aaa(?imnsx-imnsx:match this)bbb", "AaAmatcH thisBBb", RegexOptions.IgnoreCase, 0, 16, false, string.Empty); // Actual - "aaa(?#ignore this completely)bbb" yield return ("aAa(?#ignore this completely)bbb", "aAabbb", RegexOptions.None, 0, 6, true, "aAabbb"); // Trying empty string: Actual "[a-z0-9]+", "" yield return ("[a-z0-9]+", "", RegexOptions.None, 0, 0, false, string.Empty); // Numbering pattern slots: "(?<1>\\d{3})(?<2>\\d{3})(?<3>\\d{4})" yield return (@"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "8885551111", RegexOptions.None, 0, 10, true, "8885551111"); yield return (@"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "Invalid string", RegexOptions.None, 0, 14, false, string.Empty); // Not naming pattern slots at all: "^(cat|chat)" yield return ("^(cat|chat)", "cats are bad", RegexOptions.None, 0, 12, true, "cat"); yield return ("abc", "abc", RegexOptions.None, 0, 3, true, "abc"); yield return ("abc", "aBc", RegexOptions.None, 0, 3, false, string.Empty); yield return ("abc", "aBc", RegexOptions.IgnoreCase, 0, 3, true, "aBc"); yield return (@"abc.*def", "abcghiDEF", RegexOptions.IgnoreCase, 0, 9, true, "abcghiDEF"); // Using *, +, ?, {}: Actual - "a+\\.?b*\\.?c{2}" yield return (@"a+\.?b*\.+c{2}", "ab.cc", RegexOptions.None, 0, 5, true, "ab.cc"); yield return (@"[^a]+\.[^z]+", "zzzzz", RegexOptions.None, 0, 5, false, string.Empty); // IgnoreCase yield return ("AAA", "aaabbb", RegexOptions.IgnoreCase, 0, 6, true, "aaa"); yield return (@"\p{Lu}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b"); yield return (@"\p{Ll}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b"); yield return (@"\p{Lt}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b"); yield return (@"\p{Lo}", "1bc", RegexOptions.IgnoreCase, 0, 3, false, string.Empty); yield return (".[abc]", "xYZAbC", RegexOptions.IgnoreCase, 0, 6, true, "ZA"); yield return (".[abc]", "xYzXyZx", RegexOptions.IgnoreCase, 0, 6, false, ""); // Sets containing characters that differ by a bit yield return ("123[Aa]", "123a", RegexOptions.None, 0, 4, true, "123a"); yield return ("123[0p]", "123p", RegexOptions.None, 0, 4, true, "123p"); yield return ("123[Aa@]", "123@", RegexOptions.None, 0, 4, true, "123@"); // "\D+" yield return (@"\D+", "12321", RegexOptions.None, 0, 5, false, string.Empty); // Groups yield return ("(?<first_name>\\S+)\\s(?<last_name>\\S+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau"); // "^b" yield return ("^b", "abc", RegexOptions.None, 0, 3, false, string.Empty); // Trim leading and trailing whitespace yield return (@"\s*(.*?)\s*$", " Hello World ", RegexOptions.None, 0, 13, true, " Hello World "); if (!RegexHelpers.IsNonBacktracking(engine)) { // Throws NotSupported with NonBacktracking engine because of the balancing group dog-0 yield return (@"(?<cat>cat)\w+(?<dog-0>dog)", "cat_Hello_World_dog", RegexOptions.None, 0, 19, false, string.Empty); } // Atomic Zero-Width Assertions \A \Z \z \b \B yield return (@"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.None, 0, 20, false, string.Empty); yield return (@"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.Multiline, 0, 20, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.ECMAScript, 0, 20, false, string.Empty); } yield return (@"(cat)\s+(dog)\Z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty); yield return (@"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty); } yield return (@"(cat)\s+(dog)\z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty); yield return (@"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty); } yield return (@"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.None, 0, 16, false, string.Empty); yield return (@"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.Multiline, 0, 16, false, string.Empty); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.ECMAScript, 0, 16, false, string.Empty); } yield return (@"\b@cat", "123START123;@catEND", RegexOptions.None, 0, 19, false, string.Empty); yield return (@"\b<cat", "123START123'<catEND", RegexOptions.None, 0, 19, false, string.Empty); yield return (@"\b,cat", "satwe,,,START',catEND", RegexOptions.None, 0, 21, false, string.Empty); yield return (@"\b\[cat", "`12START123'[catEND", RegexOptions.None, 0, 19, false, string.Empty); yield return (@"\B@cat", "123START123@catEND", RegexOptions.None, 0, 18, false, string.Empty); yield return (@"\B<cat", "123START123<catEND", RegexOptions.None, 0, 18, false, string.Empty); yield return (@"\B,cat", "satwe,,,START,catEND", RegexOptions.None, 0, 20, false, string.Empty); yield return (@"\B\[cat", "`12START123[catEND", RegexOptions.None, 0, 18, false, string.Empty); // Lazy operator Backtracking yield return (@"http://([a-zA-z0-9\-]*\.?)*?(:[0-9]*)??/", "http://www.msn.com", RegexOptions.IgnoreCase, 0, 18, false, string.Empty); // Grouping Constructs Invalid Regular Expressions if (!RegexHelpers.IsNonBacktracking(engine)) { yield return ("(?!)", "(?!)cat", RegexOptions.None, 0, 7, false, string.Empty); yield return ("(?<!)", "(?<!)cat", RegexOptions.None, 0, 8, false, string.Empty); } // Alternation construct foreach (string input in new[] { "abc", "def" }) { string upper = input.ToUpperInvariant(); // Two branches yield return (@"abc|def", input, RegexOptions.None, 0, input.Length, true, input); yield return (@"abc|def", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); yield return (@"abc|def", upper, RegexOptions.None, 0, input.Length, false, ""); // Three branches yield return (@"abc|agh|def", input, RegexOptions.None, 0, input.Length, true, input); yield return (@"abc|agh|def", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); yield return (@"abc|agh|def", upper, RegexOptions.None, 0, input.Length, false, ""); // Four branches yield return (@"abc|agh|def|aij", input, RegexOptions.None, 0, input.Length, true, input); yield return (@"abc|agh|def|aij", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); yield return (@"abc|agh|def|aij", upper, RegexOptions.None, 0, input.Length, false, ""); // Four branches (containing various other constructs) if (!RegexHelpers.IsNonBacktracking(engine)) { yield return (@"abc|(agh)|(?=def)def|(?:(?(aij)aij|(?!)))", input, RegexOptions.None, 0, input.Length, true, input); yield return (@"abc|(agh)|(?=def)def|(?:(?(aij)aij|(?!)))", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); yield return (@"abc|(agh)|(?=def)def|(?:(?(aij)aij|(?!)))", upper, RegexOptions.None, 0, input.Length, false, ""); } // Sets in various positions in each branch yield return (@"a\wc|\wgh|de\w", input, RegexOptions.None, 0, input.Length, true, input); yield return (@"a\wc|\wgh|de\w", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); yield return (@"a\wc|\wgh|de\w", upper, RegexOptions.None, 0, input.Length, false, ""); } yield return ("[^a-z0-9]etag|[^a-z0-9]digest", "this string has .digest as a substring", RegexOptions.None, 16, 7, true, ".digest"); yield return (@"(\w+|\d+)a+[ab]+", "123123aa", RegexOptions.None, 0, 8, true, "123123aa"); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return ("(?(dog2))", "dog2", RegexOptions.None, 0, 4, true, string.Empty); yield return ("(?(a:b))", "a", RegexOptions.None, 0, 1, true, string.Empty); yield return ("(?(a:))", "a", RegexOptions.None, 0, 1, true, string.Empty); yield return ("(?(cat)cat|dog)", "cat", RegexOptions.None, 0, 3, true, "cat"); yield return ("(?((?=cat))cat|dog)", "cat", RegexOptions.None, 0, 3, true, "cat"); yield return ("(?(cat)|dog)", "cat", RegexOptions.None, 0, 3, true, string.Empty); yield return ("(?(cat)|dog)", "catdog", RegexOptions.None, 0, 6, true, string.Empty); yield return ("(?(cat)|dog)", "oof", RegexOptions.None, 0, 3, false, string.Empty); yield return ("(?(cat)dog1|dog2)", "catdog1", RegexOptions.None, 0, 7, false, string.Empty); yield return ("(?(cat)dog1|dog2)", "catdog2", RegexOptions.None, 0, 7, true, "dog2"); yield return ("(?(cat)dog1|dog2)", "catdog1dog2", RegexOptions.None, 0, 11, true, "dog2"); yield return (@"(?(\w+)\w+)dog", "catdog", RegexOptions.None, 0, 6, true, "catdog"); yield return (@"(?(abc)\w+|\w{0,2})dog", "catdog", RegexOptions.None, 0, 6, true, "atdog"); yield return (@"(?(abc)cat|\w{0,2})dog", "catdog", RegexOptions.None, 0, 6, true, "atdog"); yield return ("(a|ab|abc|abcd)d", "abcd", RegexOptions.RightToLeft, 0, 4, true, "abcd"); yield return ("(?>(?:a|ab|abc|abcd))d", "abcd", RegexOptions.None, 0, 4, false, string.Empty); yield return ("(?>(?:a|ab|abc|abcd))d", "abcd", RegexOptions.RightToLeft, 0, 4, true, "abcd"); yield return (@"(...)(?(1)\w*)[a1 ]", "zabcaaaaaaa", RegexOptions.None, 0, 11, true, "zabcaaaaaaa"); yield return (@"(...)(?(1)\w*)[a1 ]", "zabcaaaaaaa", RegexOptions.RightToLeft, 0, 11, true, "aaaa"); yield return (@"(...)(?(1)\w*)[a1 ]", " ", RegexOptions.None, 0, 11, true, " "); yield return (@"(...)(?(1)\w*)[a1 ]", " ", RegexOptions.RightToLeft, 0, 11, true, " "); yield return (@"(...)(?(1)\w*|\s*)[a1 ]", "zabcaaaaaaa", RegexOptions.None, 0, 11, true, "zabcaaaaaaa"); yield return (@"(...)(?(1)\w*|\s*)[a1 ]", "---- ", RegexOptions.None, 0, 11, true, "--- "); yield return (@"(...)(?(1)\w*|\s*)[a1 ]", "zabcaaaaaaa", RegexOptions.RightToLeft, 0, 11, true, "aaaa"); yield return (@"(...)(?(1)\w*|\s*)[a1 ]", "---- ", RegexOptions.RightToLeft, 0, 11, true, "--- "); } // Character Class Substraction // No Negation yield return ("[abcd-[abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return ("[1234-[1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // All Negation yield return ("[^abcd-[^abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return ("[^1234-[^1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // No Negation yield return ("[a-z-[a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return ("[0-9-[0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // All Negation yield return ("[^a-z-[^a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return ("[^0-9-[^0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // No Negation yield return (@"[\w-[\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\W-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\s-[\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\S-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\d-[\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\D-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // All Negation yield return (@"[^\w-[^\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\W-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\s-[^\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\S-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\d-[^\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\D-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // MixedNegation yield return (@"[^\w-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\w-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\s-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\s-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\d-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\d-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // No Negation yield return (@"[\p{Ll}-[\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\P{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\p{Lu}-[\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\P{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\p{Nd}-[\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\P{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); // All Negation yield return (@"[^\p{Ll}-[^\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\P{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\p{Lu}-[^\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\P{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\p{Nd}-[^\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\P{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\p{IsGreek}\p{IsGreekExtended}]", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, true, "a"); // MixedNegation yield return (@"[^\p{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\p{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\p{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\p{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[^\p{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[\p{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); yield return (@"[ab\-\[cd-[-[]]]]", "[]]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[ab\-\[cd-[-[]]]]", "-]]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[ab\-\[cd-[-[]]]]", "`]]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[ab\-\[cd-[-[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[ab\-\[cd-[[]]]]", "']]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[ab\-\[cd-[[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"[a-[a-f]]", "abcdefghijklmnopqrstuvwxyz", RegexOptions.None, 0, 26, false, string.Empty); // \c if (!PlatformDetection.IsNetFramework) // missing fix for https://github.com/dotnet/runtime/issues/24759 { yield return (@"(cat)(\c[*)(dog)", "asdlkcat\u00FFdogiwod", RegexOptions.None, 0, 15, false, string.Empty); } // Surrogate pairs split up into UTF-16 code units. yield return (@"(\uD82F[\uDCA0-\uDCA3])", "\uD82F\uDCA2", RegexOptions.CultureInvariant, 0, 2, true, "\uD82F\uDCA2"); // Unicode text foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.RightToLeft, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant }) { if (engine != RegexEngine.NonBacktracking || options != RegexOptions.RightToLeft) { yield return ("\u05D0\u05D1\u05D2\u05D3(\u05D4\u05D5|\u05D6\u05D7|\u05D8)", "abc\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5def", options, 3, 6, true, "\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5"); yield return ("\u05D0(\u05D4\u05D5|\u05D6\u05D7|\u05D8)", "\u05D0\u05D8", options, 0, 2, true, "\u05D0\u05D8"); yield return ("\u05D0(?:\u05D1|\u05D2|\u05D3)", "\u05D0\u05D2", options, 0, 2, true, "\u05D0\u05D2"); yield return ("\u05D0(?:\u05D1|\u05D2|\u05D3)", "\u05D0\u05D4", options, 0, 0, false, ""); } } // .* : Case sensitive yield return (@".*\nfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@"a.*\nfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@".*\nFoo", $"\nFooThis should match", RegexOptions.None, 0, 21, true, "\nFoo"); yield return (@".*\nfoo", "\nfooThis should match", RegexOptions.None, 4, 17, false, ""); yield return (@".*?\nfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@"a.*?\nfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@".*?\nFoo", $"\nFooThis should match", RegexOptions.None, 0, 21, true, "\nFoo"); yield return (@".*?\nfoo", "\nfooThis should match", RegexOptions.None, 4, 17, false, ""); yield return (@".*\dfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@".*\dFoo", "This1Foo should match", RegexOptions.None, 0, 21, true, "This1Foo"); yield return (@".*\dFoo", "This1foo should 2Foo match", RegexOptions.None, 0, 26, true, "This1foo should 2Foo"); yield return (@".*\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None, 0, 29, false, ""); yield return (@".*\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None, 24, 5, false, ""); yield return (@".*?\dfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@".*?\dFoo", "This1Foo should match", RegexOptions.None, 0, 21, true, "This1Foo"); yield return (@".*?\dFoo", "This1foo should 2Foo match", RegexOptions.None, 0, 26, true, "This1foo should 2Foo"); yield return (@".*?\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None, 0, 29, false, ""); yield return (@".*?\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None, 24, 5, false, ""); yield return (@".*\dfoo", "1fooThis1foo should 1foo match", RegexOptions.None, 4, 9, true, "This1foo"); yield return (@".*\dfoo", "This shouldn't match 1foo", RegexOptions.None, 0, 20, false, ""); yield return (@".*?\dfoo", "1fooThis1foo should 1foo match", RegexOptions.None, 4, 9, true, "This1foo"); yield return (@".*?\dfoo", "This shouldn't match 1foo", RegexOptions.None, 0, 20, false, ""); // Turkish case sensitivity yield return (@"[\u0120-\u0130]", "\u0130", RegexOptions.None, 0, 1, true, "\u0130"); // .* : Case insensitive yield return (@".*\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase, 0, 21, true, "\nfoo"); yield return (@".*\dFoo", "This1foo should match", RegexOptions.IgnoreCase, 0, 21, true, "This1foo"); yield return (@".*\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo should 2FoO"); yield return (@".*\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo should 2fOo"); yield return (@".*\dfoo", "1fooThis1FOO should 1foo match", RegexOptions.IgnoreCase, 4, 9, true, "This1FOO"); yield return (@".*?\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase, 0, 21, true, "\nfoo"); yield return (@".*?\dFoo", "This1foo should match", RegexOptions.IgnoreCase, 0, 21, true, "This1foo"); yield return (@".*?\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo"); yield return (@".*?\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo"); yield return (@".*?\dFo{2}", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo"); yield return (@".*?\dFo{2}", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo"); yield return (@".*?\dfoo", "1fooThis1FOO should 1foo match", RegexOptions.IgnoreCase, 4, 9, true, "This1FOO"); if (!RegexHelpers.IsNonBacktracking(engine)) { // RightToLeft yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 0, 32, true, "foo4567890"); yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 22, true, "foo4567890"); yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 4, true, "foo4"); yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 3, false, string.Empty); yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 11, 21, false, string.Empty); yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 0, 32, true, "foo4567890"); yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 22, true, "foo4567890"); yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 4, true, "foo4"); yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 3, false, string.Empty); yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 11, 21, false, string.Empty); yield return (@"\s+\d+", "sdf 12sad", RegexOptions.RightToLeft, 0, 9, true, " 12"); yield return (@"\s+\d+", " asdf12 ", RegexOptions.RightToLeft, 0, 6, false, string.Empty); yield return ("aaa", "aaabbb", RegexOptions.None, 3, 3, false, string.Empty); yield return ("abc|def", "123def456", RegexOptions.RightToLeft | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 9, true, "def"); // .* : RTL, Case-sensitive yield return (@".*\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*\nfoo", "This should matchfoo\n", RegexOptions.None | RegexOptions.RightToLeft, 4, 13, false, ""); yield return (@"a.*\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*\nFoo", $"This should match\nFoo", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "This should match\nFoo"); yield return (@".*?\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*?\nfoo", "This should matchfoo\n", RegexOptions.None | RegexOptions.RightToLeft, 4, 13, false, ""); yield return (@"a.*?\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*?\nFoo", $"This should match\nFoo", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "\nFoo"); yield return (@".*\dfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*\dFoo", "This1Foo should match", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "This1Foo"); yield return (@".*\dFoo", "This1foo should 2Foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 26, true, "This1foo should 2Foo"); yield return (@".*\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 29, false, ""); yield return (@".*\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 19, 0, false, ""); yield return (@".*?\dfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*?\dFoo", "This1Foo should match", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "1Foo"); yield return (@".*?\dFoo", "This1foo should 2Foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 26, true, "2Foo"); yield return (@".*?\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 29, false, ""); yield return (@".*?\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 19, 0, false, ""); yield return (@".*\dfoo", "1fooThis2foo should 1foo match", RegexOptions.None | RegexOptions.RightToLeft, 8, 4, true, "2foo"); yield return (@".*\dfoo", "This shouldn't match 1foo", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*?\dfoo", "1fooThis2foo should 1foo match", RegexOptions.None | RegexOptions.RightToLeft, 8, 4, true, "2foo"); yield return (@".*?\dfoo", "This shouldn't match 1foo", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); // .* : RTL, case insensitive yield return (@".*\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "\nfoo"); yield return (@".*\dFoo", "This1foo should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "This1foo"); yield return (@".*\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 26, true, "This1foo should 2FoO"); yield return (@".*\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 26, true, "This1Foo should 2fOo"); yield return (@".*\dfoo", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 8, 4, true, "2FOO"); yield return (@"[\w\s].*", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "1fooThis2FOO should 1foo match"); yield return (@"i.*", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "is2FOO should 1foo match"); yield return (@".*?\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "\nfoo"); yield return (@".*?\dFoo", "This1foo should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "1foo"); yield return (@".*?\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 26, true, "2FoO"); yield return (@".*?\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 26, true, "2fOo"); yield return (@".*?\dfoo", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 8, 4, true, "2FOO"); yield return (@"[\w\s].*?", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "h"); yield return (@"i.*?", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "is2FOO should 1foo match"); } // [ActiveIssue("https://github.com/dotnet/runtime/issues/36149")] //if (PlatformDetection.IsNetCore) //{ // // Unicode symbols in character ranges. These are chars whose lowercase values cannot be found by using the offsets specified in s_lcTable. // yield return (@"^(?i:[\u00D7-\u00D8])$", '\u00F7'.ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u00C0-\u00DE])$", '\u00F7'.ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u00C0-\u00DE])$", ((char)('\u00C0' + 32)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u00C0' + 32)).ToString()); // yield return (@"^(?i:[\u00C0-\u00DE])$", ((char)('\u00DE' + 32)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u00DE' + 32)).ToString()); // yield return (@"^(?i:[\u0391-\u03AB])$", ((char)('\u03A2' + 32)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u0391-\u03AB])$", ((char)('\u0391' + 32)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u0391' + 32)).ToString()); // yield return (@"^(?i:[\u0391-\u03AB])$", ((char)('\u03AB' + 32)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u03AB' + 32)).ToString()); // yield return (@"^(?i:[\u1F18-\u1F1F])$", ((char)('\u1F1F' - 8)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u1F18-\u1F1F])$", ((char)('\u1F18' - 8)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u1F18' - 8)).ToString()); // yield return (@"^(?i:[\u10A0-\u10C5])$", ((char)('\u10A0' + 7264)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u10A0' + 7264)).ToString()); // yield return (@"^(?i:[\u10A0-\u10C5])$", ((char)('\u1F1F' + 48)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u24B6-\u24D0])$", ((char)('\u24D0' + 26)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, false, ""); // yield return (@"^(?i:[\u24B6-\u24D0])$", ((char)('\u24CF' + 26)).ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, 1, true, ((char)('\u24CF' + 26)).ToString()); //} // Long inputs string longCharacterRange = string.Concat(Enumerable.Range(1, 0x2000).Select(c => (char)c)); foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.IgnoreCase }) { yield return ("\u1000", longCharacterRange, options, 0, 0x2000, true, "\u1000"); yield return ("[\u1000-\u1001]", longCharacterRange, options, 0, 0x2000, true, "\u1000"); yield return ("[\u0FF0-\u0FFF][\u1000-\u1001]", longCharacterRange, options, 0, 0x2000, true, "\u0FFF\u1000"); yield return ("\uA640", longCharacterRange, options, 0, 0x2000, false, ""); yield return ("[\u3000-\u3001]", longCharacterRange, options, 0, 0x2000, false, ""); yield return ("[\uA640-\uA641][\u3000-\u3010]", longCharacterRange, options, 0, 0x2000, false, ""); if (!RegexHelpers.IsNonBacktracking(engine)) { yield return ("\u1000", longCharacterRange, options | RegexOptions.RightToLeft, 0, 0x2000, true, "\u1000"); yield return ("[\u1000-\u1001]", longCharacterRange, options | RegexOptions.RightToLeft, 0, 0x2000, true, "\u1001"); yield return ("[\u1000][\u1001-\u1010]", longCharacterRange, options, 0, 0x2000, true, "\u1000\u1001"); yield return ("\uA640", longCharacterRange, options | RegexOptions.RightToLeft, 0, 0x2000, false, ""); yield return ("[\u3000-\u3001][\uA640-\uA641]", longCharacterRange, options | RegexOptions.RightToLeft, 0, 0x2000, false, ""); } } foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.Singleline }) { yield return (@"\W.*?\D", "seq 012 of 3 digits", options, 0, 19, true, " 012 "); yield return (@"\W.+?\D", "seq 012 of 3 digits", options, 0, 19, true, " 012 "); yield return (@"\W.{1,7}?\D", "seq 012 of 3 digits", options, 0, 19, true, " 012 "); yield return (@"\W.{1,2}?\D", "seq 012 of 3 digits", options, 0, 19, true, " of"); yield return (@"\W.*?\b", "digits:0123456789", options, 0, 17, true, ":"); yield return (@"\B.*?\B", "e.g:abc", options, 0, 7, true, ""); yield return (@"\B\W+?", "e.g:abc", options, 0, 7, false, ""); yield return (@"\B\W*?", "e.g:abc", options, 0, 7, true, ""); // While not lazy loops themselves, variants of the prior case that should give same results here yield return (@"\B\W*", "e.g:abc", options, 0, 7, true, ""); yield return (@"\B\W?", "e.g:abc", options, 0, 7, true, ""); //mixed lazy and eager counting yield return ("z(a{0,5}|a{0,10}?)", "xyzaaaaaaaaaxyz", options, 0, 15, true, "zaaaaa"); } } } [Theory] [MemberData(nameof(Match_MemberData))] public void Match(RegexEngine engine, string pattern, string input, RegexOptions options, Regex r, int beginning, int length, bool expectedSuccess, string expectedValue) { bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning); bool isDefaultCount = RegexHelpers.IsDefaultCount(input, options, length); // Test instance method overloads if (isDefaultStart && isDefaultCount) { VerifyMatch(r.Match(input)); VerifyIsMatch(r, input, expectedSuccess, Regex.InfiniteMatchTimeout); } if (beginning + length == input.Length && (options & RegexOptions.RightToLeft) == 0) { VerifyMatch(r.Match(input, beginning)); } VerifyMatch(r.Match(input, beginning, length)); // Test static method overloads if (isDefaultStart && isDefaultCount) { switch (engine) { case RegexEngine.Interpreter: case RegexEngine.Compiled: case RegexEngine.NonBacktracking: VerifyMatch(Regex.Match(input, pattern, options | RegexHelpers.OptionsFromEngine(engine))); VerifyIsMatch(null, input, expectedSuccess, Regex.InfiniteMatchTimeout, pattern, options | RegexHelpers.OptionsFromEngine(engine)); break; } } void VerifyMatch(Match match) { Assert.Equal(expectedSuccess, match.Success); RegexAssert.Equal(expectedValue, match); // Groups can never be empty Assert.True(match.Groups.Count >= 1); Assert.Equal(expectedSuccess, match.Groups[0].Success); RegexAssert.Equal(expectedValue, match.Groups[0]); } } private async Task CreateAndMatch(RegexEngine engine, string pattern, string input, RegexOptions options, int beginning, int length, bool expectedSuccess, string expectedValue) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); Match(engine, pattern, input, options, r, beginning, length, expectedSuccess, expectedValue); } public static IEnumerable<object[]> Match_VaryingLengthStrings_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { foreach (int length in new[] { 2, 3, 7, 8, 9, 64 }) { yield return new object[] { engine, RegexOptions.None, length }; yield return new object[] { engine, RegexOptions.IgnoreCase, length }; yield return new object[] { engine, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, length }; } } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Takes several minutes on .NET Framework")] [Theory] [MemberData(nameof(Match_VaryingLengthStrings_MemberData))] public async Task Match_VaryingLengthStrings(RegexEngine engine, RegexOptions options, int length) { bool caseInsensitive = (options & RegexOptions.IgnoreCase) != 0; string pattern = "[123]" + string.Concat(Enumerable.Range(0, length).Select(i => (char)('A' + (i % 26)))); string input = "2" + string.Concat(Enumerable.Range(0, length).Select(i => (char)((caseInsensitive ? 'a' : 'A') + (i % 26)))); Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); Match(engine, pattern, input, options, r, 0, input.Length, expectedSuccess: true, expectedValue: input); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Takes several minutes on .NET Framework")] [OuterLoop("Takes several seconds")] [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_VaryingLengthStrings_Huge(RegexEngine engine) { await Match_VaryingLengthStrings(engine, RegexOptions.None, 100_000); } public static IEnumerable<object[]> Match_DeepNesting_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { if (RegexHelpers.IsNonBacktracking(engine)) { // expression uses atomic group continue; } yield return new object[] { engine, 1 }; yield return new object[] { engine, 10 }; yield return new object[] { engine, 100 }; } } [Theory] [MemberData(nameof(Match_DeepNesting_MemberData))] public async void Match_DeepNesting(RegexEngine engine, int count) { const string Start = @"((?>abc|(?:def[ghi]", End = @")))"; const string Match = "defg"; string pattern = string.Concat(Enumerable.Repeat(Start, count)) + string.Concat(Enumerable.Repeat(End, count)); string input = string.Concat(Enumerable.Repeat(Match, count)); Regex r = await RegexHelpers.GetRegexAsync(engine, pattern); Match m = r.Match(input); Assert.True(m.Success); RegexAssert.Equal(input, m); Assert.Equal(count + 1, m.Groups.Count); } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_Timeout(RegexEngine engine) { Regex regex = await RegexHelpers.GetRegexAsync(engine, @"\p{Lu}", RegexOptions.IgnoreCase, TimeSpan.FromHours(1)); Match match = regex.Match("abc"); Assert.True(match.Success); RegexAssert.Equal("a", match); } /// <summary> /// Test that timeout exception is being thrown. /// </summary> [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] private async Task Match_TestThatTimeoutHappens(RegexEngine engine) { var rnd = new Random(42); var chars = new char[1_000_000]; for (int i = 0; i < chars.Length; i++) { byte b = (byte)rnd.Next(0, 256); chars[i] = b < 200 ? 'a' : (char)b; } string input = new string(chars); Regex re = await RegexHelpers.GetRegexAsync(engine, @"a.{20}^", RegexOptions.None, TimeSpan.FromMilliseconds(10)); Assert.Throws<RegexMatchTimeoutException>(() => { re.Match(input); }); } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_Timeout_Throws(RegexEngine engine) { if (RegexHelpers.IsNonBacktracking(engine)) { // test relies on backtracking taking a long time return; } const string Pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$"; string input = new string('a', 50) + "@a.a"; Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.None, TimeSpan.FromMilliseconds(100)); Assert.Throws<RegexMatchTimeoutException>(() => r.Match(input)); } // TODO: Figure out what to do with default timeouts for source generated regexes [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [InlineData(RegexOptions.None)] [InlineData(RegexOptions.Compiled)] public void Match_DefaultTimeout_Throws(RegexOptions options) { RemoteExecutor.Invoke(optionsString => { const string Pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$"; string input = new string('a', 50) + "@a.a"; AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, TimeSpan.FromMilliseconds(100)); if ((RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture) == RegexOptions.None) { Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern).Match(input)); Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern).IsMatch(input)); Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern).Matches(input).Count); Assert.Throws<RegexMatchTimeoutException>(() => Regex.Match(input, Pattern)); Assert.Throws<RegexMatchTimeoutException>(() => Regex.IsMatch(input, Pattern)); Assert.Throws<RegexMatchTimeoutException>(() => Regex.Matches(input, Pattern).Count); } Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture)).Match(input)); Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture)).IsMatch(input)); Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture)).Matches(input).Count); Assert.Throws<RegexMatchTimeoutException>(() => Regex.Match(input, Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture))); Assert.Throws<RegexMatchTimeoutException>(() => Regex.IsMatch(input, Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture))); Assert.Throws<RegexMatchTimeoutException>(() => Regex.Matches(input, Pattern, (RegexOptions)int.Parse(optionsString, CultureInfo.InvariantCulture)).Count); }, ((int)options).ToString(CultureInfo.InvariantCulture)).Dispose(); } // TODO: Figure out what to do with default timeouts for source generated regexes [Theory] [InlineData(RegexOptions.None)] [InlineData(RegexOptions.Compiled)] public void Match_CachedPattern_NewTimeoutApplies(RegexOptions options) { const string PatternLeadingToLotsOfBacktracking = @"^(\w+\s?)*$"; VerifyIsMatch(null, "", true, TimeSpan.FromDays(1), PatternLeadingToLotsOfBacktracking, options); var sw = Stopwatch.StartNew(); VerifyIsMatchThrows<RegexMatchTimeoutException>(null, "An input string that takes a very very very very very very very very very very very long time!", TimeSpan.FromMilliseconds(1), PatternLeadingToLotsOfBacktracking, options); Assert.InRange(sw.Elapsed.TotalSeconds, 0, 10); // arbitrary upper bound that should be well above what's needed with a 1ms timeout } // On 32-bit we can't test these high inputs as they cause OutOfMemoryExceptions. // On Linux, we may get killed by the OOM Killer; on Windows, it will swap instead [OuterLoop("Can take several seconds")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess), nameof(PlatformDetection.IsWindows))] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_Timeout_Loop_Throws(RegexEngine engine) { if (RegexHelpers.IsNonBacktracking(engine)) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/60623")] return; } Regex regex = await RegexHelpers.GetRegexAsync(engine, @"a\s+", RegexOptions.None, TimeSpan.FromSeconds(1)); string input = "a" + new string(' ', 800_000_000) + " "; Assert.Throws<RegexMatchTimeoutException>(() => regex.Match(input)); } // On 32-bit we can't test these high inputs as they cause OutOfMemoryExceptions. // On Linux, we may get killed by the OOM Killer; on Windows, it will swap instead [OuterLoop("Can take several seconds")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess), nameof(PlatformDetection.IsWindows))] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_Timeout_Repetition_Throws(RegexEngine engine) { if (engine == RegexEngine.NonBacktracking) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/65991")] return; } int repetitionCount = 800_000_000; Regex regex = await RegexHelpers.GetRegexAsync(engine, @"a\s{" + repetitionCount + "}", RegexOptions.None, TimeSpan.FromSeconds(1)); string input = @"a" + new string(' ', repetitionCount) + @"b"; Assert.Throws<RegexMatchTimeoutException>(() => regex.Match(input)); } public static IEnumerable<object[]> Match_Advanced_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { // \B special character escape: ".*\\B(SUCCESS)\\B.*" yield return new object[] { engine, @".*\B(SUCCESS)\B.*", "adfadsfSUCCESSadsfadsf", RegexOptions.None, 0, 22, new CaptureData[] { new CaptureData("adfadsfSUCCESSadsfadsf", 0, 22), new CaptureData("SUCCESS", 7, 7) } }; // Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$" yield return new object[] { engine, "^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8, new CaptureData[] { new CaptureData("aaabb.cc", 0, 8), new CaptureData("bb.c", 3, 4), new CaptureData("c", 7, 1) } }; // Using greedy quantifiers: Actual - "(a+)(b*)(c?)" yield return new object[] { engine, "(a+)(b*)(c?)", "aaabbbccc", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("aaabbbc", 0, 7), new CaptureData("aaa", 0, 3), new CaptureData("bbb", 3, 3), new CaptureData("c", 6, 1) } }; // Using lazy quantifiers: Actual - "(d+?)(e*?)(f??)" // Interesting match from this pattern and input. If needed to go to the end of the string change the ? to + in the last lazy quantifier yield return new object[] { engine, "(d+?)(e*?)(f??)", "dddeeefff", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("d", 0, 1), new CaptureData("d", 0, 1), new CaptureData(string.Empty, 1, 0), new CaptureData(string.Empty, 1, 0) } }; yield return new object[] { engine, "(d+?)(e*?)(f+)", "dddeeefff", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("dddeeefff", 0, 9), new CaptureData("ddd", 0, 3), new CaptureData("eee", 3, 3), new CaptureData("fff", 6, 3), } }; // Noncapturing group : Actual - "(a+)(?:b*)(ccc)" yield return new object[] { engine, "(a+)(?:b*)(ccc)", "aaabbbccc", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("aaabbbccc", 0, 9), new CaptureData("aaa", 0, 3), new CaptureData("ccc", 6, 3), } }; // Alternation constructs: Actual - "(111|aaa)" yield return new object[] { engine, "(111|aaa)", "aaa", RegexOptions.None, 0, 3, new CaptureData[] { new CaptureData("aaa", 0, 3), new CaptureData("aaa", 0, 3) } }; // Using "n" Regex option. Only explicitly named groups should be captured: Actual - "([0-9]*)\\s(?<s>[a-z_A-Z]+)", "n" yield return new object[] { engine, @"([0-9]*)\s(?<s>[a-z_A-Z]+)", "200 dollars", RegexOptions.ExplicitCapture, 0, 11, new CaptureData[] { new CaptureData("200 dollars", 0, 11), new CaptureData("dollars", 4, 7) } }; // Single line mode "s". Includes new line character: Actual - "([^/]+)","s" yield return new object[] { engine, "(.*)", "abc\nsfc", RegexOptions.Singleline, 0, 7, new CaptureData[] { new CaptureData("abc\nsfc", 0, 7), new CaptureData("abc\nsfc", 0, 7), } }; // "([0-9]+(\\.[0-9]+){3})" yield return new object[] { engine, @"([0-9]+(\.[0-9]+){3})", "209.25.0.111", RegexOptions.None, 0, 12, new CaptureData[] { new CaptureData("209.25.0.111", 0, 12), new CaptureData("209.25.0.111", 0, 12), new CaptureData(".111", 8, 4, new CaptureData[] { new CaptureData(".25", 3, 3), new CaptureData(".0", 6, 2), new CaptureData(".111", 8, 4), }), } }; // Groups and captures yield return new object[] { engine, @"(?<A1>a*)(?<A2>b*)(?<A3>c*)", "aaabbccccccccccaaaabc", RegexOptions.None, 0, 21, new CaptureData[] { new CaptureData("aaabbcccccccccc", 0, 15), new CaptureData("aaa", 0, 3), new CaptureData("bb", 3, 2), new CaptureData("cccccccccc", 5, 10) } }; yield return new object[] { engine, @"(?<A1>A*)(?<A2>B*)(?<A3>C*)", "aaabbccccccccccaaaabc", RegexOptions.IgnoreCase, 0, 21, new CaptureData[] { new CaptureData("aaabbcccccccccc", 0, 15), new CaptureData("aaa", 0, 3), new CaptureData("bb", 3, 2), new CaptureData("cccccccccc", 5, 10) } }; // Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$" yield return new object[] { engine, "^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8, new CaptureData[] { new CaptureData("aaabb.cc", 0, 8), new CaptureData("bb.c", 3, 4), new CaptureData("c", 7, 1) } }; // Actual - ".*\\b(\\w+)\\b" yield return new object[] { engine, @".*\b(\w+)\b", "XSP_TEST_FAILURE SUCCESS", RegexOptions.None, 0, 24, new CaptureData[] { new CaptureData("XSP_TEST_FAILURE SUCCESS", 0, 24), new CaptureData("SUCCESS", 17, 7) } }; // Multiline yield return new object[] { engine, "(line2$\n)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; // Multiline yield return new object[] { engine, "(line2\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; // Multiline yield return new object[] { engine, "(line3\n$\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line3\n\nline4", 12, 12), new CaptureData("line3\n\n", 12, 7) } }; // Multiline yield return new object[] { engine, "(line3\n^\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line3\n\nline4", 12, 12), new CaptureData("line3\n\n", 12, 7) } }; // Multiline yield return new object[] { engine, "(line2$\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24, new CaptureData[] { new CaptureData("line2\nline3", 6, 11), new CaptureData("line2\n", 6, 6) } }; if (!RegexHelpers.IsNonBacktracking(engine)) { // Zero-width positive lookahead assertion: Actual - "abc(?=XXX)\\w+" yield return new object[] { engine, @"abc(?=XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("abcXXXdef", 0, 9) } }; // Backreferences : Actual - "(\\w)\\1" yield return new object[] { engine, @"(\w)\1", "aa", RegexOptions.None, 0, 2, new CaptureData[] { new CaptureData("aa", 0, 2), new CaptureData("a", 0, 1), } }; // Actual - "(?<1>\\d+)abc(?(1)222|111)" yield return new object[] { engine, @"(?<MyDigits>\d+)abc(?(MyDigits)222|111)", "111abc222", RegexOptions.None, 0, 9, new CaptureData[] { new CaptureData("111abc222", 0, 9), new CaptureData("111", 0, 3) } }; // RightToLeft yield return new object[] { engine, "aaa", "aaabbb", RegexOptions.RightToLeft, 3, 3, new CaptureData[] { new CaptureData("aaa", 0, 3) } }; // RightToLeft with anchor yield return new object[] { engine, "^aaa", "aaabbb", RegexOptions.RightToLeft, 3, 3, new CaptureData[] { new CaptureData("aaa", 0, 3) } }; yield return new object[] { engine, "bbb$", "aaabbb", RegexOptions.RightToLeft, 0, 3, new CaptureData[] { new CaptureData("bbb", 0, 3) } }; } } } [Theory] [MemberData(nameof(Match_Advanced_TestData))] public async Task Match_Advanced(RegexEngine engine, string pattern, string input, RegexOptions options, int beginning, int length, CaptureData[] expected) { bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning); bool isDefaultCount = RegexHelpers.IsDefaultStart(input, options, length); Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); if (isDefaultStart && isDefaultCount) { // Use Match(string) or Match(string, string, RegexOptions) VerifyMatch(r.Match(input)); VerifyMatch(Regex.Match(input, pattern, options)); VerifyIsMatch(null, input, true, Regex.InfiniteMatchTimeout, pattern, options); } if (beginning + length == input.Length) { // Use Match(string, int) VerifyMatch(r.Match(input, beginning)); } if ((options & RegexOptions.RightToLeft) == 0) { // Use Match(string, int, int) VerifyMatch(r.Match(input, beginning, length)); } void VerifyMatch(Match match) { Assert.True(match.Success); RegexAssert.Equal(expected[0].Value, match); Assert.Equal(expected[0].Index, match.Index); Assert.Equal(expected[0].Length, match.Length); Assert.Equal(1, match.Captures.Count); RegexAssert.Equal(expected[0].Value, match.Captures[0]); Assert.Equal(expected[0].Index, match.Captures[0].Index); Assert.Equal(expected[0].Length, match.Captures[0].Length); Assert.Equal(expected.Length, match.Groups.Count); for (int i = 0; i < match.Groups.Count; i++) { Assert.True(match.Groups[i].Success); RegexAssert.Equal(expected[i].Value, match.Groups[i]); Assert.Equal(expected[i].Index, match.Groups[i].Index); Assert.Equal(expected[i].Length, match.Groups[i].Length); if (!RegexHelpers.IsNonBacktracking(engine)) { Assert.Equal(expected[i].Captures.Length, match.Groups[i].Captures.Count); for (int j = 0; j < match.Groups[i].Captures.Count; j++) { RegexAssert.Equal(expected[i].Captures[j].Value, match.Groups[i].Captures[j]); Assert.Equal(expected[i].Captures[j].Index, match.Groups[i].Captures[j].Index); Assert.Equal(expected[i].Captures[j].Length, match.Groups[i].Captures[j].Length); } } else { // NonBacktracking does not support multiple captures Assert.Equal(1, match.Groups[i].Captures.Count); int lastExpected = expected[i].Captures.Length - 1; RegexAssert.Equal(expected[i].Captures[lastExpected].Value, match.Groups[i].Captures[0]); Assert.Equal(expected[i].Captures[lastExpected].Index, match.Groups[i].Captures[0].Index); Assert.Equal(expected[i].Captures[lastExpected].Length, match.Groups[i].Captures[0].Length); } } } } public static IEnumerable<object[]> Match_StartatDiffersFromBeginning_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.Singleline, RegexOptions.Multiline, RegexOptions.Singleline | RegexOptions.Multiline }) { // Anchors yield return new object[] { engine, @"^.*", "abc", options, 0, true, true }; yield return new object[] { engine, @"^.*", "abc", options, 1, false, true }; } if (!RegexHelpers.IsNonBacktracking(engine)) { // Positive and negative lookbehinds yield return new object[] { engine, @"(?<=abc)def", "abcdef", RegexOptions.None, 3, true, false }; yield return new object[] { engine, @"(?<!abc)def", "abcdef", RegexOptions.None, 3, false, true }; } } } [Theory] [MemberData(nameof(Match_StartatDiffersFromBeginning_MemberData))] public async Task Match_StartatDiffersFromBeginning(RegexEngine engine, string pattern, string input, RegexOptions options, int startat, bool expectedSuccessStartAt, bool expectedSuccessBeginning) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); Assert.Equal(expectedSuccessStartAt, r.IsMatch(input, startat)); Assert.Equal(expectedSuccessStartAt, r.Match(input, startat).Success); Assert.Equal(expectedSuccessBeginning, r.Match(input.Substring(startat)).Success); Assert.Equal(expectedSuccessBeginning, r.Match(input, startat, input.Length - startat).Success); } [Theory] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${time}", "16:00")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${1}", "08")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${2}", "10")] [InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${3}", "99")] [InlineData("abc", "abc", "abc", "abc")] public void Result(string pattern, string input, string replacement, string expected) { Assert.Equal(expected, new Regex(pattern).Match(input).Result(replacement)); } [Fact] public void Result_Invalid() { Match match = Regex.Match("foo", "foo"); AssertExtensions.Throws<ArgumentNullException>("replacement", () => match.Result(null)); Assert.Throws<NotSupportedException>(() => RegularExpressions.Match.Empty.Result("any")); } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_SpecialUnicodeCharacters_enUS(RegexEngine engine) { using (new ThreadCultureChange("en-US")) { await CreateAndMatch(engine, "\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); await CreateAndMatch(engine, "\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); } } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_SpecialUnicodeCharacters_Invariant(RegexEngine engine) { using (new ThreadCultureChange(CultureInfo.InvariantCulture)) { await CreateAndMatch(engine, "\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); await CreateAndMatch(engine, "\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); await CreateAndMatch(engine, "\u0130", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); await CreateAndMatch(engine, "\u0130", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty); } } private static bool IsNotArmProcessAndRemoteExecutorSupported => PlatformDetection.IsNotArmProcess && RemoteExecutor.IsSupported; [ConditionalTheory(nameof(IsNotArmProcessAndRemoteExecutorSupported))] // times out on ARM [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework does not have fix for https://github.com/dotnet/runtime/issues/24749")] [SkipOnCoreClr("Long running tests: https://github.com/dotnet/runtime/issues/10680", ~RuntimeConfiguration.Release)] [SkipOnCoreClr("Long running tests: https://github.com/dotnet/runtime/issues/10680", RuntimeTestModes.JitMinOpts)] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public void Match_ExcessPrefix(RegexEngine engine) { RemoteExecutor.Invoke(async engineString => { var engine = (RegexEngine)Enum.Parse(typeof(RegexEngine), engineString); // Should not throw out of memory // Repeaters VerifyIsMatch((await RegexHelpers.GetRegexAsync(engine, @"a{2147483647,}")), "a", false, Regex.InfiniteMatchTimeout); VerifyIsMatch((await RegexHelpers.GetRegexAsync(engine, @"a{50,}")), "a", false, Regex.InfiniteMatchTimeout); VerifyIsMatch((await RegexHelpers.GetRegexAsync(engine, @"a{50_000,}")), "a", false, Regex.InfiniteMatchTimeout); // cutoff for Boyer-Moore prefix in release // Multis foreach (int length in new[] { 50, 50_000, char.MaxValue + 1 }) { // The large counters are too slow for counting a's in NonBacktracking engine // They will incur a constant of size length because in .*a{k} after reading n a's the // state will be .*a{k}|a{k-1}|...|a{k-n} which could be compacted to // .*a{k}|a{k-n,k-1} but is not currently being compacted if (!RegexHelpers.IsNonBacktracking(engine) || length < 50_000) { string s = "bcd" + new string('a', length) + "efg"; VerifyIsMatch((await RegexHelpers.GetRegexAsync(engine, @$"a{{{length}}}")), s, true, Regex.InfiniteMatchTimeout); } } }, engine.ToString()).Dispose(); } [Fact] public void Match_Invalid() { var r = new Regex("pattern"); // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => r.Match(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => r.Match(null, 0)); AssertExtensions.Throws<ArgumentNullException>("input", () => r.Match(null, 0, 0)); // Pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None, TimeSpan.FromSeconds(1))); // Start is invalid Assert.Throws<ArgumentOutOfRangeException>(() => r.Match("input", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => r.Match("input", -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => r.Match("input", 6)); Assert.Throws<ArgumentOutOfRangeException>(() => r.Match("input", 6, 0)); // Length is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => r.Match("input", 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => r.Match("input", 0, 6)); } [Fact] public void IsMatch_Invalid() { var r = new Regex("pattern"); // Input is null AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); AssertExtensions.Throws<ArgumentNullException>("input", () => r.IsMatch(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => r.IsMatch(null, 0)); // Pattern is null VerifyIsMatchThrows<ArgumentNullException>(null, "input", Regex.InfiniteMatchTimeout, pattern: null); VerifyIsMatchThrows<ArgumentNullException>(null, "input", Regex.InfiniteMatchTimeout, pattern: null, RegexOptions.None); VerifyIsMatchThrows<ArgumentNullException>(null, "input", TimeSpan.FromSeconds(1), pattern: null, RegexOptions.None); // Start is invalid Assert.Throws<ArgumentOutOfRangeException>(() => r.IsMatch("input", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => r.IsMatch("input", 6)); } public static IEnumerable<object[]> IsMatch_SucceedQuicklyDueToLoopReduction_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, @"(?:\w*)+\.", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false }; yield return new object[] { engine, @"(?:a+)+b", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false }; yield return new object[] { engine, @"(?:x+x+)+y", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", false }; } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // take too long due to backtracking [Theory] [MemberData(nameof(IsMatch_SucceedQuicklyDueToLoopReduction_MemberData))] public async Task IsMatch_SucceedQuicklyDueToLoopReduction(RegexEngine engine, string pattern, string input, bool expected) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern); VerifyIsMatch(r, input, expected, Regex.InfiniteMatchTimeout); } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task TestCharIsLowerCultureEdgeCasesAroundTurkishCharacters(RegexEngine engine) { Regex r1 = await RegexHelpers.GetRegexAsync(engine, "[\u012F-\u0130]", RegexOptions.IgnoreCase); Regex r2 = await RegexHelpers.GetRegexAsync(engine, "[\u012F\u0130]", RegexOptions.IgnoreCase); Assert.Equal(r1.IsMatch("\u0130"), r2.IsMatch("\u0130")); #if NET7_0_OR_GREATER Assert.Equal(r1.IsMatch("\u0130".AsSpan()), r2.IsMatch("\u0130".AsSpan())); #endif } [Fact] public void Synchronized() { var m = new Regex("abc").Match("abc"); Assert.True(m.Success); RegexAssert.Equal("abc", m); var m2 = System.Text.RegularExpressions.Match.Synchronized(m); Assert.Same(m, m2); Assert.True(m2.Success); RegexAssert.Equal("abc", m2); AssertExtensions.Throws<ArgumentNullException>("inner", () => System.Text.RegularExpressions.Match.Synchronized(null)); } /// <summary> /// Tests current inconsistent treatment of \b and \w. /// The match fails because \u200c and \u200d do not belong to \w. /// At the same time \u200c and \u200d are considered as word characters for the \b and \B anchors. /// The test checks that the same behavior applies to all backends. /// </summary> [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Match_Boundary(RegexEngine engine) { Regex r = await RegexHelpers.GetRegexAsync(engine, @"\b\w+\b"); VerifyIsMatch(r, " AB\u200cCD ", false, Regex.InfiniteMatchTimeout); VerifyIsMatch(r, " AB\u200dCD ", false, Regex.InfiniteMatchTimeout); } public static IEnumerable<object[]> Match_Count_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, @"\b\w+\b", "one two three", 3 }; yield return new object[] { engine, @"\b\w+\b", "on\u200ce two three", 2 }; yield return new object[] { engine, @"\b\w+\b", "one tw\u200do three", 2 }; } string b1 = @"((?<=\w)(?!\w)|(?<!\w)(?=\w))"; string b2 = @"((?<=\w)(?=\W)|(?<=\W)(?=\w))"; // Lookarounds are currently not supported in the NonBacktracking engine foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { if (engine == RegexEngine.NonBacktracking) continue; // b1 is semantically identical to \b except for \u200c and \u200d yield return new object[] { engine, $@"{b1}\w+{b1}", "one two three", 3 }; yield return new object[] { engine, $@"{b1}\w+{b1}", "on\u200ce two three", 4 }; // contrast between using \W = [^\w] vs negative lookaround !\w yield return new object[] { engine, $@"{b2}\w+{b2}", "one two three", 1 }; yield return new object[] { engine, $@"{b2}\w+{b2}", "one two", 0 }; } } [Theory] [MemberData(nameof(Match_Count_TestData))] public async Task Match_Count(RegexEngine engine, string pattern, string input, int expectedCount) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern); Assert.Equal(expectedCount,r.Matches(input).Count); } public static IEnumerable<object[]> StressTestDeepNestingOfConcat_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, "[a-z]", "", "abcde", 2000, 400 }; yield return new object[] { engine, "[a-e]*", "$", "abcde", 2000, 20 }; yield return new object[] { engine, "[a-d]?[a-e]?[a-f]?[a-g]?[a-h]?", "$", "abcda", 400, 4 }; yield return new object[] { engine, "(a|A)", "", "aAaAa", 2000, 400 }; } } [OuterLoop("Can take over a minute")] [Theory] [MemberData(nameof(StressTestDeepNestingOfConcat_TestData))] public async Task StressTestDeepNestingOfConcat(RegexEngine engine, string pattern, string anchor, string input, int pattern_repetition, int input_repetition) { if (engine == RegexEngine.SourceGenerated) { // Currently too stressful for Roslyn. return; } if (engine == RegexEngine.NonBacktracking) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/60645")] return; } string fullpattern = string.Concat(string.Concat(Enumerable.Repeat($"({pattern}", pattern_repetition).Concat(Enumerable.Repeat(")", pattern_repetition))), anchor); string fullinput = string.Concat(Enumerable.Repeat(input, input_repetition)); Regex re = await RegexHelpers.GetRegexAsync(engine, fullpattern); Assert.True(re.Match(fullinput).Success); } public static IEnumerable<object[]> StressTestDeepNestingOfLoops_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, "(", "a", ")*", RegexOptions.None, "a", 2000, 1000 }; yield return new object[] { engine, "(", "[aA]", ")+", RegexOptions.None, "aA", 2000, 3000 }; yield return new object[] { engine, "(", "ab", "){0,1}", RegexOptions.None, "ab", 2000, 1000 }; } } [OuterLoop("Can take over 10 seconds")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))] // consumes a lot of memory [MemberData(nameof(StressTestDeepNestingOfLoops_TestData))] public async Task StressTestDeepNestingOfLoops(RegexEngine engine, string begin, string inner, string end, RegexOptions options, string input, int pattern_repetition, int input_repetition) { if (engine == RegexEngine.SourceGenerated) { // Currently too stressful for Roslyn. return; } string fullpattern = string.Concat(Enumerable.Repeat(begin, pattern_repetition)) + inner + string.Concat(Enumerable.Repeat(end, pattern_repetition)); string fullinput = string.Concat(Enumerable.Repeat(input, input_repetition)); var re = await RegexHelpers.GetRegexAsync(engine, fullpattern, options); Assert.True(re.Match(fullinput).Success); } public static IEnumerable<object[]> StressTestNfaMode_TestData() { yield return new object[] { "(?:a|aa|[abc]?[ab]?[abcd]).{20}$", "aaa01234567890123456789", 23 }; yield return new object[] { "(?:a|AA|BCD).{20}$", "a01234567890123456789", 21 }; yield return new object[] { "(?:a.{20}|a.{10})bc$", "a01234567890123456789bc", 23 }; } /// <summary> /// Causes NonBacktracking engine to switch to NFA mode internally. /// NFA mode is otherwise never triggered by typical cases. /// </summary> [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Doesn't support NonBacktracking")] [MemberData(nameof(StressTestNfaMode_TestData))] public async Task StressTestNfaMode(string pattern, string input_suffix, int expected_matchlength) { Random random = new Random(0); byte[] buffer = new byte[50_000]; random.NextBytes(buffer); // Consider a random string of 50_000 a's and b's var input = new string(Array.ConvertAll(buffer, b => (b <= 0x7F ? 'a' : 'b'))); input += input_suffix; Regex re = await RegexHelpers.GetRegexAsync(RegexEngine.NonBacktracking, pattern, RegexOptions.Singleline); Match m = re.Match(input); Assert.True(m.Success); Assert.Equal(buffer.Length, m.Index); Assert.Equal(expected_matchlength, m.Length); } public static IEnumerable<object[]> AllMatches_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { // Basic yield return new object[] { engine, @"a+", RegexOptions.None, "xxxxxaaaaxxxxxxxxxxaaaaaa", new (int, int, string)[] { (5, 4, "aaaa"), (19, 6, "aaaaaa") } }; yield return new object[] { engine, @"(...)+", RegexOptions.None, "abcd\nfghijklm", new (int, int, string)[] { (0, 3, "abc"), (5, 6, "fghijk") } }; yield return new object[] { engine, @"something", RegexOptions.None, "nothing", null }; yield return new object[] { engine, "(a|ba)c", RegexOptions.None, "bac", new (int, int, string)[] { (0, 3, "bac") } }; yield return new object[] { engine, "(a|ba)c", RegexOptions.None, "ac", new (int, int, string)[] { (0, 2, "ac") } }; yield return new object[] { engine, "(a|ba)c", RegexOptions.None, "baacd", new (int, int, string)[] { (2, 2, "ac") } }; yield return new object[] { engine, "\n", RegexOptions.None, "\n", new (int, int, string)[] { (0, 1, "\n") } }; yield return new object[] { engine, "[^a]", RegexOptions.None, "\n", new (int, int, string)[] { (0, 1, "\n") } }; // In Singleline mode . includes all characters, also \n yield return new object[] { engine, @"(...)+", RegexOptions.None | RegexOptions.Singleline, "abcd\nfghijklm", new (int, int, string)[] { (0, 12, "abcd\nfghijkl") } }; // Ignoring case yield return new object[] { engine, @"a+", RegexOptions.None | RegexOptions.IgnoreCase, "xxxxxaAAaxxxxxxxxxxaaaaAa", new (int, int, string)[] { (5, 4, "aAAa"), (19, 6, "aaaaAa") } }; // NonASCII characters yield return new object[] { engine, @"(\uFFFE\uFFFF)+", RegexOptions.None, "=====\uFFFE\uFFFF\uFFFE\uFFFF\uFFFE====", new (int, int, string)[] { (5, 4, "\uFFFE\uFFFF\uFFFE\uFFFF") } }; yield return new object[] { engine, @"\d\s\w+", RegexOptions.None, "=====1\v\u212A4==========1\ta\u0130Aa", new (int, int, string)[] { (5, 4, "1\v\u212A4"), (19, 6, "1\ta\u0130Aa") } }; yield return new object[] { engine, @"\u221E|\u2713", RegexOptions.None, "infinity \u221E and checkmark \u2713 are contained here", new (int, int, string)[] { (9, 1, "\u221E"), (25, 1, "\u2713") } }; // Whitespace yield return new object[] { engine, @"\s+", RegexOptions.None, "===== \n\t\v\r ====", new (int, int, string)[] { (5, 6, " \n\t\v\r ") } }; // Unicode character classes, the input string uses the first element of each character class yield return new object[] { engine, @"\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Mn}\p{Mc}\p{Me}\p{Nd}\p{Nl}", RegexOptions.None, "=====Aa\u01C5\u02B0\u01BB\u0300\u0903\u04880\u16EE===", new (int, int, string)[] { (5, 10, "Aa\u01C5\u02B0\u01BB\u0300\u0903\u04880\u16EE") } }; yield return new object[] { engine, @"\p{No}\p{Zs}\p{Zl}\p{Zp}\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Pc}\p{Pd}", RegexOptions.None, "=====\u00B2 \u2028\u2029\0\u0600\uD800\uE000_\u002D===", new (int, int, string)[] { (5, 10, "\u00B2 \u2028\u2029\0\u0600\uD800\uE000_\u002D") } }; yield return new object[] { engine, @"\p{Ps}\p{Pe}\p{Pi}\p{Pf}\p{Po}\p{Sm}\p{Sc}\p{Sk}\p{So}\p{Cn}", RegexOptions.None, "=====()\xAB\xBB!+$^\xA6\u0378===", new (int, int, string)[] { (5, 10, "()\xAB\xBB!+$^\xA6\u0378") } }; yield return new object[] { engine, @"\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Mn}\p{Mc}\p{Me}\p{Nd}\p{Nl}\p{No}\p{Zs}\p{Zl}\p{Zp}\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Pc}\p{Pd}\p{Ps}\p{Pe}\p{Pi}\p{Pf}\p{Po}\p{Sm}\p{Sc}\p{Sk}\p{So}\p{Cn}", RegexOptions.None, "=====Aa\u01C5\u02B0\u01BB\u0300\u0903\u04880\u16EE\xB2 \u2028\u2029\0\u0600\uD800\uE000_\x2D()\xAB\xBB!+$^\xA6\u0378===", new (int, int, string)[] { (5, 30, "Aa\u01C5\u02B0\u01BB\u0300\u0903\u04880\u16EE\xB2 \u2028\u2029\0\u0600\uD800\uE000_\x2D()\xAB\xBB!+$^\xA6\u0378") } }; // Case insensitive cases by using ?i and some non-ASCII characters like Kelvin sign and applying ?i over negated character classes yield return new object[] { engine, "(?i:[a-d\u00D5]+k*)", RegexOptions.None, "xyxaB\u00F5c\u212AKAyy", new (int, int, string)[] { (3, 6, "aB\u00F5c\u212AK"), (9, 1, "A") } }; yield return new object[] { engine, "(?i:[a-d]+)", RegexOptions.None, "xyxaBcyy", new (int, int, string)[] { (3, 3, "aBc") } }; yield return new object[] { engine, "(?i:[\0-@B-\uFFFF]+)", RegexOptions.None, "xaAaAy", new (int, int, string)[] { (0, 6, "xaAaAy") } }; // this is the same as .+ yield return new object[] { engine, "(?i:[\0-ac-\uFFFF])", RegexOptions.None, "b", new (int, int, string)[] { (0, 1, "b") } }; yield return new object[] { engine, "(?i:[\0-PR-\uFFFF])", RegexOptions.None, "Q", new (int, int, string)[] { (0, 1, "Q") } }; yield return new object[] { engine, "(?i:[\0-pr-\uFFFF])", RegexOptions.None, "q", new (int, int, string)[] { (0, 1, "q") } }; yield return new object[] { engine, "(?i:[^a])", RegexOptions.None, "aAaA", null }; // this correponds to not{a,A} yield return new object[] { engine, "(?i:[\0-\uFFFF-[A]])", RegexOptions.None, "aAaA", null }; // this correponds to not{a,A} yield return new object[] { engine, "(?i:[^Q])", RegexOptions.None, "q", null }; yield return new object[] { engine, "(?i:[^b])", RegexOptions.None, "b", null }; // Use of anchors yield return new object[] { engine, @"\b\w+nn\b", RegexOptions.None, "both Anne and Ann are names that contain nn", new (int, int, string)[] { (14, 3, "Ann") } }; yield return new object[] { engine, @"\B x", RegexOptions.None, " xx", new (int, int, string)[] { (0, 2, " x") } }; yield return new object[] { engine, @"\bxx\b", RegexOptions.None, " zxx:xx", new (int, int, string)[] { (5, 2, "xx") } }; yield return new object[] { engine, @"^abc*\B", RegexOptions.None | RegexOptions.Multiline, "\nabcc \nabcccd\n", new (int, int, string)[] { (1, 3, "abc"), (7, 5, "abccc") } }; yield return new object[] { engine, "^abc", RegexOptions.None, "abcccc", new (int, int, string)[] { (0, 3, "abc") } }; yield return new object[] { engine, "^abc", RegexOptions.None, "aabcccc", null }; yield return new object[] { engine, "abc$", RegexOptions.None, "aabcccc", null }; yield return new object[] { engine, @"abc\z", RegexOptions.None, "aabc\n", null }; yield return new object[] { engine, @"abc\Z", RegexOptions.None, "aabc\n", new (int, int, string)[] { (1, 3, "abc") } }; yield return new object[] { engine, "abc$", RegexOptions.None, "aabc\nabc", new (int, int, string)[] { (5, 3, "abc") } }; yield return new object[] { engine, "abc$", RegexOptions.None | RegexOptions.Multiline, "aabc\nabc", new (int, int, string)[] { (1, 3, "abc"), (5, 3, "abc") } }; yield return new object[] { engine, @"a\bb", RegexOptions.None, "ab", null }; yield return new object[] { engine, @"a\Bb", RegexOptions.None, "ab", new (int, int, string)[] { (0, 2, "ab") } }; yield return new object[] { engine, @"(a\Bb|a\bb)", RegexOptions.None, "ab", new (int, int, string)[] { (0, 2, "ab") } }; yield return new object[] { engine, @"a$", RegexOptions.None | RegexOptions.Multiline, "b\na", new (int, int, string)[] { (2, 1, "a") } }; // Various loop constructs yield return new object[] { engine, "a[bcd]{4,5}(.)", RegexOptions.None, "acdbcdbe", new (int, int, string)[] { (0, 7, "acdbcdb") } }; yield return new object[] { engine, "a[bcd]{4,5}?(.)", RegexOptions.None, "acdbcdbe", new (int, int, string)[] { (0, 6, "acdbcd") } }; yield return new object[] { engine, "(x{3})+", RegexOptions.None, "abcxxxxxxxxacacaca", new (int, int, string)[] { (3, 6, "xxxxxx") } }; yield return new object[] { engine, "(x{3})+?", RegexOptions.None, "abcxxxxxxxxacacaca", new (int, int, string)[] { (3, 3, "xxx"), (6, 3, "xxx") } }; yield return new object[] { engine, "a[0-9]+0", RegexOptions.None, "ababca123000xyz", new (int, int, string)[] { (5, 7, "a123000") } }; yield return new object[] { engine, "a[0-9]+?0", RegexOptions.None, "ababca123000xyz", new (int, int, string)[] { (5, 5, "a1230") } }; // Mixed lazy/eager loop yield return new object[] { engine, "a[0-9]+?0|b[0-9]+0", RegexOptions.None, "ababca123000xyzababcb123000xyz", new (int, int, string)[] { (5, 5, "a1230"), (20, 7, "b123000") } }; // Loops around alternations yield return new object[] { engine, "^(?:aaa|aa)*$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; yield return new object[] { engine, "^(?:aaa|aa)*?$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; yield return new object[] { engine, "^(?:aaa|aa){1,5}$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; yield return new object[] { engine, "^(?:aaa|aa){1,5}?$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; yield return new object[] { engine, "^(?:aaa|aa){4}$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; yield return new object[] { engine, "^(?:aaa|aa){4}?$", RegexOptions.None, "aaaaaaaa", new (int, int, string)[] { (0, 8, "aaaaaaaa") } }; // Mostly empty matches using unusual regexes consisting mostly of anchors only yield return new object[] { engine, "^", RegexOptions.None, "", new (int, int, string)[] { (0, 0, "") } }; yield return new object[] { engine, "$", RegexOptions.None, "", new (int, int, string)[] { (0, 0, "") } }; yield return new object[] { engine, "^$", RegexOptions.None, "", new (int, int, string)[] { (0, 0, "") } }; yield return new object[] { engine, "$^", RegexOptions.None, "", new (int, int, string)[] { (0, 0, "") } }; yield return new object[] { engine, "$^$$^^$^$", RegexOptions.None, "", new (int, int, string)[] { (0, 0, "") } }; yield return new object[] { engine, "a*", RegexOptions.None, "bbb", new (int, int, string)[] { (0, 0, ""), (1, 0, ""), (2, 0, ""), (3, 0, "") } }; yield return new object[] { engine, "a*", RegexOptions.None, "baaabb", new (int, int, string)[] { (0, 0, ""), (1, 3, "aaa"), (4, 0, ""), (5, 0, ""), (6, 0, "") } }; yield return new object[] { engine, @"\b", RegexOptions.None, "hello--world", new (int, int, string)[] { (0, 0, ""), (5, 0, ""), (7, 0, ""), (12, 0, "") } }; yield return new object[] { engine, @"\B", RegexOptions.None, "hello--world", new (int, int, string)[] { (1, 0, ""), (2, 0, ""), (3, 0, ""), (4, 0, ""), (6, 0, ""), (8, 0, ""), (9, 0, ""), (10, 0, ""), (11, 0, "") } }; // Involving many different characters in the same regex yield return new object[] { engine, @"(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>:;@)+", RegexOptions.None, "=====abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>:;@abcdefg======", new (int, int, string)[] { (5, 67, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>:;@") } }; //this will need a total of 2x70 + 2 parts in the partition of NonBacktracking string pattern_orig = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>:;&@%!"; string pattern_WL = new String(Array.ConvertAll(pattern_orig.ToCharArray(), c => (char)((int)c + 0xFF00 - 32))); string pattern = "(" + pattern_orig + "===" + pattern_WL + ")+"; string input = "=====" + pattern_orig + "===" + pattern_WL + pattern_orig + "===" + pattern_WL + "===" + pattern_orig + "===" + pattern_orig; int length = 2 * (pattern_orig.Length + 3 + pattern_WL.Length); yield return new object[] { engine, pattern, RegexOptions.None, input, new (int, int, string)[]{(5, length, input.Substring(5, length)) } }; } } /// <summary> /// Test all top level matches for given pattern and options. /// </summary> [Theory] [MemberData(nameof(AllMatches_TestData))] public async Task AllMatches(RegexEngine engine, string pattern, RegexOptions options, string input, (int, int, string)[] matches) { Regex re = await RegexHelpers.GetRegexAsync(engine, pattern, options); Match m = re.Match(input); if (matches == null) { Assert.False(m.Success); } else { int i = 0; do { Assert.True(m.Success); Assert.True(i < matches.Length); Assert.Equal(matches[i].Item1, m.Index); Assert.Equal(matches[i].Item2, m.Length); Assert.Equal(matches[i++].Item3, m.Value); m = m.NextMatch(); } while (m.Success); Assert.Equal(matches.Length, i); } } [Theory] [InlineData(@"\w")] [InlineData(@"\s")] [InlineData(@"\d")] public async Task StandardCharSets_SameMeaningAcrossAllEngines(string singleCharPattern) { var regexes = new List<Regex>(); foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { regexes.Add(await RegexHelpers.GetRegexAsync(engine, singleCharPattern)); } if (regexes.Count < 2) { return; } for (int c = '\0'; c <= '\uFFFF'; c++) { string s = ((char)c).ToString(); bool baseline = regexes[0].IsMatch(s); for (int i = 1; i < regexes.Count; i++) { VerifyIsMatch(regexes[i], s, baseline, Regex.InfiniteMatchTimeout); } } } private static void VerifyIsMatchThrows<T>(Regex? r, string input, TimeSpan timeout, string? pattern = null, RegexOptions options = RegexOptions.None) where T : Exception { if (r == null) { Assert.Throws<T>(() => timeout == Regex.InfiniteMatchTimeout ? Regex.IsMatch(input, pattern, options) : Regex.IsMatch(input, pattern, options, timeout)); #if NET7_0_OR_GREATER Assert.Throws<T>(() => timeout == Regex.InfiniteMatchTimeout ? Regex.IsMatch(input.AsSpan(), pattern, options) : Regex.IsMatch(input.AsSpan(), pattern, options, timeout)); #endif } else { Assert.Throws<T>(() => r.IsMatch(input)); #if NET7_0_OR_GREATER Assert.Throws<T>(() => r.IsMatch(input.AsSpan())); #endif } } private static void VerifyIsMatch(Regex? r, string input, bool expected, TimeSpan timeout, string? pattern = null, RegexOptions options = RegexOptions.None) { if (r == null) { Assert.Equal(expected, timeout == Regex.InfiniteMatchTimeout ? Regex.IsMatch(input, pattern, options) : Regex.IsMatch(input, pattern, options, timeout)); if (options == RegexOptions.None) { Assert.Equal(expected, Regex.IsMatch(input, pattern)); } #if NET7_0_OR_GREATER Assert.Equal(expected, timeout == Regex.InfiniteMatchTimeout ? Regex.IsMatch(input.AsSpan(), pattern, options) : Regex.IsMatch(input.AsSpan(), pattern, options, timeout)); if (options == RegexOptions.None) { Assert.Equal(expected, Regex.IsMatch(input.AsSpan(), pattern)); } #endif } else { Assert.Equal(expected, r.IsMatch(input)); #if NET7_0_OR_GREATER Assert.Equal(expected, r.IsMatch(input.AsSpan())); #endif } } public static IEnumerable<object[]> Match_DisjunctionOverCounting_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, "a[abc]{0,10}", "a[abc]{0,3}", "xxxabbbbbbbyyy", true, "abbbbbbb" }; yield return new object[] { engine, "a[abc]{0,10}?", "a[abc]{0,3}?", "xxxabbbbbbbyyy", true, "a" }; } } [Theory] [MemberData(nameof(Match_DisjunctionOverCounting_TestData))] public async Task Match_DisjunctionOverCounting(RegexEngine engine, string disjunct1, string disjunct2, string input, bool success, string match) { Regex re = await RegexHelpers.GetRegexAsync(engine, disjunct1 + "|" + disjunct2); Match m = re.Match(input); Assert.Equal(success, m.Success); Assert.Equal(match, m.Value); } public static IEnumerable<object[]> MatchAmbiguousRegexes_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, "(a|ab|c|bcd){0,}d*", "ababcd", (0, 1) }; yield return new object[] { engine, "(a|ab|c|bcd){0,10}d*", "ababcd", (0, 1) }; yield return new object[] { engine, "(a|ab|c|bcd)*d*", "ababcd", (0, 1) }; yield return new object[] { engine, @"(the)\s*([12][0-9]|3[01]|0?[1-9])", "it is the 10:00 time", (6, 6) }; yield return new object[] { engine, "(ab|a|bcd|c){0,}d*", "ababcd", (0, 6) }; yield return new object[] { engine, "(ab|a|bcd|c){0,10}d*", "ababcd", (0, 6) }; yield return new object[] { engine, "(ab|a|bcd|c)*d*", "ababcd", (0, 6) }; yield return new object[] { engine, @"(the)\s*(0?[1-9]|[12][0-9]|3[01])", "it is the 10:00 time", (6, 5) }; } } [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Doesn't support NonBacktracking")] [MemberData(nameof(MatchAmbiguousRegexes_TestData))] public async Task MatchAmbiguousRegexes(RegexEngine engine, string pattern, string input, (int,int) expected_match) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern); var match = r.Match(input); Assert.Equal(expected_match.Item1, match.Index); Assert.Equal(expected_match.Item2, match.Length); } public static IEnumerable<object[]> UseRegexConcurrently_ThreadSafe_Success_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, Timeout.InfiniteTimeSpan }; yield return new object[] { engine, TimeSpan.FromMinutes(1) }; } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [OuterLoop("Takes several seconds")] [MemberData(nameof(UseRegexConcurrently_ThreadSafe_Success_MemberData))] public async Task UseRegexConcurrently_ThreadSafe_Success(RegexEngine engine, TimeSpan timeout) { const string Input = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Aenean nec lorem. In porttitor. abcdefghijklmnx Donec laoreet nonummy augue. Suspendisse dui purus, scelerisque at, vulputate vitae, pretium mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut nonummy. Fusce aliquet pede non pede. Suspendisse dapibus lorem pellentesque magna. Integer nulla. Donec blandit feugiat ligula. Donec hendrerit, felis et imperdiet euismod, purus ipsum pretium metus, in lacinia nulla nisl eget sapien. Donec ut est in lectus consequat consequat. Etiam eget dui. Aliquam erat volutpat. Sed at lorem in nunc porta tristique. Proin nec augue. Quisque aliquam tempor magna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nunc ac magna. Maecenas odio dolor, vulputate vel, auctor ac, accumsan id, felis. Pellentesque cursus sagittis felis. Pellentesque porttitor, velit lacinia egestas auctor, diam eros tempus arcu, nec vulputate augue magna vel risus.nmlkjihgfedcbax"; const int Trials = 100; const int IterationsPerTask = 10; using var b = new Barrier(Environment.ProcessorCount); for (int trial = 0; trial < Trials; trial++) { Regex r = await RegexHelpers.GetRegexAsync(engine, "[a-q][^u-z]{13}x", RegexOptions.None, timeout); Task.WaitAll(Enumerable.Range(0, b.ParticipantCount).Select(_ => Task.Factory.StartNew(() => { b.SignalAndWait(); for (int i = 0; i < IterationsPerTask; i++) { Match m = r.Match(Input); Assert.NotNull(m); Assert.True(m.Success); Assert.Equal("abcdefghijklmnx", m.Value); m = m.NextMatch(); Assert.NotNull(m); Assert.True(m.Success); Assert.Equal("nmlkjihgfedcbax", m.Value); m = m.NextMatch(); Assert.NotNull(m); Assert.False(m.Success); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray()); } } [Theory] [MemberData(nameof(MatchWordsInAnchoredRegexes_TestData))] public async Task MatchWordsInAnchoredRegexes(RegexEngine engine, RegexOptions options, string pattern, string input, (int, int)[] matches) { // The aim of these test is to test corner cases of matches involving anchors // For NonBacktracking these tests are meant to // cover most contexts in _nullabilityForContext in SymbolicRegexNode Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); MatchCollection ms = r.Matches(input); Assert.Equal(matches.Length, ms.Count); for (int i = 0; i < matches.Length; i++) { Assert.Equal(ms[i].Index, matches[i].Item1); Assert.Equal(ms[i].Length, matches[i].Item2); } } public static IEnumerable<object[]> MatchWordsInAnchoredRegexes_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, RegexOptions.None, @"\b\w{10,}\b", "this is a complicated word in a\nnontrivial sentence", new (int, int)[] { (10, 11), (32, 10) } }; yield return new object[] { engine, RegexOptions.Multiline, @"^\w{10,}\b", "this is a\ncomplicated word in a\nnontrivial sentence", new (int, int)[] { (10, 11), (32, 10) } }; yield return new object[] { engine, RegexOptions.None, @"\b\d{1,2}\/\d{1,2}\/\d{2,4}\b", "date 10/12/1966 and 10/12/66 are the same", new (int, int)[] { (5, 10), (20, 8) } }; yield return new object[] { engine, RegexOptions.Multiline, @"\b\d{1,2}\/\d{1,2}\/\d{2,4}$", "date 10/12/1966\nand 10/12/66\nare the same", new (int, int)[] { (5, 10), (20, 8) } }; } } } }
1
dotnet/runtime
66,321
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug
Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
stephentoub
2022-03-08T01:37:40Z
2022-03-08T19:24:48Z
446a0d610d4479fa9ba58ec14a89132a18ed33c4
b6c5a12cfa92e06734286bd991e7cca87ded1e24
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug. Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
./src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/RegexGeneratorParserTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using Xunit; namespace System.Text.RegularExpressions.Tests { // Tests don't actually use reflection emit, but they do generate assembly via Roslyn in-memory at run time and expect it to be JIT'd. // The tests also use typeof(object).Assembly.Location, which returns an empty string on wasm. [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported), nameof(PlatformDetection.IsNotMobile), nameof(PlatformDetection.IsNotBrowser))] public class RegexGeneratorParserTests { [Fact] public async Task Diagnostic_MultipleAttributes() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] [RegexGenerator(""abc"")] private static partial Regex MultipleAttributes(); } "); Assert.Equal("SYSLIB1041", Assert.Single(diagnostics).Id); } public static IEnumerable<object[]> Diagnostic_MalformedCtor_MemberData() { const string Pre = "[RegexGenerator"; const string Post = "]"; const string Middle = "\"abc\", RegexOptions.None, -1, \"extra\""; foreach (bool withParens in new[] { false, true }) { string preParen = withParens ? "(" : ""; string postParen = withParens ? ")" : ""; for (int i = 0; i < Middle.Length; i++) { yield return new object[] { Pre + preParen + Middle.Substring(0, i) + postParen }; yield return new object[] { Pre + preParen + Middle.Substring(0, i) + postParen + Post }; } } } [Theory] [MemberData(nameof(Diagnostic_MalformedCtor_MemberData))] public async Task Diagnostic_MalformedCtor(string attribute) { // Validate the generator doesn't crash with an incomplete attribute IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ {attribute} private static partial Regex MultipleAttributes(); }} "); if (diagnostics.Count != 0) { Assert.Contains(Assert.Single(diagnostics).Id, new[] { "SYSLIB1040", "SYSLIB1042" }); } } [Theory] [InlineData("null")] [InlineData("\"ab[]\"")] public async Task Diagnostic_InvalidRegexPattern(string pattern) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator({pattern})] private static partial Regex InvalidPattern(); }} "); Assert.Equal("SYSLIB1042", Assert.Single(diagnostics).Id); } [Theory] [InlineData(0x800)] public async Task Diagnostic_InvalidRegexOptions(int options) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@$" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", (RegexOptions){options})] private static partial Regex InvalidPattern(); }} "); Assert.Equal("SYSLIB1042", Assert.Single(diagnostics).Id); } [Theory] [InlineData(-2)] [InlineData(0)] public async Task Diagnostic_InvalidRegexTimeout(int matchTimeout) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@$" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", RegexOptions.None, {matchTimeout.ToString(CultureInfo.InvariantCulture)})] private static partial Regex InvalidPattern(); }} "); Assert.Equal("SYSLIB1042", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustReturnRegex() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial int MethodMustReturnRegex(); } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustNotBeGeneric() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex MethodMustNotBeGeneric<T>(); } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustBeParameterless() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex MethodMustBeParameterless(int i); } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustBePartial() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static Regex MethodMustBePartial() => null; } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Theory] [InlineData(LanguageVersion.CSharp9)] [InlineData(LanguageVersion.CSharp10)] public async Task Diagnostic_InvalidLangVersion(LanguageVersion version) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex InvalidLangVersion(); } ", langVersion: version); Assert.Equal("SYSLIB1044", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_NonBacktracking_LimitedSupport() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"", RegexOptions.NonBacktracking)] private static partial Regex RightToLeftNotSupported(); } "); Assert.Equal("SYSLIB1045", Assert.Single(diagnostics).Id); } [Fact] public async Task Valid_ClassWithoutNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } ", compile: true)); } [Theory] [InlineData("RegexOptions.None")] [InlineData("RegexOptions.Compiled")] [InlineData("RegexOptions.IgnoreCase | RegexOptions.CultureInvariant")] public async Task Valid_PatternOptions(string options) { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", {options})] private static partial Regex Valid(); }} ", compile: true)); } [Theory] [InlineData("-1")] [InlineData("1")] [InlineData("1_000")] public async Task Valid_PatternOptionsTimeout(string timeout) { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", RegexOptions.None, {timeout})] private static partial Regex Valid(); }} ", compile: true)); } [Fact] public async Task Valid_NamedArguments() { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(pattern: ""ab"", options: RegexOptions.None, matchTimeoutMilliseconds: -1)] private static partial Regex Valid(); }} ", compile: true)); } [Fact] public async Task Valid_ReorderedNamedArguments() { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(options: RegexOptions.None, matchTimeoutMilliseconds: -1, pattern: ""ab"")] private static partial Regex Valid1(); [RegexGenerator(matchTimeoutMilliseconds: -1, pattern: ""ab"", options: RegexOptions.None)] private static partial Regex Valid2(); }} ", compile: true)); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Valid_ClassWithNamespace(bool allowUnsafe) { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } ", compile: true, allowUnsafe: allowUnsafe)); } [Fact] public async Task Valid_ClassWithFileScopedNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A; partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } ", compile: true)); } [Fact] public async Task Valid_ClassWithNestedNamespaces() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { namespace B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } ", compile: true)); } [Fact] public async Task Valid_NestedClassWithoutNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } ", compile: true)); } [Fact] public async Task Valid_NestedClassWithNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { partial class B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } ", compile: true)); } [Fact] public async Task Valid_NestedClassWithFileScopedNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A; partial class B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } ", compile: true)); } [Fact] public async Task Valid_NestedClassesWithNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { public partial class B { internal partial class C { protected internal partial class D { private protected partial class E { private partial class F { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } } } } ", compile: true)); } [Fact] public async Task Valid_NullableRegex() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" #nullable enable using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex? Valid(); } ", compile: true)); } [Fact] public async Task Valid_ClassWithGenericConstraints() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using D; using System.Text.RegularExpressions; namespace A { public partial class B<U> { private partial class C<T> where T : IBlah { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } namespace D { internal interface IBlah { } } ", compile: true)); } public static IEnumerable<object[]> Valid_Modifiers_MemberData() { foreach (string type in new[] { "class", "struct", "record", "record struct", "record class", "interface" }) { string[] typeModifiers = type switch { "class" => new[] { "", "public", "public sealed", "internal abstract", "internal static" }, _ => new[] { "", "public", "internal" } }; foreach (string typeModifier in typeModifiers) { foreach (bool instance in typeModifier.Contains("static") ? new[] { false } : new[] { false, true }) { string[] methodVisibilities = type switch { "class" when !typeModifier.Contains("sealed") && !typeModifier.Contains("static") => new[] { "public", "internal", "private protected", "protected internal", "private" }, _ => new[] { "public", "internal", "private" } }; foreach (string methodVisibility in methodVisibilities) { yield return new object[] { type, typeModifier, instance, methodVisibility }; } } } } } [Theory] [MemberData(nameof(Valid_Modifiers_MemberData))] public async Task Valid_Modifiers(string type, string typeModifier, bool instance, string methodVisibility) { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@$" using System.Text.RegularExpressions; {typeModifier} partial {type} C {{ [RegexGenerator(""ab"")] {methodVisibility} {(instance ? "" : "static")} partial Regex Valid(); }} ", compile: true)); } [Fact] public async Task Valid_MultiplRegexMethodsPerClass() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C1 { [RegexGenerator(""a"")] private static partial Regex A(); [RegexGenerator(""b"")] public static partial Regex B(); [RegexGenerator(""b"")] public static partial Regex C(); } partial class C2 { [RegexGenerator(""d"")] public static partial Regex D(); [RegexGenerator(""d"")] public static partial Regex E(); } ", compile: true)); } [Fact] public async Task Valid_NestedVaryingTypes() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; public partial class A { public partial record class B { public partial record struct C { public partial record D { public partial struct E { [RegexGenerator(""ab"")] public static partial Regex Valid(); } } } } } ", compile: true)); } [Fact] public async Task MultipleTypeDefinitions_DoesntBreakGeneration() { byte[] referencedAssembly = RegexGeneratorHelper.CreateAssemblyImage(@" namespace System.Text.RegularExpressions; [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class RegexGeneratorAttribute : Attribute { public RegexGeneratorAttribute(string pattern){} }", "TestAssembly"); Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""abc"")] private static partial Regex Valid(); }", compile: true, additionalRefs: new[] { MetadataReference.CreateFromImage(referencedAssembly) })); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using Xunit; namespace System.Text.RegularExpressions.Tests { // Tests don't actually use reflection emit, but they do generate assembly via Roslyn in-memory at run time and expect it to be JIT'd. // The tests also use typeof(object).Assembly.Location, which returns an empty string on wasm. [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported), nameof(PlatformDetection.IsNotMobile), nameof(PlatformDetection.IsNotBrowser))] public class RegexGeneratorParserTests { [Fact] public async Task Diagnostic_MultipleAttributes() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] [RegexGenerator(""abc"")] private static partial Regex MultipleAttributes(); } "); Assert.Equal("SYSLIB1041", Assert.Single(diagnostics).Id); } public static IEnumerable<object[]> Diagnostic_MalformedCtor_MemberData() { const string Pre = "[RegexGenerator"; const string Post = "]"; const string Middle = "\"abc\", RegexOptions.None, -1, \"extra\""; foreach (bool withParens in new[] { false, true }) { string preParen = withParens ? "(" : ""; string postParen = withParens ? ")" : ""; for (int i = 0; i < Middle.Length; i++) { yield return new object[] { Pre + preParen + Middle.Substring(0, i) + postParen }; yield return new object[] { Pre + preParen + Middle.Substring(0, i) + postParen + Post }; } } } [Theory] [MemberData(nameof(Diagnostic_MalformedCtor_MemberData))] public async Task Diagnostic_MalformedCtor(string attribute) { // Validate the generator doesn't crash with an incomplete attribute IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ {attribute} private static partial Regex MultipleAttributes(); }} "); if (diagnostics.Count != 0) { Assert.Contains(Assert.Single(diagnostics).Id, new[] { "SYSLIB1040", "SYSLIB1042" }); } } [Theory] [InlineData("null")] [InlineData("\"ab[]\"")] public async Task Diagnostic_InvalidRegexPattern(string pattern) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator({pattern})] private static partial Regex InvalidPattern(); }} "); Assert.Equal("SYSLIB1042", Assert.Single(diagnostics).Id); } [Theory] [InlineData(0x800)] public async Task Diagnostic_InvalidRegexOptions(int options) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@$" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", (RegexOptions){options})] private static partial Regex InvalidPattern(); }} "); Assert.Equal("SYSLIB1042", Assert.Single(diagnostics).Id); } [Theory] [InlineData(-2)] [InlineData(0)] public async Task Diagnostic_InvalidRegexTimeout(int matchTimeout) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@$" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", RegexOptions.None, {matchTimeout.ToString(CultureInfo.InvariantCulture)})] private static partial Regex InvalidPattern(); }} "); Assert.Equal("SYSLIB1042", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustReturnRegex() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial int MethodMustReturnRegex(); } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustNotBeGeneric() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex MethodMustNotBeGeneric<T>(); } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustBeParameterless() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex MethodMustBeParameterless(int i); } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_MethodMustBePartial() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static Regex MethodMustBePartial() => null; } "); Assert.Equal("SYSLIB1043", Assert.Single(diagnostics).Id); } [Theory] [InlineData(LanguageVersion.CSharp9)] [InlineData(LanguageVersion.CSharp10)] public async Task Diagnostic_InvalidLangVersion(LanguageVersion version) { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex InvalidLangVersion(); } ", langVersion: version); Assert.Equal("SYSLIB1044", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_NonBacktracking_LimitedSupport() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"", RegexOptions.NonBacktracking)] private static partial Regex RightToLeftNotSupported(); } "); Assert.Equal("SYSLIB1045", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_CustomRegexGeneratorAttribute_ZeroArgCtor() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator] private static partial Regex InvalidCtor(); } namespace System.Text.RegularExpressions { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class RegexGeneratorAttribute : Attribute { } } "); Assert.Equal("SYSLIB1040", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_CustomRegexGeneratorAttribute_FourArgCtor() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""a"", RegexOptions.None, -1, ""b""] private static partial Regex InvalidCtor(); } namespace System.Text.RegularExpressions { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class RegexGeneratorAttribute : Attribute { public RegexGeneratorAttribute(string pattern, RegexOptions options, int timeout, string somethingElse) { } } } "); Assert.Equal("SYSLIB1040", Assert.Single(diagnostics).Id); } [Fact] public async Task Valid_ClassWithoutNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } ", compile: true)); } [Theory] [InlineData("RegexOptions.None")] [InlineData("RegexOptions.Compiled")] [InlineData("RegexOptions.IgnoreCase | RegexOptions.CultureInvariant")] public async Task Valid_PatternOptions(string options) { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", {options})] private static partial Regex Valid(); }} ", compile: true)); } [Theory] [InlineData("-1")] [InlineData("1")] [InlineData("1_000")] public async Task Valid_PatternOptionsTimeout(string timeout) { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(""ab"", RegexOptions.None, {timeout})] private static partial Regex Valid(); }} ", compile: true)); } [Fact] public async Task Valid_NamedArguments() { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(pattern: ""ab"", options: RegexOptions.None, matchTimeoutMilliseconds: -1)] private static partial Regex Valid(); }} ", compile: true)); } [Fact] public async Task Valid_ReorderedNamedArguments() { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; partial class C {{ [RegexGenerator(options: RegexOptions.None, matchTimeoutMilliseconds: -1, pattern: ""ab"")] private static partial Regex Valid1(); [RegexGenerator(matchTimeoutMilliseconds: -1, pattern: ""ab"", options: RegexOptions.None)] private static partial Regex Valid2(); }} ", compile: true)); } [Fact] public async Task Valid_AdditionalAttributes() { Assert.Empty(await RegexGeneratorHelper.RunGenerator($@" using System.Text.RegularExpressions; using System.Diagnostics.CodeAnalysis; partial class C {{ [SuppressMessage(""CATEGORY1"", ""SOMEID1"")] [RegexGenerator(""abc"")] [SuppressMessage(""CATEGORY2"", ""SOMEID2"")] private static partial Regex AdditionalAttributes(); }} ", compile: true)); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Valid_ClassWithNamespace(bool allowUnsafe) { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } ", compile: true, allowUnsafe: allowUnsafe)); } [Fact] public async Task Valid_ClassWithFileScopedNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A; partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } ", compile: true)); } [Fact] public async Task Valid_ClassWithNestedNamespaces() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { namespace B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } ", compile: true)); } [Fact] public async Task Valid_NestedClassWithoutNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } ", compile: true)); } [Fact] public async Task Valid_NestedClassWithNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { partial class B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } ", compile: true)); } [Fact] public async Task Valid_NestedClassWithFileScopedNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A; partial class B { partial class C { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } ", compile: true)); } [Fact] public async Task Valid_NestedClassesWithNamespace() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; namespace A { public partial class B { internal partial class C { protected internal partial class D { private protected partial class E { private partial class F { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } } } } ", compile: true)); } [Fact] public async Task Valid_NullableRegex() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" #nullable enable using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"")] private static partial Regex? Valid(); } ", compile: true)); } [Fact] public async Task Valid_ClassWithGenericConstraints() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using D; using System.Text.RegularExpressions; namespace A { public partial class B<U> { private partial class C<T> where T : IBlah { [RegexGenerator(""ab"")] private static partial Regex Valid(); } } } namespace D { internal interface IBlah { } } ", compile: true)); } public static IEnumerable<object[]> Valid_Modifiers_MemberData() { foreach (string type in new[] { "class", "struct", "record", "record struct", "record class", "interface" }) { string[] typeModifiers = type switch { "class" => new[] { "", "public", "public sealed", "internal abstract", "internal static" }, _ => new[] { "", "public", "internal" } }; foreach (string typeModifier in typeModifiers) { foreach (bool instance in typeModifier.Contains("static") ? new[] { false } : new[] { false, true }) { string[] methodVisibilities = type switch { "class" when !typeModifier.Contains("sealed") && !typeModifier.Contains("static") => new[] { "public", "internal", "private protected", "protected internal", "private" }, _ => new[] { "public", "internal", "private" } }; foreach (string methodVisibility in methodVisibilities) { yield return new object[] { type, typeModifier, instance, methodVisibility }; } } } } } [Theory] [MemberData(nameof(Valid_Modifiers_MemberData))] public async Task Valid_Modifiers(string type, string typeModifier, bool instance, string methodVisibility) { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@$" using System.Text.RegularExpressions; {typeModifier} partial {type} C {{ [RegexGenerator(""ab"")] {methodVisibility} {(instance ? "" : "static")} partial Regex Valid(); }} ", compile: true)); } [Fact] public async Task Valid_MultiplRegexMethodsPerClass() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C1 { [RegexGenerator(""a"")] private static partial Regex A(); [RegexGenerator(""b"")] public static partial Regex B(); [RegexGenerator(""b"")] public static partial Regex C(); } partial class C2 { [RegexGenerator(""d"")] public static partial Regex D(); [RegexGenerator(""d"")] public static partial Regex E(); } ", compile: true)); } [Fact] public async Task Valid_NestedVaryingTypes() { Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; public partial class A { public partial record class B { public partial record struct C { public partial record D { public partial struct E { [RegexGenerator(""ab"")] public static partial Regex Valid(); } } } } } ", compile: true)); } [Fact] public async Task MultipleTypeDefinitions_DoesntBreakGeneration() { byte[] referencedAssembly = RegexGeneratorHelper.CreateAssemblyImage(@" namespace System.Text.RegularExpressions; [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class RegexGeneratorAttribute : Attribute { public RegexGeneratorAttribute(string pattern){} }", "TestAssembly"); Assert.Empty(await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""abc"")] private static partial Regex Valid(); }", compile: true, additionalRefs: new[] { MetadataReference.CreateFromImage(referencedAssembly) })); } } }
1
dotnet/runtime
66,321
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug
Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
stephentoub
2022-03-08T01:37:40Z
2022-03-08T19:24:48Z
446a0d610d4479fa9ba58ec14a89132a18ed33c4
b6c5a12cfa92e06734286bd991e7cca87ded1e24
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug. Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
./src/libraries/System.Threading.Overlapped/ref/System.Threading.Overlapped.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.Threading { [System.CLSCompliantAttribute(false)] public unsafe delegate void IOCompletionCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* pOVERLAP); public partial struct NativeOverlapped { public System.IntPtr EventHandle; public System.IntPtr InternalHigh; public System.IntPtr InternalLow; public int OffsetHigh; public int OffsetLow; } public partial class Overlapped { public Overlapped() { } [System.ObsoleteAttribute("This constructor is not 64-bit compatible and has been deprecated. Use the constructor that accepts an IntPtr for the event handle instead.")] public Overlapped(int offsetLo, int offsetHi, int hEvent, System.IAsyncResult? ar) { } public Overlapped(int offsetLo, int offsetHi, System.IntPtr hEvent, System.IAsyncResult? ar) { } public System.IAsyncResult? AsyncResult { get { throw null; } set { } } [System.ObsoleteAttribute("Overlapped.EventHandle is not 64-bit compatible and has been deprecated. Use EventHandleIntPtr instead.")] public int EventHandle { get { throw null; } set { } } public System.IntPtr EventHandleIntPtr { get { throw null; } set { } } public int OffsetHigh { get { throw null; } set { } } public int OffsetLow { get { throw null; } set { } } [System.CLSCompliantAttribute(false)] public unsafe static void Free(System.Threading.NativeOverlapped* nativeOverlappedPtr) { } [System.CLSCompliantAttribute(false)] [System.ObsoleteAttribute("This overload is not safe and has been deprecated. Use Pack(IOCompletionCallback?, object?) instead.")] public unsafe System.Threading.NativeOverlapped* Pack(System.Threading.IOCompletionCallback? iocb) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe System.Threading.NativeOverlapped* Pack(System.Threading.IOCompletionCallback? iocb, object? userData) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe static System.Threading.Overlapped Unpack(System.Threading.NativeOverlapped* nativeOverlappedPtr) { throw null; } [System.CLSCompliantAttribute(false)] [System.ObsoleteAttribute("This overload is not safe and has been deprecated. Use UnsafePack(IOCompletionCallback?, object?) instead.")] public unsafe System.Threading.NativeOverlapped* UnsafePack(System.Threading.IOCompletionCallback? iocb) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe System.Threading.NativeOverlapped* UnsafePack(System.Threading.IOCompletionCallback? iocb, object? userData) { throw null; } } public sealed partial class PreAllocatedOverlapped : System.IDisposable { [System.CLSCompliantAttribute(false)] public PreAllocatedOverlapped(System.Threading.IOCompletionCallback callback, object? state, object? pinData) { } public void Dispose() { } ~PreAllocatedOverlapped() { } [System.CLSCompliantAttribute(false)] public static System.Threading.PreAllocatedOverlapped UnsafeCreate(System.Threading.IOCompletionCallback callback, object? state, object? pinData) { throw null; } } public sealed partial class ThreadPoolBoundHandle : System.IDisposable { internal ThreadPoolBoundHandle() { } public System.Runtime.InteropServices.SafeHandle Handle { get { throw null; } } [System.CLSCompliantAttribute(false)] public unsafe System.Threading.NativeOverlapped* AllocateNativeOverlapped(System.Threading.IOCompletionCallback callback, object? state, object? pinData) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe System.Threading.NativeOverlapped* AllocateNativeOverlapped(System.Threading.PreAllocatedOverlapped preAllocated) { throw null; } public static System.Threading.ThreadPoolBoundHandle BindHandle(System.Runtime.InteropServices.SafeHandle handle) { throw null; } public void Dispose() { } [System.CLSCompliantAttribute(false)] public unsafe void FreeNativeOverlapped(System.Threading.NativeOverlapped* overlapped) { } [System.CLSCompliantAttribute(false)] public unsafe static object? GetNativeOverlappedState(System.Threading.NativeOverlapped* overlapped) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe System.Threading.NativeOverlapped* UnsafeAllocateNativeOverlapped(System.Threading.IOCompletionCallback callback, object? state, object? pinData) { 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.Threading { [System.CLSCompliantAttribute(false)] public unsafe delegate void IOCompletionCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* pOVERLAP); public partial struct NativeOverlapped { public System.IntPtr EventHandle; public System.IntPtr InternalHigh; public System.IntPtr InternalLow; public int OffsetHigh; public int OffsetLow; } public partial class Overlapped { public Overlapped() { } [System.ObsoleteAttribute("This constructor is not 64-bit compatible and has been deprecated. Use the constructor that accepts an IntPtr for the event handle instead.")] public Overlapped(int offsetLo, int offsetHi, int hEvent, System.IAsyncResult? ar) { } public Overlapped(int offsetLo, int offsetHi, System.IntPtr hEvent, System.IAsyncResult? ar) { } public System.IAsyncResult? AsyncResult { get { throw null; } set { } } [System.ObsoleteAttribute("Overlapped.EventHandle is not 64-bit compatible and has been deprecated. Use EventHandleIntPtr instead.")] public int EventHandle { get { throw null; } set { } } public System.IntPtr EventHandleIntPtr { get { throw null; } set { } } public int OffsetHigh { get { throw null; } set { } } public int OffsetLow { get { throw null; } set { } } [System.CLSCompliantAttribute(false)] public unsafe static void Free(System.Threading.NativeOverlapped* nativeOverlappedPtr) { } [System.CLSCompliantAttribute(false)] [System.ObsoleteAttribute("This overload is not safe and has been deprecated. Use Pack(IOCompletionCallback?, object?) instead.")] public unsafe System.Threading.NativeOverlapped* Pack(System.Threading.IOCompletionCallback? iocb) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe System.Threading.NativeOverlapped* Pack(System.Threading.IOCompletionCallback? iocb, object? userData) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe static System.Threading.Overlapped Unpack(System.Threading.NativeOverlapped* nativeOverlappedPtr) { throw null; } [System.CLSCompliantAttribute(false)] [System.ObsoleteAttribute("This overload is not safe and has been deprecated. Use UnsafePack(IOCompletionCallback?, object?) instead.")] public unsafe System.Threading.NativeOverlapped* UnsafePack(System.Threading.IOCompletionCallback? iocb) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe System.Threading.NativeOverlapped* UnsafePack(System.Threading.IOCompletionCallback? iocb, object? userData) { throw null; } } public sealed partial class PreAllocatedOverlapped : System.IDisposable { [System.CLSCompliantAttribute(false)] public PreAllocatedOverlapped(System.Threading.IOCompletionCallback callback, object? state, object? pinData) { } public void Dispose() { } ~PreAllocatedOverlapped() { } [System.CLSCompliantAttribute(false)] public static System.Threading.PreAllocatedOverlapped UnsafeCreate(System.Threading.IOCompletionCallback callback, object? state, object? pinData) { throw null; } } public sealed partial class ThreadPoolBoundHandle : System.IDisposable { internal ThreadPoolBoundHandle() { } public System.Runtime.InteropServices.SafeHandle Handle { get { throw null; } } [System.CLSCompliantAttribute(false)] public unsafe System.Threading.NativeOverlapped* AllocateNativeOverlapped(System.Threading.IOCompletionCallback callback, object? state, object? pinData) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe System.Threading.NativeOverlapped* AllocateNativeOverlapped(System.Threading.PreAllocatedOverlapped preAllocated) { throw null; } public static System.Threading.ThreadPoolBoundHandle BindHandle(System.Runtime.InteropServices.SafeHandle handle) { throw null; } public void Dispose() { } [System.CLSCompliantAttribute(false)] public unsafe void FreeNativeOverlapped(System.Threading.NativeOverlapped* overlapped) { } [System.CLSCompliantAttribute(false)] public unsafe static object? GetNativeOverlappedState(System.Threading.NativeOverlapped* overlapped) { throw null; } [System.CLSCompliantAttribute(false)] public unsafe System.Threading.NativeOverlapped* UnsafeAllocateNativeOverlapped(System.Threading.IOCompletionCallback callback, object? state, object? pinData) { throw null; } } }
-1
dotnet/runtime
66,321
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug
Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
stephentoub
2022-03-08T01:37:40Z
2022-03-08T19:24:48Z
446a0d610d4479fa9ba58ec14a89132a18ed33c4
b6c5a12cfa92e06734286bd991e7cca87ded1e24
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug. Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
./src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Loader; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Threading; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Xml.Serialization.Configuration; namespace System.Xml.Serialization { public struct XmlDeserializationEvents { private XmlNodeEventHandler? _onUnknownNode; private XmlAttributeEventHandler? _onUnknownAttribute; private XmlElementEventHandler? _onUnknownElement; private UnreferencedObjectEventHandler? _onUnreferencedObject; internal object? sender; public XmlNodeEventHandler? OnUnknownNode { get { return _onUnknownNode; } set { _onUnknownNode = value; } } public XmlAttributeEventHandler? OnUnknownAttribute { get { return _onUnknownAttribute; } set { _onUnknownAttribute = value; } } public XmlElementEventHandler? OnUnknownElement { get { return _onUnknownElement; } set { _onUnknownElement = value; } } public UnreferencedObjectEventHandler? OnUnreferencedObject { get { return _onUnreferencedObject; } set { _onUnreferencedObject = value; } } } public abstract class XmlSerializerImplementation { public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } } public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } } public virtual Hashtable ReadMethods { get { throw new NotSupportedException(); } } public virtual Hashtable WriteMethods { get { throw new NotSupportedException(); } } public virtual Hashtable TypedSerializers { get { throw new NotSupportedException(); } } public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); } public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); } } // This enum is intentionally kept outside of the XmlSerializer class since if it would be a subclass // of XmlSerializer, then any access to this enum would be treated by AOT compilers as access to the XmlSerializer // as well, which has a large static ctor which brings in a lot of code. So keeping the enum separate // makes sure that using just the enum itself doesn't bring in the whole of serialization code base. internal enum SerializationMode { CodeGenOnly, ReflectionOnly, ReflectionAsBackup, PreGenOnly } public class XmlSerializer { private static SerializationMode s_mode = SerializationMode.ReflectionAsBackup; internal static SerializationMode Mode { get => RuntimeFeature.IsDynamicCodeSupported ? s_mode : SerializationMode.ReflectionOnly; set => s_mode = value; } private static bool ReflectionMethodEnabled { get { return Mode == SerializationMode.ReflectionOnly || Mode == SerializationMode.ReflectionAsBackup; } } private TempAssembly? _tempAssembly; #pragma warning disable 0414 private bool _typedSerializer; #pragma warning restore 0414 private readonly Type? _primitiveType; private XmlMapping _mapping = null!; private XmlDeserializationEvents _events; internal string? DefaultNamespace; private Type? _rootType; private bool _isReflectionBasedSerializer; private static readonly TempAssemblyCache s_cache = new TempAssemblyCache(); private static volatile XmlSerializerNamespaces? s_defaultNamespaces; private static XmlSerializerNamespaces DefaultNamespaces { get { if (s_defaultNamespaces == null) { XmlSerializerNamespaces nss = new XmlSerializerNamespaces(); nss.AddInternal("xsi", XmlSchema.InstanceNamespace); nss.AddInternal("xsd", XmlSchema.Namespace); if (s_defaultNamespaces == null) { s_defaultNamespaces = nss; } } return s_defaultNamespaces; } } // Trimmer warning messages internal const string TrimSerializationWarning = "Members from serialized types may be trimmed if not referenced directly"; private const string TrimDeserializationWarning = "Members from deserialized types may be trimmed if not referenced directly"; private static readonly ContextAwareTables<Dictionary<XmlSerializerMappingKey, XmlSerializer>> s_xmlSerializerTable = new ContextAwareTables<Dictionary<XmlSerializerMappingKey, XmlSerializer>>(); protected XmlSerializer() { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) : this(type, overrides, extraTypes, root, defaultNamespace, null) { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type, XmlRootAttribute? root) : this(type, null, Type.EmptyTypes, root, null, null) { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type, Type[]? extraTypes) : this(type, null, extraTypes, null, null, null) { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type, XmlAttributeOverrides? overrides) : this(type, overrides, Type.EmptyTypes, null, null, null) { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(XmlTypeMapping xmlTypeMapping!!) { if (Mode != SerializationMode.ReflectionOnly) { _tempAssembly = GenerateTempAssembly(xmlTypeMapping); } _mapping = xmlTypeMapping; } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type) : this(type, (string?)null) { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type!!, string? defaultNamespace) { DefaultNamespace = defaultNamespace; _rootType = type; _mapping = GetKnownMapping(type, defaultNamespace)!; if (_mapping != null) { _primitiveType = type; return; } if (Mode == SerializationMode.ReflectionOnly) { return; } _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { lock (s_cache) { _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { XmlSerializerImplementation? contract = null; Assembly? assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract); if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { AssemblyName name = type.Assembly.GetName(); var serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace)!; } else { // we found the pre-generated assembly, now make sure that the assembly has the right serializer // try to avoid the reflection step, need to get ElementName, namespace and the Key form the type _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); _tempAssembly = new TempAssembly(new XmlMapping[] { _mapping }, assembly, contract); } } s_cache.Add(defaultNamespace, type, _tempAssembly); } } if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type!!, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace, string? location) { DefaultNamespace = defaultNamespace; _rootType = type; _mapping = GenerateXmlTypeMapping(type, overrides, extraTypes, root, defaultNamespace); if (Mode != SerializationMode.ReflectionOnly) { _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location); } } [RequiresUnreferencedCode("calls ImportTypeMapping")] private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) { XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) { for (int i = 0; i < extraTypes.Length; i++) importer.IncludeType(extraTypes[i]); } return importer.ImportTypeMapping(type, root, defaultNamespace); } [RequiresUnreferencedCode("creates TempAssembly")] internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping) { return GenerateTempAssembly(xmlMapping, null, null); } [RequiresUnreferencedCode("creates TempAssembly")] internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping, Type? type, string? defaultNamespace) { return GenerateTempAssembly(xmlMapping, type, defaultNamespace, null); } [RequiresUnreferencedCode("creates TempAssembly")] internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping!!, Type? type, string? defaultNamespace, string? location) { xmlMapping.CheckShallow(); if (xmlMapping.IsSoap) { return null; } return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type?[] { type }, defaultNamespace, location); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(TextWriter textWriter, object? o) { Serialize(textWriter, o, null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(TextWriter textWriter, object? o, XmlSerializerNamespaces? namespaces) { XmlWriter xmlWriter = XmlWriter.Create(textWriter); Serialize(xmlWriter, o, namespaces); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(Stream stream, object? o) { Serialize(stream, o, null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(Stream stream, object? o, XmlSerializerNamespaces? namespaces) { XmlWriter xmlWriter = XmlWriter.Create(stream); Serialize(xmlWriter, o, namespaces); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(XmlWriter xmlWriter, object? o) { Serialize(xmlWriter, o, null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces) { Serialize(xmlWriter, o, namespaces, null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { try { if (_primitiveType != null) { if (encodingStyle != null && encodingStyle.Length > 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } SerializePrimitive(xmlWriter, o, namespaces); } else if (ShouldUseReflectionBasedSerialization(_mapping) || _isReflectionBasedSerializer) { SerializeUsingReflection(xmlWriter, o, namespaces, encodingStyle, id); } else if (_tempAssembly == null || _typedSerializer) { // The contion for the block is never true, thus the block is never hit. XmlSerializationWriter writer = CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly); try { Serialize(o, writer); } finally { writer.Dispose(); } } else { _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); } } catch (Exception? e) { if (e is TargetInvocationException) e = e.InnerException; throw new InvalidOperationException(SR.XmlGenError, e); } xmlWriter.Flush(); } [RequiresUnreferencedCode("calls GetMapping")] private void SerializeUsingReflection(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { XmlMapping mapping = GetMapping(); var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); writer.WriteObject(o); } [RequiresUnreferencedCode("calls GenerateXmlTypeMapping")] private XmlMapping GetMapping() { if (_mapping == null || !_mapping.GenerateSerializer) { _mapping = GenerateXmlTypeMapping(_rootType!, null, null, null, DefaultNamespace); } return _mapping; } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(Stream stream) { XmlReader xmlReader = XmlReader.Create(stream, new XmlReaderSettings() { IgnoreWhitespace = true }); return Deserialize(xmlReader, null); } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(TextReader textReader) { XmlTextReader xmlReader = new XmlTextReader(textReader); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; xmlReader.Normalization = true; xmlReader.XmlResolver = null; return Deserialize(xmlReader, null); } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null); } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) { return Deserialize(xmlReader, null, events); } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(XmlReader xmlReader, string? encodingStyle) { return Deserialize(xmlReader, encodingStyle, _events); } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(XmlReader xmlReader, string? encodingStyle, XmlDeserializationEvents events) { events.sender = this; try { if (_primitiveType != null) { if (encodingStyle != null && encodingStyle.Length > 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } return DeserializePrimitive(xmlReader, events); } else if (ShouldUseReflectionBasedSerialization(_mapping) || _isReflectionBasedSerializer) { return DeserializeUsingReflection(xmlReader, encodingStyle, events); } else if (_tempAssembly == null || _typedSerializer) { XmlSerializationReader reader = CreateReader(); reader.Init(xmlReader, events, encodingStyle, _tempAssembly); try { return Deserialize(reader); } finally { reader.Dispose(); } } else { return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle); } } catch (Exception? e) { if (e is TargetInvocationException) e = e.InnerException; if (xmlReader is IXmlLineInfo) { IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader; throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e); } else { throw new InvalidOperationException(SR.XmlSerializeError, e); } } } [RequiresUnreferencedCode("calls GetMapping")] private object? DeserializeUsingReflection(XmlReader xmlReader, string? encodingStyle, XmlDeserializationEvents events) { XmlMapping mapping = GetMapping(); var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle); return reader.ReadObject(); } private static bool ShouldUseReflectionBasedSerialization(XmlMapping mapping) { return Mode == SerializationMode.ReflectionOnly || (mapping != null && mapping.IsSoap); } public virtual bool CanDeserialize(XmlReader xmlReader) { if (_primitiveType != null) { TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]!; return xmlReader.IsStartElement(typeDesc.DataType!.Name!, string.Empty); } else if (ShouldUseReflectionBasedSerialization(_mapping) || _isReflectionBasedSerializer) { // If we should use reflection, we will try to do reflection-based deserialization, without fallback. // Don't check xmlReader.IsStartElement to avoid having to duplicate SOAP deserialization logic here. // It is better to return an incorrect 'true', which will throw during Deserialize than to return an // incorrect 'false', and the caller won't even try to Deserialize when it would succeed. return true; } else if (_tempAssembly != null) { return _tempAssembly.CanRead(_mapping, xmlReader); } else { return false; } } [RequiresUnreferencedCode(TrimSerializationWarning)] public static XmlSerializer[] FromMappings(XmlMapping[]? mappings) { return FromMappings(mappings, (Type?)null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public static XmlSerializer[] FromMappings(XmlMapping[]? mappings, Type? type) { if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>(); bool anySoapMapping = false; foreach (var mapping in mappings) { if (mapping.IsSoap) { anySoapMapping = true; } } if ((anySoapMapping && ReflectionMethodEnabled) || Mode == SerializationMode.ReflectionOnly) { XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type); return serializers; } XmlSerializerImplementation? contract = null; Assembly? assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); TempAssembly? tempAssembly; if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { AssemblyName name = type!.Assembly.GetName(); string serializerName = Compiler.GetTempAssemblyName(name, null); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } if (XmlMapping.IsShallow(mappings)) { return Array.Empty<XmlSerializer>(); } else { if (type == null) { tempAssembly = new TempAssembly(mappings, new Type?[] { type }, null, null); XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; contract = tempAssembly.Contract; for (int i = 0; i < serializers.Length; i++) { serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key!]!; serializers[i].SetTempAssembly(tempAssembly, mappings[i]); } return serializers; } else { // Use XmlSerializer cache when the type is not null. return GetSerializersFromCache(mappings, type); } } } else { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) { serializers[i] = (XmlSerializer)contract!.TypedSerializers[mappings[i].Key!]!; TempAssembly.VerifyLoadContext(serializers[i]._rootType, type!.Assembly); } return serializers; } } private static XmlSerializer[] GetReflectionBasedSerializers(XmlMapping[] mappings, Type? type) { var serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) { serializers[i] = new XmlSerializer(); serializers[i]._rootType = type; serializers[i]._mapping = mappings[i]; serializers[i]._isReflectionBasedSerializer = true; } return serializers; } [RequiresUnreferencedCode("calls GenerateSerializerToStream")] [UnconditionalSuppressMessage("SingleFile", "IL3000: Avoid accessing Assembly file path when publishing as a single file", Justification = "Code is used on diagnostics so we fallback to print assembly.FullName if assembly.Location is empty")] internal static bool GenerateSerializer(Type[]? types, XmlMapping[] mappings, Stream stream) { if (types == null || types.Length == 0) return false; ArgumentNullException.ThrowIfNull(mappings); ArgumentNullException.ThrowIfNull(stream); if (XmlMapping.IsShallow(mappings)) { throw new InvalidOperationException(SR.XmlMelformMapping); } Assembly? assembly = null; for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, type.FullName)); } if (assembly == null) { assembly = type.Assembly; } else if (type.Assembly != assembly) { string? nameOrLocation = assembly.Location; if (nameOrLocation == string.Empty) nameOrLocation = assembly.FullName; throw new ArgumentException(SR.Format(SR.XmlPregenOrphanType, type.FullName, nameOrLocation), nameof(types)); } } return TempAssembly.GenerateSerializerToStream(mappings, types, null, assembly, new Hashtable(), stream); } [RequiresUnreferencedCode("calls Contract")] private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type) { XmlSerializer?[] serializers = new XmlSerializer?[mappings.Length]; Dictionary<XmlSerializerMappingKey, XmlSerializer>? typedMappingTable = null; AssemblyLoadContext? alc = AssemblyLoadContext.GetLoadContext(type.Assembly); typedMappingTable = s_xmlSerializerTable.GetOrCreateValue(type, () => new Dictionary<XmlSerializerMappingKey, XmlSerializer>()); lock (typedMappingTable) { var pendingKeys = new Dictionary<XmlSerializerMappingKey, int>(); for (int i = 0; i < mappings.Length; i++) { XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]); if (!typedMappingTable.TryGetValue(mappingKey, out serializers[i])) { pendingKeys.Add(mappingKey, i); } } if (pendingKeys.Count > 0) { XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count]; int index = 0; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { pendingMappings[index++] = mappingKey.Mapping; } TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null); XmlSerializerImplementation contract = tempAssembly.Contract; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { index = pendingKeys[mappingKey]; serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key!]!; serializers[index]!.SetTempAssembly(tempAssembly, mappingKey.Mapping); typedMappingTable[mappingKey] = serializers[index]!; } } } return serializers!; } [RequiresUnreferencedCode(TrimSerializationWarning)] public static XmlSerializer[] FromTypes(Type[]? types) { if (types == null) return Array.Empty<XmlSerializer>(); XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } return FromMappings(mappings); } public static string GetXmlSerializerAssemblyName(Type type) { return GetXmlSerializerAssemblyName(type, null); } public static string GetXmlSerializerAssemblyName(Type type!!, string? defaultNamespace) { return Compiler.GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace); } public event XmlNodeEventHandler UnknownNode { add { _events.OnUnknownNode += value; } remove { _events.OnUnknownNode -= value; } } public event XmlAttributeEventHandler UnknownAttribute { add { _events.OnUnknownAttribute += value; } remove { _events.OnUnknownAttribute -= value; } } public event XmlElementEventHandler UnknownElement { add { _events.OnUnknownElement += value; } remove { _events.OnUnknownElement -= value; } } public event UnreferencedObjectEventHandler UnreferencedObject { add { _events.OnUnreferencedObject += value; } remove { _events.OnUnreferencedObject -= value; } } protected virtual XmlSerializationReader CreateReader() { throw new NotImplementedException(); } protected virtual object Deserialize(XmlSerializationReader reader) { throw new NotImplementedException(); } protected virtual XmlSerializationWriter CreateWriter() { throw new NotImplementedException(); } protected virtual void Serialize(object? o, XmlSerializationWriter writer) { throw new NotImplementedException(); } internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) { _tempAssembly = tempAssembly; _mapping = mapping; _typedSerializer = true; } private static XmlTypeMapping? GetKnownMapping(Type type, string? ns) { if (ns != null && ns != string.Empty) return null; TypeDesc? typeDesc = (TypeDesc?)TypeScope.PrimtiveTypes[type]; if (typeDesc == null) return null; ElementAccessor element = new ElementAccessor(); element.Name = typeDesc.DataType!.Name; XmlTypeMapping mapping = new XmlTypeMapping(null, element); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null)); return mapping; } private void SerializePrimitive(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces) { XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter(); writer.Init(xmlWriter, namespaces, null, null, null); switch (Type.GetTypeCode(_primitiveType)) { case TypeCode.String: writer.Write_string(o); break; case TypeCode.Int32: writer.Write_int(o); break; case TypeCode.Boolean: writer.Write_boolean(o); break; case TypeCode.Int16: writer.Write_short(o); break; case TypeCode.Int64: writer.Write_long(o); break; case TypeCode.Single: writer.Write_float(o); break; case TypeCode.Double: writer.Write_double(o); break; case TypeCode.Decimal: writer.Write_decimal(o); break; case TypeCode.DateTime: writer.Write_dateTime(o); break; case TypeCode.Char: writer.Write_char(o); break; case TypeCode.Byte: writer.Write_unsignedByte(o); break; case TypeCode.SByte: writer.Write_byte(o); break; case TypeCode.UInt16: writer.Write_unsignedShort(o); break; case TypeCode.UInt32: writer.Write_unsignedInt(o); break; case TypeCode.UInt64: writer.Write_unsignedLong(o); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { writer.Write_QName(o); } else if (_primitiveType == typeof(byte[])) { writer.Write_base64Binary(o); } else if (_primitiveType == typeof(Guid)) { writer.Write_guid(o); } else if (_primitiveType == typeof(TimeSpan)) { writer.Write_TimeSpan(o); } else if (_primitiveType == typeof(DateTimeOffset)) { writer.Write_dateTimeOffset(o); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType!.FullName)); } break; } } private object? DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) { XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader(); reader.Init(xmlReader, events, null, null); object? o; switch (Type.GetTypeCode(_primitiveType)) { case TypeCode.String: o = reader.Read_string(); break; case TypeCode.Int32: o = reader.Read_int(); break; case TypeCode.Boolean: o = reader.Read_boolean(); break; case TypeCode.Int16: o = reader.Read_short(); break; case TypeCode.Int64: o = reader.Read_long(); break; case TypeCode.Single: o = reader.Read_float(); break; case TypeCode.Double: o = reader.Read_double(); break; case TypeCode.Decimal: o = reader.Read_decimal(); break; case TypeCode.DateTime: o = reader.Read_dateTime(); break; case TypeCode.Char: o = reader.Read_char(); break; case TypeCode.Byte: o = reader.Read_unsignedByte(); break; case TypeCode.SByte: o = reader.Read_byte(); break; case TypeCode.UInt16: o = reader.Read_unsignedShort(); break; case TypeCode.UInt32: o = reader.Read_unsignedInt(); break; case TypeCode.UInt64: o = reader.Read_unsignedLong(); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { o = reader.Read_QName(); } else if (_primitiveType == typeof(byte[])) { o = reader.Read_base64Binary(); } else if (_primitiveType == typeof(Guid)) { o = reader.Read_guid(); } else if (_primitiveType == typeof(TimeSpan)) { o = reader.Read_TimeSpan(); } else if (_primitiveType == typeof(DateTimeOffset)) { o = reader.Read_dateTimeOffset(); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType!.FullName)); } break; } return o; } private sealed class XmlSerializerMappingKey { public XmlMapping Mapping; public XmlSerializerMappingKey(XmlMapping mapping) { this.Mapping = mapping; } public override bool Equals([NotNullWhen(true)] object? obj) { XmlSerializerMappingKey? other = obj as XmlSerializerMappingKey; if (other == null) return false; if (this.Mapping.Key != other.Mapping.Key) return false; if (this.Mapping.ElementName != other.Mapping.ElementName) return false; if (this.Mapping.Namespace != other.Mapping.Namespace) return false; if (this.Mapping.IsSoap != other.Mapping.IsSoap) return false; return true; } public override int GetHashCode() { int hashCode = this.Mapping.IsSoap ? 0 : 1; if (this.Mapping.Key != null) hashCode ^= this.Mapping.Key.GetHashCode(); if (this.Mapping.ElementName != null) hashCode ^= this.Mapping.ElementName.GetHashCode(); if (this.Mapping.Namespace != null) hashCode ^= this.Mapping.Namespace.GetHashCode(); return hashCode; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Loader; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Threading; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Xml.Serialization.Configuration; namespace System.Xml.Serialization { public struct XmlDeserializationEvents { private XmlNodeEventHandler? _onUnknownNode; private XmlAttributeEventHandler? _onUnknownAttribute; private XmlElementEventHandler? _onUnknownElement; private UnreferencedObjectEventHandler? _onUnreferencedObject; internal object? sender; public XmlNodeEventHandler? OnUnknownNode { get { return _onUnknownNode; } set { _onUnknownNode = value; } } public XmlAttributeEventHandler? OnUnknownAttribute { get { return _onUnknownAttribute; } set { _onUnknownAttribute = value; } } public XmlElementEventHandler? OnUnknownElement { get { return _onUnknownElement; } set { _onUnknownElement = value; } } public UnreferencedObjectEventHandler? OnUnreferencedObject { get { return _onUnreferencedObject; } set { _onUnreferencedObject = value; } } } public abstract class XmlSerializerImplementation { public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } } public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } } public virtual Hashtable ReadMethods { get { throw new NotSupportedException(); } } public virtual Hashtable WriteMethods { get { throw new NotSupportedException(); } } public virtual Hashtable TypedSerializers { get { throw new NotSupportedException(); } } public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); } public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); } } // This enum is intentionally kept outside of the XmlSerializer class since if it would be a subclass // of XmlSerializer, then any access to this enum would be treated by AOT compilers as access to the XmlSerializer // as well, which has a large static ctor which brings in a lot of code. So keeping the enum separate // makes sure that using just the enum itself doesn't bring in the whole of serialization code base. internal enum SerializationMode { CodeGenOnly, ReflectionOnly, ReflectionAsBackup, PreGenOnly } public class XmlSerializer { private static SerializationMode s_mode = SerializationMode.ReflectionAsBackup; internal static SerializationMode Mode { get => RuntimeFeature.IsDynamicCodeSupported ? s_mode : SerializationMode.ReflectionOnly; set => s_mode = value; } private static bool ReflectionMethodEnabled { get { return Mode == SerializationMode.ReflectionOnly || Mode == SerializationMode.ReflectionAsBackup; } } private TempAssembly? _tempAssembly; #pragma warning disable 0414 private bool _typedSerializer; #pragma warning restore 0414 private readonly Type? _primitiveType; private XmlMapping _mapping = null!; private XmlDeserializationEvents _events; internal string? DefaultNamespace; private Type? _rootType; private bool _isReflectionBasedSerializer; private static readonly TempAssemblyCache s_cache = new TempAssemblyCache(); private static volatile XmlSerializerNamespaces? s_defaultNamespaces; private static XmlSerializerNamespaces DefaultNamespaces { get { if (s_defaultNamespaces == null) { XmlSerializerNamespaces nss = new XmlSerializerNamespaces(); nss.AddInternal("xsi", XmlSchema.InstanceNamespace); nss.AddInternal("xsd", XmlSchema.Namespace); if (s_defaultNamespaces == null) { s_defaultNamespaces = nss; } } return s_defaultNamespaces; } } // Trimmer warning messages internal const string TrimSerializationWarning = "Members from serialized types may be trimmed if not referenced directly"; private const string TrimDeserializationWarning = "Members from deserialized types may be trimmed if not referenced directly"; private static readonly ContextAwareTables<Dictionary<XmlSerializerMappingKey, XmlSerializer>> s_xmlSerializerTable = new ContextAwareTables<Dictionary<XmlSerializerMappingKey, XmlSerializer>>(); protected XmlSerializer() { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) : this(type, overrides, extraTypes, root, defaultNamespace, null) { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type, XmlRootAttribute? root) : this(type, null, Type.EmptyTypes, root, null, null) { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type, Type[]? extraTypes) : this(type, null, extraTypes, null, null, null) { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type, XmlAttributeOverrides? overrides) : this(type, overrides, Type.EmptyTypes, null, null, null) { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(XmlTypeMapping xmlTypeMapping!!) { if (Mode != SerializationMode.ReflectionOnly) { _tempAssembly = GenerateTempAssembly(xmlTypeMapping); } _mapping = xmlTypeMapping; } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type) : this(type, (string?)null) { } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type!!, string? defaultNamespace) { DefaultNamespace = defaultNamespace; _rootType = type; _mapping = GetKnownMapping(type, defaultNamespace)!; if (_mapping != null) { _primitiveType = type; return; } if (Mode == SerializationMode.ReflectionOnly) { return; } _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { lock (s_cache) { _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { XmlSerializerImplementation? contract = null; Assembly? assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract); if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { AssemblyName name = type.Assembly.GetName(); var serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace)!; } else { // we found the pre-generated assembly, now make sure that the assembly has the right serializer // try to avoid the reflection step, need to get ElementName, namespace and the Key form the type _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); _tempAssembly = new TempAssembly(new XmlMapping[] { _mapping }, assembly, contract); } } s_cache.Add(defaultNamespace, type, _tempAssembly); } } if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } } [RequiresUnreferencedCode(TrimSerializationWarning)] public XmlSerializer(Type type!!, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace, string? location) { DefaultNamespace = defaultNamespace; _rootType = type; _mapping = GenerateXmlTypeMapping(type, overrides, extraTypes, root, defaultNamespace); if (Mode != SerializationMode.ReflectionOnly) { _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location); } } [RequiresUnreferencedCode("calls ImportTypeMapping")] private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) { XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) { for (int i = 0; i < extraTypes.Length; i++) importer.IncludeType(extraTypes[i]); } return importer.ImportTypeMapping(type, root, defaultNamespace); } [RequiresUnreferencedCode("creates TempAssembly")] internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping) { return GenerateTempAssembly(xmlMapping, null, null); } [RequiresUnreferencedCode("creates TempAssembly")] internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping, Type? type, string? defaultNamespace) { return GenerateTempAssembly(xmlMapping, type, defaultNamespace, null); } [RequiresUnreferencedCode("creates TempAssembly")] internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping!!, Type? type, string? defaultNamespace, string? location) { xmlMapping.CheckShallow(); if (xmlMapping.IsSoap) { return null; } return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type?[] { type }, defaultNamespace, location); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(TextWriter textWriter, object? o) { Serialize(textWriter, o, null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(TextWriter textWriter, object? o, XmlSerializerNamespaces? namespaces) { XmlWriter xmlWriter = XmlWriter.Create(textWriter); Serialize(xmlWriter, o, namespaces); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(Stream stream, object? o) { Serialize(stream, o, null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(Stream stream, object? o, XmlSerializerNamespaces? namespaces) { XmlWriter xmlWriter = XmlWriter.Create(stream); Serialize(xmlWriter, o, namespaces); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(XmlWriter xmlWriter, object? o) { Serialize(xmlWriter, o, null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces) { Serialize(xmlWriter, o, namespaces, null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { try { if (_primitiveType != null) { if (encodingStyle != null && encodingStyle.Length > 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } SerializePrimitive(xmlWriter, o, namespaces); } else if (ShouldUseReflectionBasedSerialization(_mapping) || _isReflectionBasedSerializer) { SerializeUsingReflection(xmlWriter, o, namespaces, encodingStyle, id); } else if (_tempAssembly == null || _typedSerializer) { // The contion for the block is never true, thus the block is never hit. XmlSerializationWriter writer = CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly); try { Serialize(o, writer); } finally { writer.Dispose(); } } else { _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); } } catch (Exception? e) { if (e is TargetInvocationException) e = e.InnerException; throw new InvalidOperationException(SR.XmlGenError, e); } xmlWriter.Flush(); } [RequiresUnreferencedCode("calls GetMapping")] private void SerializeUsingReflection(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { XmlMapping mapping = GetMapping(); var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); writer.WriteObject(o); } [RequiresUnreferencedCode("calls GenerateXmlTypeMapping")] private XmlMapping GetMapping() { if (_mapping == null || !_mapping.GenerateSerializer) { _mapping = GenerateXmlTypeMapping(_rootType!, null, null, null, DefaultNamespace); } return _mapping; } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(Stream stream) { XmlReader xmlReader = XmlReader.Create(stream, new XmlReaderSettings() { IgnoreWhitespace = true }); return Deserialize(xmlReader, null); } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(TextReader textReader) { XmlTextReader xmlReader = new XmlTextReader(textReader); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; xmlReader.Normalization = true; xmlReader.XmlResolver = null; return Deserialize(xmlReader, null); } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null); } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) { return Deserialize(xmlReader, null, events); } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(XmlReader xmlReader, string? encodingStyle) { return Deserialize(xmlReader, encodingStyle, _events); } [RequiresUnreferencedCode(TrimDeserializationWarning)] public object? Deserialize(XmlReader xmlReader, string? encodingStyle, XmlDeserializationEvents events) { events.sender = this; try { if (_primitiveType != null) { if (encodingStyle != null && encodingStyle.Length > 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } return DeserializePrimitive(xmlReader, events); } else if (ShouldUseReflectionBasedSerialization(_mapping) || _isReflectionBasedSerializer) { return DeserializeUsingReflection(xmlReader, encodingStyle, events); } else if (_tempAssembly == null || _typedSerializer) { XmlSerializationReader reader = CreateReader(); reader.Init(xmlReader, events, encodingStyle, _tempAssembly); try { return Deserialize(reader); } finally { reader.Dispose(); } } else { return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle); } } catch (Exception? e) { if (e is TargetInvocationException) e = e.InnerException; if (xmlReader is IXmlLineInfo) { IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader; throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e); } else { throw new InvalidOperationException(SR.XmlSerializeError, e); } } } [RequiresUnreferencedCode("calls GetMapping")] private object? DeserializeUsingReflection(XmlReader xmlReader, string? encodingStyle, XmlDeserializationEvents events) { XmlMapping mapping = GetMapping(); var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle); return reader.ReadObject(); } private static bool ShouldUseReflectionBasedSerialization(XmlMapping mapping) { return Mode == SerializationMode.ReflectionOnly || (mapping != null && mapping.IsSoap); } public virtual bool CanDeserialize(XmlReader xmlReader) { if (_primitiveType != null) { TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]!; return xmlReader.IsStartElement(typeDesc.DataType!.Name!, string.Empty); } else if (ShouldUseReflectionBasedSerialization(_mapping) || _isReflectionBasedSerializer) { // If we should use reflection, we will try to do reflection-based deserialization, without fallback. // Don't check xmlReader.IsStartElement to avoid having to duplicate SOAP deserialization logic here. // It is better to return an incorrect 'true', which will throw during Deserialize than to return an // incorrect 'false', and the caller won't even try to Deserialize when it would succeed. return true; } else if (_tempAssembly != null) { return _tempAssembly.CanRead(_mapping, xmlReader); } else { return false; } } [RequiresUnreferencedCode(TrimSerializationWarning)] public static XmlSerializer[] FromMappings(XmlMapping[]? mappings) { return FromMappings(mappings, (Type?)null); } [RequiresUnreferencedCode(TrimSerializationWarning)] public static XmlSerializer[] FromMappings(XmlMapping[]? mappings, Type? type) { if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>(); bool anySoapMapping = false; foreach (var mapping in mappings) { if (mapping.IsSoap) { anySoapMapping = true; } } if ((anySoapMapping && ReflectionMethodEnabled) || Mode == SerializationMode.ReflectionOnly) { XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type); return serializers; } XmlSerializerImplementation? contract = null; Assembly? assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); TempAssembly? tempAssembly; if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { AssemblyName name = type!.Assembly.GetName(); string serializerName = Compiler.GetTempAssemblyName(name, null); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } if (XmlMapping.IsShallow(mappings)) { return Array.Empty<XmlSerializer>(); } else { if (type == null) { tempAssembly = new TempAssembly(mappings, new Type?[] { type }, null, null); XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; contract = tempAssembly.Contract; for (int i = 0; i < serializers.Length; i++) { serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key!]!; serializers[i].SetTempAssembly(tempAssembly, mappings[i]); } return serializers; } else { // Use XmlSerializer cache when the type is not null. return GetSerializersFromCache(mappings, type); } } } else { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) { serializers[i] = (XmlSerializer)contract!.TypedSerializers[mappings[i].Key!]!; TempAssembly.VerifyLoadContext(serializers[i]._rootType, type!.Assembly); } return serializers; } } private static XmlSerializer[] GetReflectionBasedSerializers(XmlMapping[] mappings, Type? type) { var serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) { serializers[i] = new XmlSerializer(); serializers[i]._rootType = type; serializers[i]._mapping = mappings[i]; serializers[i]._isReflectionBasedSerializer = true; } return serializers; } [RequiresUnreferencedCode("calls GenerateSerializerToStream")] [UnconditionalSuppressMessage("SingleFile", "IL3000: Avoid accessing Assembly file path when publishing as a single file", Justification = "Code is used on diagnostics so we fallback to print assembly.FullName if assembly.Location is empty")] internal static bool GenerateSerializer(Type[]? types, XmlMapping[] mappings, Stream stream) { if (types == null || types.Length == 0) return false; ArgumentNullException.ThrowIfNull(mappings); ArgumentNullException.ThrowIfNull(stream); if (XmlMapping.IsShallow(mappings)) { throw new InvalidOperationException(SR.XmlMelformMapping); } Assembly? assembly = null; for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, type.FullName)); } if (assembly == null) { assembly = type.Assembly; } else if (type.Assembly != assembly) { string? nameOrLocation = assembly.Location; if (nameOrLocation == string.Empty) nameOrLocation = assembly.FullName; throw new ArgumentException(SR.Format(SR.XmlPregenOrphanType, type.FullName, nameOrLocation), nameof(types)); } } return TempAssembly.GenerateSerializerToStream(mappings, types, null, assembly, new Hashtable(), stream); } [RequiresUnreferencedCode("calls Contract")] private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type) { XmlSerializer?[] serializers = new XmlSerializer?[mappings.Length]; Dictionary<XmlSerializerMappingKey, XmlSerializer>? typedMappingTable = null; AssemblyLoadContext? alc = AssemblyLoadContext.GetLoadContext(type.Assembly); typedMappingTable = s_xmlSerializerTable.GetOrCreateValue(type, () => new Dictionary<XmlSerializerMappingKey, XmlSerializer>()); lock (typedMappingTable) { var pendingKeys = new Dictionary<XmlSerializerMappingKey, int>(); for (int i = 0; i < mappings.Length; i++) { XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]); if (!typedMappingTable.TryGetValue(mappingKey, out serializers[i])) { pendingKeys.Add(mappingKey, i); } } if (pendingKeys.Count > 0) { XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count]; int index = 0; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { pendingMappings[index++] = mappingKey.Mapping; } TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null); XmlSerializerImplementation contract = tempAssembly.Contract; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { index = pendingKeys[mappingKey]; serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key!]!; serializers[index]!.SetTempAssembly(tempAssembly, mappingKey.Mapping); typedMappingTable[mappingKey] = serializers[index]!; } } } return serializers!; } [RequiresUnreferencedCode(TrimSerializationWarning)] public static XmlSerializer[] FromTypes(Type[]? types) { if (types == null) return Array.Empty<XmlSerializer>(); XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } return FromMappings(mappings); } public static string GetXmlSerializerAssemblyName(Type type) { return GetXmlSerializerAssemblyName(type, null); } public static string GetXmlSerializerAssemblyName(Type type!!, string? defaultNamespace) { return Compiler.GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace); } public event XmlNodeEventHandler UnknownNode { add { _events.OnUnknownNode += value; } remove { _events.OnUnknownNode -= value; } } public event XmlAttributeEventHandler UnknownAttribute { add { _events.OnUnknownAttribute += value; } remove { _events.OnUnknownAttribute -= value; } } public event XmlElementEventHandler UnknownElement { add { _events.OnUnknownElement += value; } remove { _events.OnUnknownElement -= value; } } public event UnreferencedObjectEventHandler UnreferencedObject { add { _events.OnUnreferencedObject += value; } remove { _events.OnUnreferencedObject -= value; } } protected virtual XmlSerializationReader CreateReader() { throw new NotImplementedException(); } protected virtual object Deserialize(XmlSerializationReader reader) { throw new NotImplementedException(); } protected virtual XmlSerializationWriter CreateWriter() { throw new NotImplementedException(); } protected virtual void Serialize(object? o, XmlSerializationWriter writer) { throw new NotImplementedException(); } internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) { _tempAssembly = tempAssembly; _mapping = mapping; _typedSerializer = true; } private static XmlTypeMapping? GetKnownMapping(Type type, string? ns) { if (ns != null && ns != string.Empty) return null; TypeDesc? typeDesc = (TypeDesc?)TypeScope.PrimtiveTypes[type]; if (typeDesc == null) return null; ElementAccessor element = new ElementAccessor(); element.Name = typeDesc.DataType!.Name; XmlTypeMapping mapping = new XmlTypeMapping(null, element); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null)); return mapping; } private void SerializePrimitive(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces) { XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter(); writer.Init(xmlWriter, namespaces, null, null, null); switch (Type.GetTypeCode(_primitiveType)) { case TypeCode.String: writer.Write_string(o); break; case TypeCode.Int32: writer.Write_int(o); break; case TypeCode.Boolean: writer.Write_boolean(o); break; case TypeCode.Int16: writer.Write_short(o); break; case TypeCode.Int64: writer.Write_long(o); break; case TypeCode.Single: writer.Write_float(o); break; case TypeCode.Double: writer.Write_double(o); break; case TypeCode.Decimal: writer.Write_decimal(o); break; case TypeCode.DateTime: writer.Write_dateTime(o); break; case TypeCode.Char: writer.Write_char(o); break; case TypeCode.Byte: writer.Write_unsignedByte(o); break; case TypeCode.SByte: writer.Write_byte(o); break; case TypeCode.UInt16: writer.Write_unsignedShort(o); break; case TypeCode.UInt32: writer.Write_unsignedInt(o); break; case TypeCode.UInt64: writer.Write_unsignedLong(o); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { writer.Write_QName(o); } else if (_primitiveType == typeof(byte[])) { writer.Write_base64Binary(o); } else if (_primitiveType == typeof(Guid)) { writer.Write_guid(o); } else if (_primitiveType == typeof(TimeSpan)) { writer.Write_TimeSpan(o); } else if (_primitiveType == typeof(DateTimeOffset)) { writer.Write_dateTimeOffset(o); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType!.FullName)); } break; } } private object? DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) { XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader(); reader.Init(xmlReader, events, null, null); object? o; switch (Type.GetTypeCode(_primitiveType)) { case TypeCode.String: o = reader.Read_string(); break; case TypeCode.Int32: o = reader.Read_int(); break; case TypeCode.Boolean: o = reader.Read_boolean(); break; case TypeCode.Int16: o = reader.Read_short(); break; case TypeCode.Int64: o = reader.Read_long(); break; case TypeCode.Single: o = reader.Read_float(); break; case TypeCode.Double: o = reader.Read_double(); break; case TypeCode.Decimal: o = reader.Read_decimal(); break; case TypeCode.DateTime: o = reader.Read_dateTime(); break; case TypeCode.Char: o = reader.Read_char(); break; case TypeCode.Byte: o = reader.Read_unsignedByte(); break; case TypeCode.SByte: o = reader.Read_byte(); break; case TypeCode.UInt16: o = reader.Read_unsignedShort(); break; case TypeCode.UInt32: o = reader.Read_unsignedInt(); break; case TypeCode.UInt64: o = reader.Read_unsignedLong(); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { o = reader.Read_QName(); } else if (_primitiveType == typeof(byte[])) { o = reader.Read_base64Binary(); } else if (_primitiveType == typeof(Guid)) { o = reader.Read_guid(); } else if (_primitiveType == typeof(TimeSpan)) { o = reader.Read_TimeSpan(); } else if (_primitiveType == typeof(DateTimeOffset)) { o = reader.Read_dateTimeOffset(); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType!.FullName)); } break; } return o; } private sealed class XmlSerializerMappingKey { public XmlMapping Mapping; public XmlSerializerMappingKey(XmlMapping mapping) { this.Mapping = mapping; } public override bool Equals([NotNullWhen(true)] object? obj) { XmlSerializerMappingKey? other = obj as XmlSerializerMappingKey; if (other == null) return false; if (this.Mapping.Key != other.Mapping.Key) return false; if (this.Mapping.ElementName != other.Mapping.ElementName) return false; if (this.Mapping.Namespace != other.Mapping.Namespace) return false; if (this.Mapping.IsSoap != other.Mapping.IsSoap) return false; return true; } public override int GetHashCode() { int hashCode = this.Mapping.IsSoap ? 0 : 1; if (this.Mapping.Key != null) hashCode ^= this.Mapping.Key.GetHashCode(); if (this.Mapping.ElementName != null) hashCode ^= this.Mapping.ElementName.GetHashCode(); if (this.Mapping.Namespace != null) hashCode ^= this.Mapping.Namespace.GetHashCode(); return hashCode; } } } }
-1
dotnet/runtime
66,321
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug
Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
stephentoub
2022-03-08T01:37:40Z
2022-03-08T19:24:48Z
446a0d610d4479fa9ba58ec14a89132a18ed33c4
b6c5a12cfa92e06734286bd991e7cca87ded1e24
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug. Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
./src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ArchitectureSpecificFieldLayoutTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Internal.TypeSystem.Ecma; using Internal.TypeSystem; using Xunit; namespace TypeSystemTests { public class ArchitectureSpecificFieldLayoutTests { TestTypeSystemContext _contextX86; ModuleDesc _testModuleX86; TestTypeSystemContext _contextX64; ModuleDesc _testModuleX64; TestTypeSystemContext _contextARM; ModuleDesc _testModuleARM; public ArchitectureSpecificFieldLayoutTests() { _contextX64 = new TestTypeSystemContext(TargetArchitecture.X64); var systemModuleX64 = _contextX64.CreateModuleForSimpleName("CoreTestAssembly"); _contextX64.SetSystemModule(systemModuleX64); _testModuleX64 = systemModuleX64; _contextARM = new TestTypeSystemContext(TargetArchitecture.ARM); var systemModuleARM = _contextARM.CreateModuleForSimpleName("CoreTestAssembly"); _contextARM.SetSystemModule(systemModuleARM); _testModuleARM = systemModuleARM; _contextX86 = new TestTypeSystemContext(TargetArchitecture.X86); var systemModuleX86 = _contextX86.CreateModuleForSimpleName("CoreTestAssembly"); _contextX86.SetSystemModule(systemModuleX86); _testModuleX86 = systemModuleX86; } [Fact] public void TestInstanceLayoutDoubleBool() { MetadataType tX64 = _testModuleX64.GetType("Sequential", "ClassDoubleBool"); MetadataType tX86 = _testModuleX86.GetType("Sequential", "ClassDoubleBool"); MetadataType tARM = _testModuleARM.GetType("Sequential", "ClassDoubleBool"); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x11, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0xD, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0xD, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x18, tX64.InstanceByteCount.AsInt); Assert.Equal(0x10, tARM.InstanceByteCount.AsInt); Assert.Equal(0x10, tX86.InstanceByteCount.AsInt); } [Fact] public void TestInstanceLayoutBoolDoubleBool() { MetadataType tX64 = _testModuleX64.GetType("Sequential", "ClassBoolDoubleBool"); MetadataType tX86 = _testModuleX86.GetType("Sequential", "ClassBoolDoubleBool"); MetadataType tARM = _testModuleARM.GetType("Sequential", "ClassBoolDoubleBool"); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x19, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x15, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x15, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x20, tX64.InstanceByteCount.AsInt); Assert.Equal(0x18, tARM.InstanceByteCount.AsInt); Assert.Equal(0x18, tX86.InstanceByteCount.AsInt); } [Fact] public void TestAlignmentBehavior_LongIntEnumStruct() { string _namespace = "EnumAlignment"; string _type = "LongIntEnumStruct"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x20, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x20, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x20, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x20, tX64.InstanceByteCount.AsInt); Assert.Equal(0x20, tARM.InstanceByteCount.AsInt); Assert.Equal(0x20, tX86.InstanceByteCount.AsInt); Assert.Equal(0x8, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x8, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x20, tX64.InstanceFieldSize.AsInt); Assert.Equal(0x20, tARM.InstanceFieldSize.AsInt); Assert.Equal(0x20, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x8, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x10, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x10, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x10, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0x18, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0x18, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0x18, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x8, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x8, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x8, tARMFieldStruct.GetField("_struct").Offset.AsInt); } [Fact] public void TestAlignmentBehavior_IntShortEnumStruct() { string _namespace = "EnumAlignment"; string _type = "IntShortEnumStruct"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x10, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x10, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x10, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x10, tX64.InstanceByteCount.AsInt); Assert.Equal(0x10, tARM.InstanceByteCount.AsInt); Assert.Equal(0x10, tX86.InstanceByteCount.AsInt); Assert.Equal(0x4, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x10, tX64.InstanceFieldSize.AsInt); Assert.Equal(0x10, tARM.InstanceFieldSize.AsInt); Assert.Equal(0x10, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x4, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x8, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x8, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0xC, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0xC, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0xC, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x4, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tARMFieldStruct.GetField("_struct").Offset.AsInt); } [Fact] public void TestAlignmentBehavior_ShortByteEnumStruct() { string _namespace = "EnumAlignment"; string _type = "ShortByteEnumStruct"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tX64.InstanceByteCount.AsInt); Assert.Equal(0x8, tARM.InstanceByteCount.AsInt); Assert.Equal(0x8, tX86.InstanceByteCount.AsInt); Assert.Equal(0x2, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x2, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x2, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x8, tX64.InstanceFieldSize.AsInt); Assert.Equal(0x8, tARM.InstanceFieldSize.AsInt); Assert.Equal(0x8, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x2, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x2, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x2, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x4, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x4, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0x6, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0x6, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0x6, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x2, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x2, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x2, tARMFieldStruct.GetField("_struct").Offset.AsInt); } [Fact] public void TestAlignmentBehavior_LongIntEnumStructAuto() { string _namespace = "EnumAlignment"; string _type = "LongIntEnumStructAuto"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x18, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x18, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x18, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x18, tX64.InstanceByteCount.AsInt); Assert.Equal(0x18, tARM.InstanceByteCount.AsInt); Assert.Equal(0x18, tX86.InstanceByteCount.AsInt); Assert.Equal(0x8, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x18, tX64.InstanceFieldSize.AsInt); Assert.Equal(0x18, tARM.InstanceFieldSize.AsInt); Assert.Equal(0x18, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x10, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x10, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x10, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x8, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x8, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0x14, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0x14, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0x14, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x8, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x8, tARMFieldStruct.GetField("_struct").Offset.AsInt); } [Fact] public void TestAlignmentBehavior_IntShortEnumStructAuto() { string _namespace = "EnumAlignment"; string _type = "IntShortEnumStructAuto"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x10, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0xC, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0xC, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x10, tX64.InstanceByteCount.AsInt); Assert.Equal(0xC, tARM.InstanceByteCount.AsInt); Assert.Equal(0xC, tX86.InstanceByteCount.AsInt); Assert.Equal(0x8, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x10, tX64.InstanceFieldSize.AsInt); Assert.Equal(0xC, tARM.InstanceFieldSize.AsInt); Assert.Equal(0xC, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x8, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x4, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x4, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0xA, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0xA, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0xA, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x8, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tARMFieldStruct.GetField("_struct").Offset.AsInt); } [Fact] public void TestAlignmentBehavior_ShortByteEnumStructAuto() { string _namespace = "EnumAlignment"; string _type = "ShortByteEnumStructAuto"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tX64.InstanceByteCount.AsInt); Assert.Equal(0x8, tARM.InstanceByteCount.AsInt); Assert.Equal(0x8, tX86.InstanceByteCount.AsInt); Assert.Equal(0x8, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x8, tX64.InstanceFieldSize.AsInt); Assert.Equal(0x8, tARM.InstanceFieldSize.AsInt); Assert.Equal(0x8, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x4, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x2, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x2, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x2, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0x5, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0x5, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0x5, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x8, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tARMFieldStruct.GetField("_struct").Offset.AsInt); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Internal.TypeSystem.Ecma; using Internal.TypeSystem; using Xunit; namespace TypeSystemTests { public class ArchitectureSpecificFieldLayoutTests { TestTypeSystemContext _contextX86; ModuleDesc _testModuleX86; TestTypeSystemContext _contextX64; ModuleDesc _testModuleX64; TestTypeSystemContext _contextARM; ModuleDesc _testModuleARM; public ArchitectureSpecificFieldLayoutTests() { _contextX64 = new TestTypeSystemContext(TargetArchitecture.X64); var systemModuleX64 = _contextX64.CreateModuleForSimpleName("CoreTestAssembly"); _contextX64.SetSystemModule(systemModuleX64); _testModuleX64 = systemModuleX64; _contextARM = new TestTypeSystemContext(TargetArchitecture.ARM); var systemModuleARM = _contextARM.CreateModuleForSimpleName("CoreTestAssembly"); _contextARM.SetSystemModule(systemModuleARM); _testModuleARM = systemModuleARM; _contextX86 = new TestTypeSystemContext(TargetArchitecture.X86); var systemModuleX86 = _contextX86.CreateModuleForSimpleName("CoreTestAssembly"); _contextX86.SetSystemModule(systemModuleX86); _testModuleX86 = systemModuleX86; } [Fact] public void TestInstanceLayoutDoubleBool() { MetadataType tX64 = _testModuleX64.GetType("Sequential", "ClassDoubleBool"); MetadataType tX86 = _testModuleX86.GetType("Sequential", "ClassDoubleBool"); MetadataType tARM = _testModuleARM.GetType("Sequential", "ClassDoubleBool"); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x11, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0xD, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0xD, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x18, tX64.InstanceByteCount.AsInt); Assert.Equal(0x10, tARM.InstanceByteCount.AsInt); Assert.Equal(0x10, tX86.InstanceByteCount.AsInt); } [Fact] public void TestInstanceLayoutBoolDoubleBool() { MetadataType tX64 = _testModuleX64.GetType("Sequential", "ClassBoolDoubleBool"); MetadataType tX86 = _testModuleX86.GetType("Sequential", "ClassBoolDoubleBool"); MetadataType tARM = _testModuleARM.GetType("Sequential", "ClassBoolDoubleBool"); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x19, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x15, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x15, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x20, tX64.InstanceByteCount.AsInt); Assert.Equal(0x18, tARM.InstanceByteCount.AsInt); Assert.Equal(0x18, tX86.InstanceByteCount.AsInt); } [Fact] public void TestAlignmentBehavior_LongIntEnumStruct() { string _namespace = "EnumAlignment"; string _type = "LongIntEnumStruct"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x20, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x20, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x20, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x20, tX64.InstanceByteCount.AsInt); Assert.Equal(0x20, tARM.InstanceByteCount.AsInt); Assert.Equal(0x20, tX86.InstanceByteCount.AsInt); Assert.Equal(0x8, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x8, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x20, tX64.InstanceFieldSize.AsInt); Assert.Equal(0x20, tARM.InstanceFieldSize.AsInt); Assert.Equal(0x20, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x8, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x10, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x10, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x10, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0x18, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0x18, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0x18, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x8, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x8, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x8, tARMFieldStruct.GetField("_struct").Offset.AsInt); } [Fact] public void TestAlignmentBehavior_IntShortEnumStruct() { string _namespace = "EnumAlignment"; string _type = "IntShortEnumStruct"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x10, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x10, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x10, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x10, tX64.InstanceByteCount.AsInt); Assert.Equal(0x10, tARM.InstanceByteCount.AsInt); Assert.Equal(0x10, tX86.InstanceByteCount.AsInt); Assert.Equal(0x4, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x10, tX64.InstanceFieldSize.AsInt); Assert.Equal(0x10, tARM.InstanceFieldSize.AsInt); Assert.Equal(0x10, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x4, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x8, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x8, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0xC, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0xC, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0xC, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x4, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tARMFieldStruct.GetField("_struct").Offset.AsInt); } [Fact] public void TestAlignmentBehavior_ShortByteEnumStruct() { string _namespace = "EnumAlignment"; string _type = "ShortByteEnumStruct"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tX64.InstanceByteCount.AsInt); Assert.Equal(0x8, tARM.InstanceByteCount.AsInt); Assert.Equal(0x8, tX86.InstanceByteCount.AsInt); Assert.Equal(0x2, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x2, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x2, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x8, tX64.InstanceFieldSize.AsInt); Assert.Equal(0x8, tARM.InstanceFieldSize.AsInt); Assert.Equal(0x8, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x2, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x2, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x2, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x4, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x4, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0x6, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0x6, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0x6, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x2, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x2, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x2, tARMFieldStruct.GetField("_struct").Offset.AsInt); } [Fact] public void TestAlignmentBehavior_LongIntEnumStructAuto() { string _namespace = "EnumAlignment"; string _type = "LongIntEnumStructAuto"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x18, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x18, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x18, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x18, tX64.InstanceByteCount.AsInt); Assert.Equal(0x18, tARM.InstanceByteCount.AsInt); Assert.Equal(0x18, tX86.InstanceByteCount.AsInt); Assert.Equal(0x8, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x8, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x18, tX64.InstanceFieldSize.AsInt); Assert.Equal(0x18, tARM.InstanceFieldSize.AsInt); Assert.Equal(0x18, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x10, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x10, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x10, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x8, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x8, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0x14, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0x14, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0x14, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x8, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x8, tARMFieldStruct.GetField("_struct").Offset.AsInt); } [Fact] public void TestAlignmentBehavior_IntShortEnumStructAuto() { string _namespace = "EnumAlignment"; string _type = "IntShortEnumStructAuto"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x10, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0xC, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0xC, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x10, tX64.InstanceByteCount.AsInt); Assert.Equal(0xC, tARM.InstanceByteCount.AsInt); Assert.Equal(0xC, tX86.InstanceByteCount.AsInt); Assert.Equal(0x8, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x10, tX64.InstanceFieldSize.AsInt); Assert.Equal(0xC, tARM.InstanceFieldSize.AsInt); Assert.Equal(0xC, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x8, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x8, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x4, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x4, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0xA, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0xA, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0xA, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x8, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tARMFieldStruct.GetField("_struct").Offset.AsInt); } [Fact] public void TestAlignmentBehavior_ShortByteEnumStructAuto() { string _namespace = "EnumAlignment"; string _type = "ShortByteEnumStructAuto"; MetadataType tX64 = _testModuleX64.GetType(_namespace, _type); MetadataType tX86 = _testModuleX86.GetType(_namespace, _type); MetadataType tARM = _testModuleARM.GetType(_namespace, _type); Assert.Equal(0x8, tX64.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceByteAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x8, tX64.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tARM.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x8, tX64.InstanceByteCount.AsInt); Assert.Equal(0x8, tARM.InstanceByteCount.AsInt); Assert.Equal(0x8, tX86.InstanceByteCount.AsInt); Assert.Equal(0x8, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x8, tX64.InstanceFieldSize.AsInt); Assert.Equal(0x8, tARM.InstanceFieldSize.AsInt); Assert.Equal(0x8, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tX86.GetField("_1").Offset.AsInt); Assert.Equal(0x4, tX64.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tARM.GetField("_2").Offset.AsInt); Assert.Equal(0x4, tX86.GetField("_2").Offset.AsInt); Assert.Equal(0x2, tX64.GetField("_3").Offset.AsInt); Assert.Equal(0x2, tARM.GetField("_3").Offset.AsInt); Assert.Equal(0x2, tX86.GetField("_3").Offset.AsInt); Assert.Equal(0x5, tX64.GetField("_4").Offset.AsInt); Assert.Equal(0x5, tARM.GetField("_4").Offset.AsInt); Assert.Equal(0x5, tX86.GetField("_4").Offset.AsInt); MetadataType tX64FieldStruct = _testModuleX64.GetType(_namespace, _type + "FieldStruct"); MetadataType tX86FieldStruct = _testModuleX86.GetType(_namespace, _type + "FieldStruct"); MetadataType tARMFieldStruct = _testModuleARM.GetType(_namespace, _type + "FieldStruct"); Assert.Equal(0x8, tX64FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tX86FieldStruct.GetField("_struct").Offset.AsInt); Assert.Equal(0x4, tARMFieldStruct.GetField("_struct").Offset.AsInt); } } }
-1
dotnet/runtime
66,321
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug
Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
stephentoub
2022-03-08T01:37:40Z
2022-03-08T19:24:48Z
446a0d610d4479fa9ba58ec14a89132a18ed33c4
b6c5a12cfa92e06734286bd991e7cca87ded1e24
Fix code coverage gaps in RegexGenerator and fix RegexCompiler bug. Noticed some easily-fillable gaps in code coverage for RegexGenerator. In adding those tests, found and fixed a bug in RegexCompiler where we were incorrectly using `Call(s_spanIndexOfSpan)` instead of `Call(s_spanIndexOfAnySpan)`.
./src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Signatures/SignatureTypeCode.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.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata { /// <summary> /// Represents the type codes that are used in signature encoding. /// </summary> public enum SignatureTypeCode : byte { /// <summary> /// Represents an invalid or uninitialized type code. It will not appear in valid signatures. /// </summary> Invalid = 0x0, /// <summary> /// Represents <see cref="System.Void"/> in signatures. /// </summary> Void = CorElementType.ELEMENT_TYPE_VOID, /// <summary> /// Represents <see cref="bool"/> in signatures. /// </summary> Boolean = CorElementType.ELEMENT_TYPE_BOOLEAN, /// <summary> /// Represents <see cref="char"/> in signatures. /// </summary> Char = CorElementType.ELEMENT_TYPE_CHAR, /// <summary> /// Represents <see cref="sbyte"/> in signatures. /// </summary> SByte = CorElementType.ELEMENT_TYPE_I1, /// <summary> /// Represents <see cref="byte"/> in signatures. /// </summary> Byte = CorElementType.ELEMENT_TYPE_U1, /// <summary> /// Represents <see cref="short"/> in signatures. /// </summary> Int16 = CorElementType.ELEMENT_TYPE_I2, /// <summary> /// Represents <see cref="ushort"/> in signatures. /// </summary> UInt16 = CorElementType.ELEMENT_TYPE_U2, /// <summary> /// Represents <see cref="int"/> in signatures. /// </summary> Int32 = CorElementType.ELEMENT_TYPE_I4, /// <summary> /// Represents <see cref="uint"/> in signatures. /// </summary> UInt32 = CorElementType.ELEMENT_TYPE_U4, /// <summary> /// Represents <see cref="long"/> in signatures. /// </summary> Int64 = CorElementType.ELEMENT_TYPE_I8, /// <summary> /// Represents <see cref="ulong"/> in signatures. /// </summary> UInt64 = CorElementType.ELEMENT_TYPE_U8, /// <summary> /// Represents <see cref="float"/> in signatures. /// </summary> Single = CorElementType.ELEMENT_TYPE_R4, /// <summary> /// Represents <see cref="double"/> in signatures. /// </summary> Double = CorElementType.ELEMENT_TYPE_R8, /// <summary> /// Represents <see cref="string"/> in signatures. /// </summary> String = CorElementType.ELEMENT_TYPE_STRING, // every type above PTR will be simple type /// <summary> /// Represents a unmanaged pointers in signatures. /// It is followed in the blob by the signature encoding of the underlying type. /// </summary> Pointer = CorElementType.ELEMENT_TYPE_PTR, // PTR <type> /// <summary> /// Represents managed pointers (byref return values and parameters) in signatures. /// It is followed in the blob by the signature encoding of the underlying type. /// </summary> ByReference = CorElementType.ELEMENT_TYPE_BYREF, // BYREF <type> // ELEMENT_TYPE_VALUETYPE (0x11) and ELEMENT_TYPE_CLASS (0x12) are unified to ELEMENT_TYPE_HANDLE. /// <summary> /// Represents a generic type parameter used within a signature. /// </summary> GenericTypeParameter = CorElementType.ELEMENT_TYPE_VAR, // a class type variable VAR <U1> /// <summary> /// Represents a generalized <see cref="System.Array"/> in signatures. /// </summary> Array = CorElementType.ELEMENT_TYPE_ARRAY, // MDARRAY <type> <rank> <bcount> <bound1> ... <lbcount> <lb1> ... /// <summary> /// Represents the instantiation of a generic type in signatures. /// </summary> GenericTypeInstance = CorElementType.ELEMENT_TYPE_GENERICINST, // GENERICINST <generic type> <argCnt> <arg1> ... <argn> // Doc issue: We can't use <see cref> because System.TypedReference isn't portable. /// <summary> /// Represents a System.TypedReference in signatures. /// </summary> TypedReference = CorElementType.ELEMENT_TYPE_TYPEDBYREF, // TYPEDREF (it takes no args) a typed reference to some other type /// <summary> /// Represents a <see cref="System.IntPtr"/> in signatures. /// </summary> IntPtr = CorElementType.ELEMENT_TYPE_I, /// <summary> /// Represents a <see cref="System.UIntPtr"/> in signatures. /// </summary> UIntPtr = CorElementType.ELEMENT_TYPE_U, /// <summary> /// Represents function pointer types in signatures. /// </summary> FunctionPointer = CorElementType.ELEMENT_TYPE_FNPTR, // FNPTR <complete sig for the function including calling convention> /// <summary> /// Represents <see cref="object"/> /// </summary> Object = CorElementType.ELEMENT_TYPE_OBJECT, /// <summary> /// Represents a single dimensional <see cref="System.Array"/> with 0 lower bound. /// </summary> SZArray = CorElementType.ELEMENT_TYPE_SZARRAY, // SZARRAY <type> /// <summary> /// Represents a generic method parameter used within a signature. /// </summary> GenericMethodParameter = CorElementType.ELEMENT_TYPE_MVAR, // a method type variable MVAR <U1> // This is only for binding /// <summary> /// Represents a custom modifier applied to a type within a signature that the caller must understand. /// </summary> RequiredModifier = CorElementType.ELEMENT_TYPE_CMOD_REQD, // required C modifier : E_T_CMOD_REQD <mdTypeRef/mdTypeDef> /// <summary> /// Represents a custom modifier applied to a type within a signature that the caller can ignore. /// </summary> OptionalModifier = CorElementType.ELEMENT_TYPE_CMOD_OPT, // optional C modifier : E_T_CMOD_OPT <mdTypeRef/mdTypeDef> /// <summary> /// Precedes a type <see cref="EntityHandle"/> in signatures. /// </summary> /// <remarks> /// In raw metadata, this will be encoded as either ELEMENT_TYPE_CLASS (0x12) for reference /// types and ELEMENT_TYPE_VALUETYPE (0x11) for value types. This is collapsed to a single /// code because Windows Runtime projections can project from class to value type or vice-versa /// and the raw code is misleading in those cases. /// </remarks> TypeHandle = CorElementType.ELEMENT_TYPE_HANDLE, // CLASS | VALUETYPE <class Token> /// <summary> /// Represents a marker to indicate the end of fixed arguments and the beginning of variable arguments. /// </summary> Sentinel = CorElementType.ELEMENT_TYPE_SENTINEL, /// <summary> /// Represents a local variable that is pinned by garbage collector /// </summary> Pinned = CorElementType.ELEMENT_TYPE_PINNED, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata { /// <summary> /// Represents the type codes that are used in signature encoding. /// </summary> public enum SignatureTypeCode : byte { /// <summary> /// Represents an invalid or uninitialized type code. It will not appear in valid signatures. /// </summary> Invalid = 0x0, /// <summary> /// Represents <see cref="System.Void"/> in signatures. /// </summary> Void = CorElementType.ELEMENT_TYPE_VOID, /// <summary> /// Represents <see cref="bool"/> in signatures. /// </summary> Boolean = CorElementType.ELEMENT_TYPE_BOOLEAN, /// <summary> /// Represents <see cref="char"/> in signatures. /// </summary> Char = CorElementType.ELEMENT_TYPE_CHAR, /// <summary> /// Represents <see cref="sbyte"/> in signatures. /// </summary> SByte = CorElementType.ELEMENT_TYPE_I1, /// <summary> /// Represents <see cref="byte"/> in signatures. /// </summary> Byte = CorElementType.ELEMENT_TYPE_U1, /// <summary> /// Represents <see cref="short"/> in signatures. /// </summary> Int16 = CorElementType.ELEMENT_TYPE_I2, /// <summary> /// Represents <see cref="ushort"/> in signatures. /// </summary> UInt16 = CorElementType.ELEMENT_TYPE_U2, /// <summary> /// Represents <see cref="int"/> in signatures. /// </summary> Int32 = CorElementType.ELEMENT_TYPE_I4, /// <summary> /// Represents <see cref="uint"/> in signatures. /// </summary> UInt32 = CorElementType.ELEMENT_TYPE_U4, /// <summary> /// Represents <see cref="long"/> in signatures. /// </summary> Int64 = CorElementType.ELEMENT_TYPE_I8, /// <summary> /// Represents <see cref="ulong"/> in signatures. /// </summary> UInt64 = CorElementType.ELEMENT_TYPE_U8, /// <summary> /// Represents <see cref="float"/> in signatures. /// </summary> Single = CorElementType.ELEMENT_TYPE_R4, /// <summary> /// Represents <see cref="double"/> in signatures. /// </summary> Double = CorElementType.ELEMENT_TYPE_R8, /// <summary> /// Represents <see cref="string"/> in signatures. /// </summary> String = CorElementType.ELEMENT_TYPE_STRING, // every type above PTR will be simple type /// <summary> /// Represents a unmanaged pointers in signatures. /// It is followed in the blob by the signature encoding of the underlying type. /// </summary> Pointer = CorElementType.ELEMENT_TYPE_PTR, // PTR <type> /// <summary> /// Represents managed pointers (byref return values and parameters) in signatures. /// It is followed in the blob by the signature encoding of the underlying type. /// </summary> ByReference = CorElementType.ELEMENT_TYPE_BYREF, // BYREF <type> // ELEMENT_TYPE_VALUETYPE (0x11) and ELEMENT_TYPE_CLASS (0x12) are unified to ELEMENT_TYPE_HANDLE. /// <summary> /// Represents a generic type parameter used within a signature. /// </summary> GenericTypeParameter = CorElementType.ELEMENT_TYPE_VAR, // a class type variable VAR <U1> /// <summary> /// Represents a generalized <see cref="System.Array"/> in signatures. /// </summary> Array = CorElementType.ELEMENT_TYPE_ARRAY, // MDARRAY <type> <rank> <bcount> <bound1> ... <lbcount> <lb1> ... /// <summary> /// Represents the instantiation of a generic type in signatures. /// </summary> GenericTypeInstance = CorElementType.ELEMENT_TYPE_GENERICINST, // GENERICINST <generic type> <argCnt> <arg1> ... <argn> // Doc issue: We can't use <see cref> because System.TypedReference isn't portable. /// <summary> /// Represents a System.TypedReference in signatures. /// </summary> TypedReference = CorElementType.ELEMENT_TYPE_TYPEDBYREF, // TYPEDREF (it takes no args) a typed reference to some other type /// <summary> /// Represents a <see cref="System.IntPtr"/> in signatures. /// </summary> IntPtr = CorElementType.ELEMENT_TYPE_I, /// <summary> /// Represents a <see cref="System.UIntPtr"/> in signatures. /// </summary> UIntPtr = CorElementType.ELEMENT_TYPE_U, /// <summary> /// Represents function pointer types in signatures. /// </summary> FunctionPointer = CorElementType.ELEMENT_TYPE_FNPTR, // FNPTR <complete sig for the function including calling convention> /// <summary> /// Represents <see cref="object"/> /// </summary> Object = CorElementType.ELEMENT_TYPE_OBJECT, /// <summary> /// Represents a single dimensional <see cref="System.Array"/> with 0 lower bound. /// </summary> SZArray = CorElementType.ELEMENT_TYPE_SZARRAY, // SZARRAY <type> /// <summary> /// Represents a generic method parameter used within a signature. /// </summary> GenericMethodParameter = CorElementType.ELEMENT_TYPE_MVAR, // a method type variable MVAR <U1> // This is only for binding /// <summary> /// Represents a custom modifier applied to a type within a signature that the caller must understand. /// </summary> RequiredModifier = CorElementType.ELEMENT_TYPE_CMOD_REQD, // required C modifier : E_T_CMOD_REQD <mdTypeRef/mdTypeDef> /// <summary> /// Represents a custom modifier applied to a type within a signature that the caller can ignore. /// </summary> OptionalModifier = CorElementType.ELEMENT_TYPE_CMOD_OPT, // optional C modifier : E_T_CMOD_OPT <mdTypeRef/mdTypeDef> /// <summary> /// Precedes a type <see cref="EntityHandle"/> in signatures. /// </summary> /// <remarks> /// In raw metadata, this will be encoded as either ELEMENT_TYPE_CLASS (0x12) for reference /// types and ELEMENT_TYPE_VALUETYPE (0x11) for value types. This is collapsed to a single /// code because Windows Runtime projections can project from class to value type or vice-versa /// and the raw code is misleading in those cases. /// </remarks> TypeHandle = CorElementType.ELEMENT_TYPE_HANDLE, // CLASS | VALUETYPE <class Token> /// <summary> /// Represents a marker to indicate the end of fixed arguments and the beginning of variable arguments. /// </summary> Sentinel = CorElementType.ELEMENT_TYPE_SENTINEL, /// <summary> /// Represents a local variable that is pinned by garbage collector /// </summary> Pinned = CorElementType.ELEMENT_TYPE_PINNED, } }
-1